39 Commits
Author SHA1 Message Date
Double Sine 599ac96c30 Make compatible with openssl@1.1 2019-11-22 13:21:12 +08:00
Double Sine e61b0f9e8e Override rapidjson include path if specified 2019-08-28 15:33:28 +08:00
Double Sine a69805e470 Remove assert 2019-08-28 11:57:54 +08:00
Double Sine f1394f6aeb fix a typo 2019-08-28 11:55:49 +08:00
Double Sine 6272f56d01 Override include/lib path if specified 2019-08-28 11:03:17 +08:00
Double Sine ea583e9797 Add '--single-branch' option to make git-clone faster 2019-07-30 01:51:24 +08:00
Double Sine 316314f9bb Refactor code + Add support for 12.1.24 2019-07-30 01:30:16 +08:00
Double SineandGitHub c05f755957 Merge pull request #245 from cvno/mac
Fix undefined template error
2019-03-02 01:24:37 +08:00
cvnoandGitHub e37e72e2fa FIX undefined template error
FIX Exception.hpp:46:23: error: implicit instantiation of undefined template
2019-03-01 13:44:11 +08:00
Double Sine e4c55e0fa0 Remove navicat-activate-server 2019-02-08 12:26:45 +08:00
Double Sine b32aa80331 Fix typo 2019-02-08 12:25:39 +08:00
Double Sine 0d0c2a2ba7 Fix output format mistake 2019-02-08 12:21:35 +08:00
Double Sine e6964a1da3 Update readme 2019-02-08 12:20:31 +08:00
Double Sine ddf0ff7443 Add version message 2019-02-08 11:13:21 +08:00
Double Sine 8e74008d01 Update Makefile 2019-02-08 02:34:38 +08:00
Double Sine dd6d0713e6 Refactor code + Add support for 12.1.15 2019-02-08 02:23:00 +08:00
Double SineandGitHub e4e433ec94 Merge pull request #198 from bringtree/mac
fix bug
2018-12-20 14:39:47 +08:00
黄培松andGitHub bcce475faa fix bugs
```bash
g++ -std=c++11 -O2 -I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib -lcrypto ./navicat-patcher/Helper.cpp ./navicat-patcher/main.cpp ./navicat-patcher/Solution0.cpp ./navicat-patcher/Solution1.cpp -o ./bin/navicat-patcher
g++ -std=c++11 -O2 -I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib -lcrypto ./navicat-keygen/Helper.cpp ./navicat-keygen/main.cpp -o ./bin/navicat-keygen
./navicat-keygen/Helper.cpp:47:13: error: use of undeclared identifier 'assert'
            assert(bits_collected < 6);
            ^
./navicat-keygen/Helper.cpp:51:9: error: use of undeclared identifier 'assert'
        assert(outpos >= (retval.size() - 2));
        ^
./navicat-keygen/Helper.cpp:52:9: error: use of undeclared identifier 'assert'
        assert(outpos <= retval.size());
```
2018-12-20 14:31:57 +08:00
Double Sine 88ccb398a0 Refactor code 2018-12-19 18:00:46 +08:00
Double SineandGitHub 7e0705dd9d Merge pull request #96 from lxiaoxiang/update-readme
update readme
2018-09-11 14:17:43 +08:00
luoxiaoxiang.bj 193ae6bdfa update readme 2018-07-03 17:41:19 +08:00
Double Sine 23508443c4 Add Chinese README 2018-06-24 12:18:28 +08:00
Double Sine cae2eb95ff Update README.md 2018-06-24 12:16:29 +08:00
Double Sine 9f1f661752 Add supplement about code sign 2018-04-16 20:08:21 +08:00
Double Sine ee22a9ed24 Support Navicat 12.0.24 2018-04-15 20:06:05 +08:00
Double Sine 50fbcc52c3 Update readme 2018-03-17 16:52:03 +08:00
Double Sine 96cf594fe0 Add language selection. 2018-03-17 16:47:56 +08:00
Double Sine d24a420ce5 Support for multiple language. 2018-02-07 18:07:38 +08:00
Double Sine 41b319332a Support for Navicat 12 French version. 2018-02-07 10:29:05 +08:00
Double Sine 0ca18231b5 Update README.md for some adjustment. 2018-01-13 00:30:46 +08:00
Double Sine 1ec9c0cea9 Update README.md for better description. 2018-01-13 00:20:27 +08:00
Double Sine 83e43f5178 Update code for better customization. 2018-01-13 00:19:31 +08:00
Double Sine fc82c87597 remove old branch file 2017-12-11 20:37:18 +08:00
Double Sine 5e9a98c71d start mac branch 2017-12-11 20:31:50 +08:00
Double Sine 2e4b12b34d Update README.md 2017-12-11 13:42:16 +08:00
Double Helix ff61253d18 Update README.md 2017-12-09 14:12:51 +08:00
Double Helix 27b1c70bb3 Add description for Traditional Chinese version. 2017-12-09 02:24:38 +08:00
Double Helix 5cb6d46601 Update README.md 2017-12-08 00:56:17 +08:00
Double Helix 5adc56499e Upload project. 2017-12-07 17:11:08 +08:00
82 changed files with 3606 additions and 8760 deletions
+2 -4
View File
@@ -1,4 +1,2 @@
.vs/
.vscode/
bin/
obj/
*.DS_Store
bin/*
+233
View File
@@ -0,0 +1,233 @@
# Navicat Keygen - How does it work?
[中文版 How does it work?](HOW_DOES_IT_WORK.zh-CN.md)
## 1. Keyword Explanation.
* __Navicat Activation Public Key__
It is an __RSA-2048__ public key that Navicat used to encrypt or decrypt offline activation information.
It is stored in
```
Navicat Premium.app/Contents/Resources/rpk
```
You can see it by any kind of text editor. The content is:
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
If you have the corresponding private key, please tell me. I would be very appreciated for your generous.
__NOTICE:__
Start from __Navicat Premuim 12.0.24 for Mac__, the public key is no longer stored in
```
Navicat Premium.app/Contents/Resources/rpk
```
Instead, the public key is stored in Navicat executable file
```
Navicat Premium.app/Contents/MacOS/Navicat Premium
```
in plaintext. You can see it by searching string `"-----BEGIN PUBLIC KEY----- "`.
__NOTICE:__
Start from __Navicat Premium 12.1.14 for Mac__, the public key is still stored in the executable file in plaintext.
However, it does not load the key from the plaintext. Instead, it loads the key from a piece of ciphertext which is 0x188 bytes long. The ciphertext is
```c
const uint8_t ciphertext[0x188] = {
0xfe, 0xfd, 0xfc, 0xf4, 0xfe, 0xd2, 0xf8, 0xf4, 0xf1, 0xd3, 0xde, 0xc7, 0xdf, 0xd3, 0xd0, 0xfd,
0x8a, 0xc3, 0x85, 0xf4, 0xf6, 0xe9, 0xfc, 0xfc, 0xf2, 0xf5, 0xfa, 0xf5, 0xf6, 0xe9, 0x81, 0xfb,
0xfe, 0xfd, 0xfc, 0xf4, 0xf4, 0xdf, 0xf2, 0xf9, 0xf2, 0xe5, 0xf0, 0xf7, 0xc0, 0x89, 0xdd, 0xcb,
0xf5, 0x87, 0xe6, 0xdd, 0xf4, 0xd9, 0xf8, 0xfb, 0xde, 0xf9, 0xcf, 0xc5, 0x8f, 0x80, 0x80, 0xf3,
0xc2, 0xd0, 0xe2, 0x8f, 0xfa, 0x8a, 0xdd, 0xf3, 0xd7, 0xdc, 0x86, 0xdc, 0xf0, 0x81, 0xc0, 0xea,
0xd0, 0xd9, 0xf9, 0xd8, 0xda, 0xf2, 0xd0, 0xfd, 0xc3, 0xf6, 0xf3, 0x82, 0xf2, 0x81, 0xef, 0xf2,
0xe0, 0xf9, 0xf2, 0xd3, 0x8f, 0xd7, 0xe9, 0xfb, 0xca, 0x86, 0xde, 0xfc, 0xf3, 0xd5, 0xdd, 0xf4,
0xc7, 0x80, 0xf7, 0xd5, 0xf2, 0xc1, 0xde, 0xcc, 0xc0, 0xc7, 0xf0, 0xd0, 0xd0, 0xd1, 0xd7, 0xcc,
0xd2, 0x81, 0xc1, 0x83, 0xdd, 0xd5, 0x8a, 0x8f, 0x81, 0xe1, 0xf4, 0xd9, 0xf3, 0xd7, 0xca, 0xef,
0xf9, 0xdf, 0xe1, 0xee, 0xf0, 0xe9, 0xd1, 0xca, 0xf2, 0xe3, 0xf8, 0xf0, 0x83, 0xde, 0xfb, 0xd7,
0xf1, 0xc4, 0xfa, 0x85, 0xf2, 0xdd, 0xdd, 0xfd, 0x85, 0x86, 0xc7, 0xf9, 0xc4, 0xc9, 0xf4, 0xf8,
0xd4, 0xd9, 0xe6, 0xd2, 0xf6, 0xc1, 0xc1, 0xf9, 0xe0, 0xe4, 0xf7, 0xe4, 0xfd, 0xf1, 0xf6, 0xfc,
0xe1, 0x84, 0xe4, 0xd1, 0xed, 0xfe, 0xdb, 0xe8, 0xdd, 0xe1, 0x85, 0xd0, 0xc5, 0xd2, 0x8a, 0x8e,
0xd5, 0xdd, 0xe3, 0xdb, 0xd0, 0xe1, 0xd0, 0xf6, 0xc6, 0xee, 0xe6, 0xf7, 0xda, 0xf1, 0xdb, 0xc9,
0x8b, 0xee, 0xcd, 0xdf, 0xff, 0xe8, 0xdd, 0xca, 0x82, 0xdb, 0xf1, 0x82, 0xc3, 0xed, 0xc9, 0xcc,
0xc0, 0xf2, 0xd6, 0xdf, 0x83, 0xe9, 0xf3, 0xce, 0xea, 0xfa, 0xdf, 0xf8, 0xd9, 0xff, 0xec, 0x88,
0xe4, 0xe4, 0xfd, 0x80, 0xc5, 0xce, 0xfa, 0xd2, 0xf4, 0xd8, 0x84, 0xff, 0xe5, 0xf3, 0xcb, 0xc2,
0xfe, 0xc0, 0xc4, 0xfa, 0xde, 0xdd, 0xd5, 0xc9, 0xc5, 0xd5, 0xdf, 0xe3, 0xdd, 0xc1, 0xcb, 0xdd,
0xfc, 0xf7, 0x83, 0xf8, 0xda, 0xc1, 0xd4, 0xe3, 0xfe, 0xc2, 0xef, 0xf8, 0xf2, 0xea, 0x8a, 0xd2,
0xc7, 0xf2, 0xf0, 0xc2, 0xfb, 0x89, 0xdc, 0xeb, 0xd1, 0xf7, 0xcc, 0xe2, 0xd1, 0xfc, 0xd4, 0xce,
0xea, 0xcd, 0xe4, 0x87, 0xe0, 0xcc, 0x8d, 0xf5, 0xc7, 0x85, 0x87, 0xda, 0xcf, 0xde, 0x89, 0xcd,
0xe5, 0xfd, 0xe7, 0x83, 0xda, 0xdb, 0xfe, 0xf4, 0x84, 0xec, 0xf6, 0xee, 0xfd, 0xea, 0xf1, 0xf5,
0xf5, 0xfc, 0xe6, 0xd0, 0x86, 0xdf, 0xc3, 0xe2, 0xe4, 0xd5, 0xd7, 0xe4, 0xe4, 0xce, 0xd4, 0xce,
0x82, 0xda, 0xc7, 0xda, 0x80, 0xcb, 0xee, 0x8c, 0xd0, 0xde, 0xcd, 0xda, 0xdd, 0xcd, 0xcc, 0xeb,
0xd2, 0xc3, 0xfc, 0xf2, 0xf6, 0xe9, 0xf8, 0xf8
};
```
The ciphertext is encrypted by XOR encryption where XOR key is
```
\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba
```
* __Request Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the ciphertext of __Offline Activation Request Information__ encrypted by __Navicat Activation Public Key__.
* __Offline Activation Request Information__
It is just a JSON-style UTF-8 string which contains 3 items. Respectively they are `"K"`, `"DI"` and `"P"`, which represent __snKey__, __DeviceIdentifier__, __Platform__.
Example:
```
{ "K": "xxxxxxxxxxxxxxxx", "P": "Mac 10.13", "DI": "xxxxxxxxxxxxxxxxxxxx" }
```
* __Activation Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the ciphertext of __Offline Activation Response Information__ encrypted by __Navicat Activation Private Key__ which, so far, we don't know.
* __Offline Activation Response Information__
Just like __Offline Activation Request Information__, it is also a JSON-style UTF-8 string. But it contains 5 items. Respectively they are `"K"`, `"N"`, `"O"`, `"T"`, '`DI`'.
`"K"` and `"DI"` has the same meaning mentioned in __Offline Activation Request Information__ and must be same with the corresponding items in __Offline Activation Request Information__.
`"N"`, `"O"`, `"T"` represent __Name__, __Organization__, __Time__ respectively. __Name__ and __Organization__ are string and the type of __Time__ can be string or integer (Thanks for discoveries from @Wizr, issue #10).
Differ from Navicat Windows version, `"T"` is mandatory and must have -1 ~ +4 days difference from current time.
Example:
```
{
"DI" : "xxxxxxxxxxxxxxxxxxxx",
"T" : "1515770827.925012",
"K" : "xxxxxxxxxxxxxxxx",
"N" : "DoubleLabyrinth",
"O" : "Shadow"
}
```
* __snKey__
It is a 4-block-long string, while every block is 4-chars-long.
__snKey__ is generated by 10-bytes-long data. In order to explain it easily, I use __uint8_t data[10]__ to represent the 10-bytes-long data.
1. __data[0]__ and __data[1]__ must be `0x68` and `0x2A` respectively.
These two bytes are Naivcat signature number.
2. __data[2]__, __data[3]__ and __data[4]__ can be any byte. Just set them whatever you want.
3. __data[5]__ and __data[6]__ are related with your Navicat product language.
| Language | data[5] | data[6] | Discoverer |
|------------|-----------|-----------|-----------------|
| English | 0xAC | 0x88 | |
| 简体中文 | 0xCE | 0x32 | |
| 繁體中文 | 0xAA | 0x99 | |
| 日本語 | 0xAD | 0x82 | @dragonflylee |
| Polski | 0xBB | 0x55 | @dragonflylee |
| Español | 0xAE | 0x10 | @dragonflylee |
| Français | 0xFA | 0x20 | @Deltafox79 |
| Deutsch | 0xB1 | 0x60 | @dragonflylee |
| 한국어 | 0xB5 | 0x60 | @dragonflylee |
| Русский | 0xEE | 0x16 | @dragonflylee |
| Português | 0xCD | 0x49 | @dragonflylee |
4. __data[7]__ is Navicat product ID. (Thanks @dragonflylee and @Deltafox79)
|Product Name |Enterprise|Standard|Educational|Essentials|
|---------------------|:--------:|:------:|:---------:|:--------:|
|Navicat Report Viewer|0x0B | | | |
|Navicat Data Modeler | |0x47 |0x4A | |
|Navicat Premium |0x65 | |0x66 |0x67 |
|Navicat MySQL |0x68 |0x69 |0x6A |0x6B |
|Navicat PostgreSQL |0x6C |0x6D |0x6E |0x6F |
|Navicat Oracle |0x70 |0x71 |0x72 |0x73 |
|Navicat SQL Server |0x74 |0x75 |0x76 |0x77 |
|Navicat SQLite |0x78 |0x79 |0x7A |0x7B |
|Navicat MariaDB |0x7C |0x7D |0x7E |0x7F |
|Navicat MongoDB |0x80 |0x81 |0x82 | |
5. High 4 bits of __data[8]__ represents __major version number__.
Low 4 bits is unknown, but we can use it to delay activation deadline. Possible values are `0000` or `0001`.
__Example:__
For __Navicat 12 x64__: High 4 bits must be `1100`, which is the binary of number `12`.
For __Navicat 11 x64__: High 4 bits must be `1011`, which is the binary of number `11`.
6. __data[9]__ is unknown, but you can set it by `0xFD`, `0xFC` or `0xFB` if you want to use __not-for-resale license__.
According to symbol information in __Navicat 12 for Mac x64__ version:
* `0xFB` is __Not-For-Resale-30-days__ license.
* `0xFC` is __Not-For-Resale-90-days__ license.
* `0xFD` is __Not-For-Resale-365-days__ license.
* `0xFE` is __Not-For-Resale__ license.
* `0xFF` is __Site__ license.
After that. Navicat use __DES__ with __ECB mode__ to encrypt the last 8 bytes which are from __data[2]__ to __data[9]__.
The DES key is:
```cpp
const uint8_t DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
```
Then use Base32 to encode `uint8_t data[10]` whose encode table is
```cpp
// Thanks for discoveries from @Wizr, issue #10
char EncodeTable[] = "ABCDEFGH8JKLMN9PQRSTUVWXYZ234567";
```
After encoding, you will get a 16-char-long string starting with `"NAV"`.
Finally, divide the 16-char-long string to four 4-chars-long blocks and join them with `"-"` then you will get __snKey__.
## 2. Activation Process
1. Check whether __snKey__ that user inputs is valid.
2. After user clicks `Activate`, Navicat will start online activation first. If fails, user can choose offline activation.
3. Navicat will use the __snKey__ that user inputs and some information collected from user's machine to generate __Offline Activation Request Information__. Then Navicat will encrypt it by __Navicat Activation Public Key__ and return a Base64-encoded string as __Request Code__.
4. In legal way, the __Request Code__ should be sent to Navicat official activation server by a Internet-accessible computer. And Navicat official activation server will return a legal __Activation Code__.
But now, we use keygen to play the official activation server's role.
1. According to the __Request Code__, get `"DI"` value and `"K"` value.
2. Fill __Offline Activation Response Information__ with `"K"` value, name, organization name, `"DI"` value and `"T"` value.
3. Encrypt __Offline Activation Response Information__ by __Navicat Activation Private Key__ and you will get 256-byte-long data.
4. Encode the 256-byte-long data by Base64. The result is __Activation Code__.
5. After user input __Activation Code__, offline activation is done successfully.
+230
View File
@@ -0,0 +1,230 @@
# Navicat keygen - 注册机是怎么工作的?
## 1. 关键词解释.
* __Navicat激活公钥__
这是一个2048位的RSA公钥,Navicat使用这个公钥来完成相关激活信息的加密和解密。
这个公钥储存在
```
Navicat Premium.app/Contents/Resources/rpk
```
中,你可以用任何一种文本编辑器打开并查看它。这个公钥的具体内容为:
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
如果您有相应的私钥并乐意公开的话欢迎联系我,我将非常感谢您的慷慨。
__注意:__
从 __Navicat Premium for Mac 12.0.24__ 开始,公钥不再存储在
```
Navicat Premium.app/Contents/Resources/rpk
```
中。事实上,公钥放在了Navicat的二进制执行文件
```
Navicat Premium.app/Contents/MacOS/Navicat Premium
```
中,你可以通过搜索`"-----BEGIN PUBLIC KEY-----"`来找到它。
__注意:__
从 __Navicat Premium for Mac 12.1.14__ 开始,公钥仍然以明文的方式储存在二进制可执行文件中。
但是Navicat并不从这个明文中加载公钥。事实上,密钥是从一段0x188字节长的密文中加载的。密文为:
```c
const uint8_t ciphertext[0x188] = {
0xfe, 0xfd, 0xfc, 0xf4, 0xfe, 0xd2, 0xf8, 0xf4, 0xf1, 0xd3, 0xde, 0xc7, 0xdf, 0xd3, 0xd0, 0xfd,
0x8a, 0xc3, 0x85, 0xf4, 0xf6, 0xe9, 0xfc, 0xfc, 0xf2, 0xf5, 0xfa, 0xf5, 0xf6, 0xe9, 0x81, 0xfb,
0xfe, 0xfd, 0xfc, 0xf4, 0xf4, 0xdf, 0xf2, 0xf9, 0xf2, 0xe5, 0xf0, 0xf7, 0xc0, 0x89, 0xdd, 0xcb,
0xf5, 0x87, 0xe6, 0xdd, 0xf4, 0xd9, 0xf8, 0xfb, 0xde, 0xf9, 0xcf, 0xc5, 0x8f, 0x80, 0x80, 0xf3,
0xc2, 0xd0, 0xe2, 0x8f, 0xfa, 0x8a, 0xdd, 0xf3, 0xd7, 0xdc, 0x86, 0xdc, 0xf0, 0x81, 0xc0, 0xea,
0xd0, 0xd9, 0xf9, 0xd8, 0xda, 0xf2, 0xd0, 0xfd, 0xc3, 0xf6, 0xf3, 0x82, 0xf2, 0x81, 0xef, 0xf2,
0xe0, 0xf9, 0xf2, 0xd3, 0x8f, 0xd7, 0xe9, 0xfb, 0xca, 0x86, 0xde, 0xfc, 0xf3, 0xd5, 0xdd, 0xf4,
0xc7, 0x80, 0xf7, 0xd5, 0xf2, 0xc1, 0xde, 0xcc, 0xc0, 0xc7, 0xf0, 0xd0, 0xd0, 0xd1, 0xd7, 0xcc,
0xd2, 0x81, 0xc1, 0x83, 0xdd, 0xd5, 0x8a, 0x8f, 0x81, 0xe1, 0xf4, 0xd9, 0xf3, 0xd7, 0xca, 0xef,
0xf9, 0xdf, 0xe1, 0xee, 0xf0, 0xe9, 0xd1, 0xca, 0xf2, 0xe3, 0xf8, 0xf0, 0x83, 0xde, 0xfb, 0xd7,
0xf1, 0xc4, 0xfa, 0x85, 0xf2, 0xdd, 0xdd, 0xfd, 0x85, 0x86, 0xc7, 0xf9, 0xc4, 0xc9, 0xf4, 0xf8,
0xd4, 0xd9, 0xe6, 0xd2, 0xf6, 0xc1, 0xc1, 0xf9, 0xe0, 0xe4, 0xf7, 0xe4, 0xfd, 0xf1, 0xf6, 0xfc,
0xe1, 0x84, 0xe4, 0xd1, 0xed, 0xfe, 0xdb, 0xe8, 0xdd, 0xe1, 0x85, 0xd0, 0xc5, 0xd2, 0x8a, 0x8e,
0xd5, 0xdd, 0xe3, 0xdb, 0xd0, 0xe1, 0xd0, 0xf6, 0xc6, 0xee, 0xe6, 0xf7, 0xda, 0xf1, 0xdb, 0xc9,
0x8b, 0xee, 0xcd, 0xdf, 0xff, 0xe8, 0xdd, 0xca, 0x82, 0xdb, 0xf1, 0x82, 0xc3, 0xed, 0xc9, 0xcc,
0xc0, 0xf2, 0xd6, 0xdf, 0x83, 0xe9, 0xf3, 0xce, 0xea, 0xfa, 0xdf, 0xf8, 0xd9, 0xff, 0xec, 0x88,
0xe4, 0xe4, 0xfd, 0x80, 0xc5, 0xce, 0xfa, 0xd2, 0xf4, 0xd8, 0x84, 0xff, 0xe5, 0xf3, 0xcb, 0xc2,
0xfe, 0xc0, 0xc4, 0xfa, 0xde, 0xdd, 0xd5, 0xc9, 0xc5, 0xd5, 0xdf, 0xe3, 0xdd, 0xc1, 0xcb, 0xdd,
0xfc, 0xf7, 0x83, 0xf8, 0xda, 0xc1, 0xd4, 0xe3, 0xfe, 0xc2, 0xef, 0xf8, 0xf2, 0xea, 0x8a, 0xd2,
0xc7, 0xf2, 0xf0, 0xc2, 0xfb, 0x89, 0xdc, 0xeb, 0xd1, 0xf7, 0xcc, 0xe2, 0xd1, 0xfc, 0xd4, 0xce,
0xea, 0xcd, 0xe4, 0x87, 0xe0, 0xcc, 0x8d, 0xf5, 0xc7, 0x85, 0x87, 0xda, 0xcf, 0xde, 0x89, 0xcd,
0xe5, 0xfd, 0xe7, 0x83, 0xda, 0xdb, 0xfe, 0xf4, 0x84, 0xec, 0xf6, 0xee, 0xfd, 0xea, 0xf1, 0xf5,
0xf5, 0xfc, 0xe6, 0xd0, 0x86, 0xdf, 0xc3, 0xe2, 0xe4, 0xd5, 0xd7, 0xe4, 0xe4, 0xce, 0xd4, 0xce,
0x82, 0xda, 0xc7, 0xda, 0x80, 0xcb, 0xee, 0x8c, 0xd0, 0xde, 0xcd, 0xda, 0xdd, 0xcd, 0xcc, 0xeb,
0xd2, 0xc3, 0xfc, 0xf2, 0xf6, 0xe9, 0xf8, 0xf8
};
```
这个密文是采用XOR加密得来,XOR密钥为
```
\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba
```
* __请求码__
这是一个Base64编码的字符串,代表的是长度为256字节的数据。这256字节的数据是 __离线激活信息__ 用 __Navicat激活公钥__ 加密的密文。
* __离线激活请求信息__
这是一个JSON风格的UTF-8字符串。它包含了3个Key:`"K"`、`"DI"`和`"P"`,分别代表 __序列号__、__设备识别码__(与你的电脑硬件信息相关)和 __平台__ (其实就是操作系统类型)。
例如:
```
{ "K": "xxxxxxxxxxxxxxxx", "P": "Mac 10.13", "DI": "xxxxxxxxxxxxxxxxxxxx" }
```
* __激活码__
这是一个Base64编码的字符串,代表的是长度为256字节的数据。这256字节的数据是 __离线激活回复信息__ 用 __Navicat激活私钥__ 加密的密文。目前我们不知道官方的 __Navicat激活私钥__,所以我们得替换掉软件里的公钥。
* __离线激活回复信息__
和 __离线激活请求信息__ 一样,它也是一个JSON风格的UTF-8字符串。但是它包含5个Key,分别为`"K"`、`"N"`、`"O"`、`"T"` 和 `"DI"`.
`"K"` 和 `"DI"` 的意义与 __离线激活请求信息__ 中的相同,且Value必须与 __离线激活请求信息__ 中的相同。
`"N"`、`"O"`、`"T"` 分别代表 __注册名__、__组织__、__授权时间__。
__注册名__ 和 __组织__ 的值类型为UTF-8编码的字符串。__授权时间__ 的值类型可以为字符串或整数(感谢@Wizr在issue #10中的报告)。
和Windows版本Navicat不同的是,`"T"` 项不可以省略,并且和当前时间的差距必须在-1 ~ +4天之内。
例如:
```
{
"DI" : "xxxxxxxxxxxxxxxxxxxx",
"T" : "1515770827.925012",
"K" : "xxxxxxxxxxxxxxxx",
"N" : "DoubleLabyrinth",
"O" : "Shadow"
}
```
* __序列号__
这是一个被分为了4个部分的字符串,其中每个部分都是4个字符长。
__序列号__ 是通过10个字节的数据来生成的。为了表达方便,我用 __uint8_t data[10]__ 来表示这10个字节。
1. __data[0]__ 和 __data[1]__ 必须分别为 `0x68` 和 `0x2A`。
这两个字节为Navicat的标志数。
2. __data[2]__、__data[3]__ 和 __data[4]__ 可以是任意字节,你想设成什么都行。
3. __data[5]__ 和 __data[6]__ 是Navicat的语言标志,值如下:
| 语言类型 | data[5] | data[6] | 发现者 |
|------------|:---------:|:---------:|-----------------|
| English | 0xAC | 0x88 | |
| 简体中文 | 0xCE | 0x32 | |
| 繁體中文 | 0xAA | 0x99 | |
| 日本語 | 0xAD | 0x82 | @dragonflylee |
| Polski | 0xBB | 0x55 | @dragonflylee |
| Español | 0xAE | 0x10 | @dragonflylee |
| Français | 0xFA | 0x20 | @Deltafox79 |
| Deutsch | 0xB1 | 0x60 | @dragonflylee |
| 한국어 | 0xB5 | 0x60 | @dragonflylee |
| Русский | 0xEE | 0x16 | @dragonflylee |
| Português | 0xCD | 0x49 | @dragonflylee |
4. __data[7]__ 是Navicat产品ID。(感谢 @dragonflylee 和 @Deltafox79提供的数据)
|产品名 |Enterprise|Standard|Educational|Essentials|
|---------------------|:--------:|:------:|:---------:|:--------:|
|Navicat Report Viewer|0x0B | | | |
|Navicat Data Modeler | |0x47 |0x4A | |
|Navicat Premium |0x65 | |0x66 |0x67 |
|Navicat MySQL |0x68 |0x69 |0x6A |0x6B |
|Navicat PostgreSQL |0x6C |0x6D |0x6E |0x6F |
|Navicat Oracle |0x70 |0x71 |0x72 |0x73 |
|Navicat SQL Server |0x74 |0x75 |0x76 |0x77 |
|Navicat SQLite |0x78 |0x79 |0x7A |0x7B |
|Navicat MariaDB |0x7C |0x7D |0x7E |0x7F |
|Navicat MongoDB |0x80 |0x81 |0x82 | |
5. __data[8]__ 的高4位代表 __版本号__。低4位未知,但可以用来延长激活期限,可取的值有`0000`和`0001`。
例如:
对于 __Navicat 12__: 高4位必须是`1100`,为`12`的二进制形式。
对于 __Navicat 11__: 高4位必须是`1011`,为`11`的二进制形式。
6. __data[9]__ 目前暂未知,但如果你想要 __not-for-resale license__ 的话可以设成`0xFD`、`0xFC`或`0xFB`。
根据 __Navicat 12 for Mac x64__ 版本残留的符号信息可知:
* `0xFB`是 __Not-For-Resale-30-days__ license.
* `0xFC`是 __Not-For-Resale-90-days__ license.
* `0xFD`是 __Not-For-Resale-365-days__ license.
* `0xFE`是 __Not-For-Resale__ license.
* `0xFF`是 __Site__ license.
之后Navicat使用 __ECB__ 模式的 __DES__ 算法来加密 __data[10]__ 的后8字节,也就是 __data[2]__ 到 __data[9]__ 的部分。
相应的DES密钥为:
```cpp
const uint8_t DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
```
之后使用Base32编码 __data[10]__,其中编码表改为:
```cpp
// Thanks for discoveries from @Wizr, issue #10
char EncodeTable[] = "ABCDEFGH8JKLMN9PQRSTUVWXYZ234567";
```
编码之后你应该会得到一个16字节长的字符串,并且以"NAV"打头。
将16字节的字符串分成4个4字节的小块,然后用`"-"`连接就可以得到 __序列号__。
## 2. 激活过程
1. 检查用户输入的 __序列号__ 是否合法。
2. 在用户点击了`激活`按钮之后,Navicat会先尝试在线激活。如果失败,用户可以选择离线激活。
3. Navicat会使用用户输入的 __序列号__ 以及从用户电脑收集来的信息生成 __离线激活请求信息__,然后用 __Navicat激活公钥__ 加密,并将密文用Base64编码,最后得到 __请求码__。
4. 正常流程下,__请求码__ 应该通过可联网的电脑发送给Navicat的官方激活服务器。之后Navicat的官方激活服务器会返回一个合法的 __激活码__。
但现在我们使用注册机来扮演官方激活服务器的角色,只是Navicat软件里的激活公钥得换成自己的公钥:
1. 根据 __请求码__, 获得`"DI"`值和`"K"`值。
2. 用`"K"`值、用户名、组织名和`"DI"`值填写 __离线激活回复信息__
3. 用自己的2048位RSA私钥加密 __离线激活回复信息__,你将会得到256字节的密文。
4. 用Base64编码这256字节的密文,就可以得到 __激活码__
5. 在Navicat软件中填入 __激活码__ 即可完成离线激活。
+89
View File
@@ -0,0 +1,89 @@
CC = g++
OPENSSL_INCLUDE_PATH = /usr/local/opt/openssl/include
OPENSSL_LIB_PATH = /usr/local/opt/openssl/lib
CAPSTONE_INCLUDE_PATH = #/usr/local/Cellar/capstone/4.0.1/include
CAPSTONE_LIB_PATH = #/usr/local/Cellar/capstone/4.0.1/lib
KEYSTONE_INCLUDE_PATH = #/usr/local/Cellar/keystone/0.9.1/include
KEYSTONE_LIB_PATH = #/usr/local/Cellar/keystone/0.9.1/lib
RAPIDJSON_INCLUDE_PATH = #/usr/local/Cellar/rapidjson/1.1.0/include
LIBPLIST_INCLUDE_PATH = #/usr/local/Cellar/libplist/2.0.0_1/include
LIBPLIST_LIB_PATH = #/usr/local/Cellar/libplist/2.0.0_1/lib
OUTPUT_DIR = ./bin/
COMMON_DIR = ./common/
PATCHER_DIR = ./navicat-patcher/
KEYGEN_DIR = ./navicat-keygen/
COMMON_HEADER = \
$(COMMON_DIR)Exception.hpp \
$(COMMON_DIR)ExceptionOpenssl.hpp \
$(COMMON_DIR)ExceptionSystem.hpp \
$(COMMON_DIR)ResourceOwned.hpp \
$(COMMON_DIR)ResourceTraitsOpenssl.hpp \
$(COMMON_DIR)RSACipher.hpp \
PATCHER_HEADER = \
$(PATCHER_DIR)ExceptionCapstone.hpp \
$(PATCHER_DIR)ExceptionKeystone.hpp \
$(PATCHER_DIR)ResourceTraitsCapstone.hpp \
$(PATCHER_DIR)ResourceTraitsKeystone.hpp \
$(PATCHER_DIR)ResourceTraitsUnix.hpp \
$(PATCHER_DIR)CapstoneDisassembler.hpp \
$(PATCHER_DIR)KeystoneAssembler.hpp \
$(PATCHER_DIR)X64ImageInterpreter.hpp \
$(PATCHER_DIR)PatchSolutions.hpp
PATCHER_SOURCE = \
$(PATCHER_DIR)CapstoneDisassembler.cpp \
$(PATCHER_DIR)KeystoneAssembler.cpp \
$(PATCHER_DIR)X64ImageInterpreter.cpp \
$(PATCHER_DIR)HelperIsResolvedTo.cpp \
$(PATCHER_DIR)HelperPrintMemory.cpp \
$(PATCHER_DIR)PatchSolution0.cpp \
$(PATCHER_DIR)PatchSolution1.cpp \
$(PATCHER_DIR)PatchSolution2.cpp \
$(PATCHER_DIR)main.cpp
PATCHER_BINARY = $(OUTPUT_DIR)navicat-patcher
KEYGEN_HEADER = \
$(KEYGEN_DIR)DESCipher.hpp \
$(KEYGEN_DIR)NavicatKeygen.hpp
KEYGEN_SOURCE = \
$(KEYGEN_DIR)Base64.cpp \
$(KEYGEN_DIR)main.cpp
KEYGEN_BINARY = $(OUTPUT_DIR)navicat-keygen
patcher: $(PATCHER_HEADER) $(PATCHER_SOURCE)
@if [ ! -d $(OUTPUT_DIR) ]; then mkdir -p $(OUTPUT_DIR); fi
$(CC) -std=c++17 -O2 \
-I$(OPENSSL_INCLUDE_PATH) -L$(OPENSSL_LIB_PATH) \
$(if $(CAPSTONE_INCLUDE_PATH),-I$(CAPSTONE_INCLUDE_PATH),) $(if $(CAPSTONE_LIB_PATH),-L$(CAPSTONE_LIB_PATH),) \
$(if $(KEYSTONE_INCLUDE_PATH),-I$(KEYSTONE_INCLUDE_PATH),) $(if $(KEYSTONE_LIB_PATH),-L$(KEYSTONE_LIB_PATH),) \
$(if $(LIBPLIST_INCLUDE_PATH),-I$(LIBPLIST_INCLUDE_PATH),) $(if $(LIBPLIST_LIB_PATH),-L$(LIBPLIST_LIB_PATH),) \
-lcrypto -lcapstone -lkeystone -lplist++ $(PATCHER_SOURCE) -o $(PATCHER_BINARY)
@echo
keygen: $(KEYGEM_HEADER) $(KEYGEN_SOURCE)
@if [ ! -d $(OUTPUT_DIR) ]; then mkdir -p $(OUTPUT_DIR); fi
$(CC) -std=c++17 -O2 \
-I$(OPENSSL_INCLUDE_PATH) -L$(OPENSSL_LIB_PATH) \
$(if $(RAPIDJSON_INCLUDE_PATH),-I$(RAPIDJSON_INCLUDE_PATH),) \
-lcrypto $(KEYGEN_SOURCE) -o $(KEYGEN_BINARY)
all: patcher keygen
@echo 'Done.'
.PHONY: all
clean:
ifeq ($(wildcard $(PATCHER_BINARY)), $(PATCHER_BINARY))
rm $(PATCHER_BINARY)
endif
ifeq ($(wildcard $(KEYGEN_BINARY)), $(KEYGEN_BINARY))
rm $(KEYGEN_BINARY)
endif
+299 -16
View File
@@ -4,33 +4,316 @@
This repository will tell you how Navicat offline activation works.
Previous code is archived in [`windows-archived`](https://github.com/DoubleLabyrinth/navicat-keygen/tree/windows-archived) branch for the reason that previous code contains 3rd binary libraries and it gets quite big :-(
[How does it work?](HOW_DOES_IT_WORK.md)
When you git-clone this repo, please add `--single-branch` flag so that archived branch won't be cloned to your computer, which saves your time and disk.
__NOTICE: This keygen only supports Navicat Premium.__
```console
$ git clone -b windows --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
```
## 1. How to build
## 1. How does it work?
* Before you build keygen, you should make sure you have following libs:
```
openssl
capstone
keystone
rapidjson
libplist
```
see [here](doc/how-does-it-work.md)
You can install them by
```shell
$ brew install openssl
$ brew install capstone
$ brew install keystone
$ brew install rapidjson
$ brew install libplist
```
## 2. How to build?
* Clone `mac` branch and build keygen and patcher:
see [here](doc/how-to-build.md).
```shell
$ git clone -b mac --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
$ cd navicat-keygen
$ make all
```
## 3. How to use?
You will see two executable files in `bin/` directory:
For Windows users, see [here](doc/how-to-use.windows.md).
```shell
$ ls bin/
navicat-keygen navicat-patcher
```
For Linux users, see [here](doc/how-to-use.linux.md).
## 2. How to Use
## 4. Contributor
1. Build keygen and patcher.
* Deltafox79
2. Backup all of your saved database connection configurations (with password).
* dragonflylee
3. Remove all connections, if have, that Navicat saved in `Keychain Access.app`.
* zenuo
You can find them by search with keyword `navicat` in `Keychain Access.app`.
4. Use `navicat-patcher` to replace __Navicat Activation Public Key__.
```
Usage:
navicat-patcher <Navicat installation path> [RSA-2048 Private Key File]
<Navicat installation path> Path to `Navicat Premium.app`.
Example:
/Applications/Navicat\ Premium.app/
This parameter must be specified.
[RSA-2048 Private Key File] Path to a PEM-format RSA-2048 private key file.
This parameter is optional.
```
* `<Navicat installation path>`: The path to `Navicat Premium.app`.
__This parameter must be specified.__
* `[RSA-2048 PrivateKey(PEM file)]`: The path to an RSA-2048 private key file.
__This parameter is optional.__
If not specified, `navicat-patcher` will generate a new RSA-2048 private key file `RegPrivateKey.pem` at current directory.
__Example:__
```console
$ ./navicat-patcher /Applications/Navicat\ Premium.app/
```
It has been tested on __Navicat Premium 12.1.24 For Mac Simplified Chinese__ version.
The following is an example of output:
```console
$ ./navicat-patcher /Applications/Navicat\ Premium.app/
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[*] Your Navicat version: 12.1.24
[+] PatchSolution0 ...... Ready to apply.
Keyword offset = +0x024a7db8
[-] PatchSolution1 ...... Omitted.
[+] PatchSolution2 ...... Ready to apply.
Function offset = +0x00ec9868
Keyword offset = +0x0263fd60
std::string::append(const char*) RVA = 0x000000010214b726
[*] Generating new RSA private key, it may take a long time...
[+] New RSA private key has been saved to RegPrivateKey.pem.
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA030QIDXRx372bGrne9kp
uuAqpxaxJX0x6LVaOf8+Uan2SQnFH8frnuMDRg5PjdBnFWEJGqZmRD1fNkLOhhCE
iFZWxrDgJcuEBrv5VlduQ4hlYIulcf6qilBZUaaX9Kb3R7+H8ClMb00HwLc/Iht5
bd9krhU3CT3g2ZG00GxVhEF4a/zZMDjeuQvTUeeubIeriT/2YC+w/tKfGbqWvjC6
wkbjXGbVICSiKzhzztS4BHbtQMl8v6doMhFVd/PEDNFQrbkEr3kbk/oD8AccL8iz
aV17UHt4VW2fR8tMyTvcuhTaUtWmt/tL6Z1RzCqH+KvTv8GpH8qFcty89YXja7dL
kQIDAQAB
-----END PUBLIC KEY-----
**************************************************************
* PatchSolution0 *
**************************************************************
@+0x024a7db8
Previous:
-0x0000000000000008 2d 2d 2d 2d 2d 42 45 47 -----BEG
+0x0000000000000008 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d IN PUBLIC KEY---
+0x0000000000000018 2d 2d 00 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 --.MIIBIjANBgkqh
+0x0000000000000028 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 kiG9w0BAQEFAAOCA
...
...
...
After:
-0x0000000000000008 2d 2d 2d 2d 2d 42 45 47 -----BEG
+0x0000000000000008 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d IN PUBLIC KEY---
+0x0000000000000018 2d 2d 00 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 --.MIIBIjANBgkqh
+0x0000000000000028 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 kiG9w0BAQEFAAOCA
...
...
...
**************************************************************
* PatchSolution2 *
**************************************************************
@+0x0263fd60
Previous:
+0x0000000000000000 42 49 6a 57 79 6f 65 52 52 30 4e 42 67 6b 71 6e BIjWyoeRR0NBgkqn
+0x0000000000000010 44 5a 57 78 43 67 4b 43 45 41 77 31 64 71 46 33 DZWxCgKCEAw1dqF3
+0x0000000000000020 44 54 76 4f 42 39 31 5a 48 77 65 63 4a 59 46 72 DTvOB91ZHwecJYFr
+0x0000000000000030 64 4d 31 4b 45 68 31 79 56 65 52 6f 47 71 53 64 dM1KEh1yVeRoGqSd
+0x0000000000000040 4c 4c 47 5a 47 55 6c 6e 67 69 67 33 4f 44 35 6d LLGZGUlngig3OD5m
...
...
...
@+0x00ec9868
Previous:
-0x0000000000000008 55 48 89 e5 41 57 41 56 UH..AWAV
+0x0000000000000008 53 48 83 ec 38 49 89 fe c6 45 e5 01 31 c0 88 45 SH..8I...E..1..E
+0x0000000000000018 e6 88 45 e7 48 8d 35 c5 70 61 01 48 8d 5d b0 48 ..E.H.5.pa.H.].H
+0x0000000000000028 89 df e8 49 d9 ff ff 48 8d 35 ef ed 60 01 48 89 ...I...H.5..`.H.
+0x0000000000000038 df e8 80 1e 28 01 e8 3f f4 00 00 88 45 e5 e8 b7 ....(..?....E...
+0x0000000000000048 f4 00 00 88 45 e6 e8 2f f5 00 00 88 45 e7 f6 45 ....E../....E..E
After:
-0x0000000000000008 55 48 89 e5 41 57 41 56 UH..AWAV
+0x0000000000000008 53 48 83 ec 48 48 89 fb 48 31 c0 48 89 04 24 48 SH..HH..H1.H..$H
+0x0000000000000018 89 44 24 08 48 89 44 24 10 48 8d 3c 24 48 8d 35 .D$.H.D$.H.<$H.5
+0x0000000000000028 cc 64 77 01 e8 8d 1e 28 01 48 8b 04 24 48 89 03 .dw....(.H..$H..
+0x0000000000000038 48 8b 44 24 08 48 89 43 08 48 8b 44 24 10 48 89 H.D$.H.C.H.D$.H.
+0x0000000000000048 43 10 48 89 d8 48 83 c4 48 5b 41 5e 41 5f 5d c3 C.H..H..H[A^A_].
[+] PatchSolution0 has been applied.
[+] PatchSolution2 has been applied.
**************************************************************
* Patch has been done successfully. Have fun and enjoy~~ *
* DO NOT FORGET TO SIGN NAVICAT BY YOUR CERTIFICATE!!! *
**************************************************************
```
* __FOR Navicat Premium version < 12.0.24 ONLY:__
`navicat-patcher` will abort and won't apply any patch.
You should use openssl to generate `RegPrivateKey.pem` and `rpk` file.
```console
$ openssl genrsa -out RegPrivateKey.pem 2048
$ openssl rsa -in RegPrivateKey.pem -pubout -out rpk
```
Then replace
```
/Applications/Navicat Premium.app/Contents/Resources/rpk
```
by `rpk` you just generated.
5. __Generate a self-signed code-sign certificate and always trust it.__
__Then use `codesign` to re-sign `Navicat Premium.app`.__
```console
$ codesign -f -s "Your self-signed code-sign certificate name" <path to Navicat Premium.app>
```
__NOTICE:__
"Your self-signed code-sign certificate name" is the name of your certificate in `Keychain Access.app`, not path.
__Example:__
```console
$ codesign -f -s "foobar" /Applications/Navicat\ Premium.app/
```
6. Then use `navicat-keygen` to generate __snKey__ and __Activation Code__.
```
Usage:
navicat-keygen <RSA-2048 Private Key File>
<RSA-2048 Private Key File> Path to a PEM-format RSA-2048 private key file.
This parameter must be specified.
```
* `<RSA-2048 Private Key File>`: Path to a PEM-format RSA-2048 private key file.
__This parameter must be specified.__
__Example:__
```console
$ ./navicat-keygen ./RegPrivateKey.pem
```
You will be asked to select Navicat language and give major version number. After that an randomly generated __snKey__ will be given.
```console
$ ./navicat-keygen ./RegPrivateKey.pem
***************************************************
* Navicat Keygen by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Which is your Navicat Premium language?
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVG-Z5H9-NK2L-MAZJ
Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```console
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input request code. Now __DO NOT CLOSE KEYGEN__.
7. __Disconnect your network__ and open Navicat Premium.
Find and click `Registration`.
Fill license key by __Serial number__ that the keygen gave and click `Activate`.
8. Generally online activation will fail and Navicat will ask you do `Manual Activation`, just choose it.
9. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```console
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
Nuk6pouXNhuGnqb2rBbxpDOiCFxhdJF4/gteYA/UZFUwqmhhphn3PAErvlxCtbUCf9Lzw02gfIFog3gmTB1C5JzPdeE5uuD6SAvhlQ7ZVOmdA66dvt6mDDpuf78cGio1Rpkd0D/6dLzgHnFJJPOfPtlIT5ZOLDiWkiSJm8d83+ckMBoMtcvpXCiwDIGb1KfVZwsgLojyrrO5OzakIzd2xQ8r3mEmbVbMl/zD0S5fO4agxEOp2WvpmM1cqom9Egll7kgcQG8A0z1Abqo1PrVBjjOsb/v8wy5V/469G6/uDT4AkZQSz8m/TX9ZQlZE3QBlzrJ+sTEkpMVhw3h3u6l4JQ==
Request Info:
{"K":"NAVGZ5H9NK2LMAZJ", "DI":"NGVlZjdjOTViMzYyMWI0", "P":"MAC"}
Response Info:
{"K":"NAVGZ5H9NK2LMAZJ","DI":"NGVlZjdjOTViMzYyMWI0","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1564415636}
License:
Vd4QUzEw6DPNpJLYVKV6ZNDny0gsZWCXbKyrf2nF27iTM35YUBouXEcAB/Vy355V2z++7iXe/coKmV4kNZbywlBchI5ts7gOHnhXWzBYQ3yKsBYKob/7sxaiw7CXCmhM4mPLMzrp5okewCWjBjb51keZ4SA3F6j8HGIVYiZW3CAZtkjxs9uUoXvVIJr+Gt83TgU+sqiC4oSplokopAql2zWPieA9KuhPoCKiGLMvuQwv0wWWPc2HorY0AHAetsyZ8MN4utZ2ylQ9z/ZojwX1KViyh3xxnjWF7xXJljIdBA4tCi4QDqDLvTuICfUV7VeKzOUY+ZKCO0xGxkTe1HVwog==
```
10. Finally, you will get __Activation Code__ which looks like a Base64 string.
Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`.
If nothing wrong, activation should be done successfully.
+292 -16
View File
@@ -2,33 +2,309 @@
这份repo将会告诉你Navicat是怎么完成离线激活的。
由于历史代码包含第三方二进制库,且大小较大,故决定将该项目的历史代码归档到 [`windows-archived`](https://github.com/DoubleLabyrinth/navicat-keygen/tree/windows-archived) 分支。
[注册机是怎么工作的?](HOW_DOES_IT_WORK.zh-CN.md)
当你clone该仓库的时候,请使用 `--single-branch` 选项,以此避免clone到 `windows-archived` 分支,并且还可以节省你的时间和磁盘空间。
## 1. 如何编译
```console
$ git clone -b windows --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
```
* 在编译之前,你应该确保你有如下几个库:
## 1. 注册机是怎么工作的?
```
openssl
capstone
keystone
rapidjson
libplist
```
如果你有`brew`的话,你可以通过
```
$ brew install openssl
$ brew install capstone
$ brew install keystone
$ brew install rapidjson
$ brew install libplist
```
来完成它们的安装。
见[这里](doc/how-does-it-work.zh-CN.md)。
* Clone `mac` 分支,并编译keygen和patcher
## 2. 如何编译?
```bash
$ git clone -b mac --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
$ cd navicat-keygen
$ make all
```
见[这里](doc/how-to-build.zh-CN.md)。
编译完成后你会在 `bin/` 文件夹下看到两个可执行文件:
## 3. 如何使用这个注册机?
```bash
$ ls bin/
navicat-keygen navicat-patcher
```
针对 Windows 用户,请见[这里](doc/how-to-use.windows.zh-CN.md)。
## 2. 如何使用这个Keygen
针对 Linux 用户,请见[这里](doc/how-to-use.linux.zh-CN.md)
1. 编译好keygen和patcher
## 4. 贡献者
2. 备份好Navicat中所有已保存的数据库连接(包括密码)。
* Deltafox79
3. 移除所有Navicat在 `Keychain Access.app` (即钥匙链)中保存的连接,如果有的话。
* dragonflylee
你可以通过在 `Keychain Access.app` 中搜索关键词 `navicat` 来找到它们。
* zenuo
4. 使用`navicat-patcher`替换掉公钥:
```
Usage:
navicat-patcher <Navicat installation path> [RSA-2048 Private Key File]
<Navicat installation path> Path to `Navicat Premium.app`.
Example:
/Applications/Navicat\ Premium.app/
This parameter must be specified.
[RSA-2048 Private Key File] Path to a PEM-format RSA-2048 private key file.
This parameter is optional.
```
* `<Navicat installation path>`: `Navicat Premium.app` 的路径。
__这个参数必须指定。__
* `[RSA-2048 PrivateKey(PEM file)]`: PEM格式的RSA-2048私钥文件路径。
__这个参数是可选的。__
如果没有指定,`navicat-patcher`将会在当前目录下生成一个新的RSA-2048私钥文件`RegPrivateKey.pem`。
__例如:__
```console
$ ./navicat-patcher /Applications/Navicat\ Premium.app/
```
__Navicat Premium For Mac 12.1.24 简体中文版__ 已通过测试。下面将是一份样例输出:
```console
$ ./navicat-patcher /Applications/Navicat\ Premium.app/
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[*] Your Navicat version: 12.1.24
[+] PatchSolution0 ...... Ready to apply.
Keyword offset = +0x024a7db8
[-] PatchSolution1 ...... Omitted.
[+] PatchSolution2 ...... Ready to apply.
Function offset = +0x00ec9868
Keyword offset = +0x0263fd60
std::string::append(const char*) RVA = 0x000000010214b726
[*] Generating new RSA private key, it may take a long time...
[+] New RSA private key has been saved to RegPrivateKey.pem.
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA030QIDXRx372bGrne9kp
uuAqpxaxJX0x6LVaOf8+Uan2SQnFH8frnuMDRg5PjdBnFWEJGqZmRD1fNkLOhhCE
iFZWxrDgJcuEBrv5VlduQ4hlYIulcf6qilBZUaaX9Kb3R7+H8ClMb00HwLc/Iht5
bd9krhU3CT3g2ZG00GxVhEF4a/zZMDjeuQvTUeeubIeriT/2YC+w/tKfGbqWvjC6
wkbjXGbVICSiKzhzztS4BHbtQMl8v6doMhFVd/PEDNFQrbkEr3kbk/oD8AccL8iz
aV17UHt4VW2fR8tMyTvcuhTaUtWmt/tL6Z1RzCqH+KvTv8GpH8qFcty89YXja7dL
kQIDAQAB
-----END PUBLIC KEY-----
**************************************************************
* PatchSolution0 *
**************************************************************
@+0x024a7db8
Previous:
-0x0000000000000008 2d 2d 2d 2d 2d 42 45 47 -----BEG
+0x0000000000000008 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d IN PUBLIC KEY---
+0x0000000000000018 2d 2d 00 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 --.MIIBIjANBgkqh
+0x0000000000000028 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 kiG9w0BAQEFAAOCA
...
...
...
After:
-0x0000000000000008 2d 2d 2d 2d 2d 42 45 47 -----BEG
+0x0000000000000008 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d IN PUBLIC KEY---
+0x0000000000000018 2d 2d 00 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 --.MIIBIjANBgkqh
+0x0000000000000028 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 kiG9w0BAQEFAAOCA
...
...
...
**************************************************************
* PatchSolution2 *
**************************************************************
@+0x0263fd60
Previous:
+0x0000000000000000 42 49 6a 57 79 6f 65 52 52 30 4e 42 67 6b 71 6e BIjWyoeRR0NBgkqn
+0x0000000000000010 44 5a 57 78 43 67 4b 43 45 41 77 31 64 71 46 33 DZWxCgKCEAw1dqF3
+0x0000000000000020 44 54 76 4f 42 39 31 5a 48 77 65 63 4a 59 46 72 DTvOB91ZHwecJYFr
+0x0000000000000030 64 4d 31 4b 45 68 31 79 56 65 52 6f 47 71 53 64 dM1KEh1yVeRoGqSd
+0x0000000000000040 4c 4c 47 5a 47 55 6c 6e 67 69 67 33 4f 44 35 6d LLGZGUlngig3OD5m
...
...
...
@+0x00ec9868
Previous:
-0x0000000000000008 55 48 89 e5 41 57 41 56 UH..AWAV
+0x0000000000000008 53 48 83 ec 38 49 89 fe c6 45 e5 01 31 c0 88 45 SH..8I...E..1..E
+0x0000000000000018 e6 88 45 e7 48 8d 35 c5 70 61 01 48 8d 5d b0 48 ..E.H.5.pa.H.].H
+0x0000000000000028 89 df e8 49 d9 ff ff 48 8d 35 ef ed 60 01 48 89 ...I...H.5..`.H.
+0x0000000000000038 df e8 80 1e 28 01 e8 3f f4 00 00 88 45 e5 e8 b7 ....(..?....E...
+0x0000000000000048 f4 00 00 88 45 e6 e8 2f f5 00 00 88 45 e7 f6 45 ....E../....E..E
After:
-0x0000000000000008 55 48 89 e5 41 57 41 56 UH..AWAV
+0x0000000000000008 53 48 83 ec 48 48 89 fb 48 31 c0 48 89 04 24 48 SH..HH..H1.H..$H
+0x0000000000000018 89 44 24 08 48 89 44 24 10 48 8d 3c 24 48 8d 35 .D$.H.D$.H.<$H.5
+0x0000000000000028 cc 64 77 01 e8 8d 1e 28 01 48 8b 04 24 48 89 03 .dw....(.H..$H..
+0x0000000000000038 48 8b 44 24 08 48 89 43 08 48 8b 44 24 10 48 89 H.D$.H.C.H.D$.H.
+0x0000000000000048 43 10 48 89 d8 48 83 c4 48 5b 41 5e 41 5f 5d c3 C.H..H..H[A^A_].
[+] PatchSolution0 has been applied.
[+] PatchSolution2 has been applied.
**************************************************************
* Patch has been done successfully. Have fun and enjoy~~ *
* DO NOT FORGET TO SIGN NAVICAT BY YOUR CERTIFICATE!!! *
**************************************************************
```
* __仅对 Navicat Premium 版本 < 12.0.24 的说明:__
如果你的Navicat版本小于12.0.24,那么`navicat-patcher`将会终止并且不会修改目标文件。
你必须使用openssl生成`RegPrivateKey.pem`和`rpk`文件:
```console
$ openssl genrsa -out RegPrivateKey.pem 2048
$ openssl rsa -in RegPrivateKey.pem -pubout -out rpk
```
接着用刚生成的`rpk`文件替换
```
/Applications/Navicat Premium.app/Contents/Resources/rpk
```
5. __生成一份自签名的代码证书,并总是信任该证书。这一步非常重要。__
__然后用`codesign`对`Navicat Premium.app`重签名。__
```console
$ codesign -f -s "Your self-signed code-sign certificate name" <path to Navicat Premium.app>
```
__注意:__
"Your self-signed code-sign certificate name"是你证书的名字,不是路径。
__例如:__
```console
$ codesign -f -s "foobar" /Applications/Navicat\ Premium.app/
```
6. 接下来使用`navicat-keygen`来生成 __序列号__ 和 __激活码__。
```
Usage:
navicat-keygen <RSA-2048 Private Key File>
<RSA-2048 Private Key File> Path to a PEM-format RSA-2048 private key file.
This parameter must be specified.
```
* `<RSA-2048 Private Key File>`: PEM格式的RSA-2048私钥文件路径。
__这个参数必须指定。__
__例如:__
```console
$ ./navicat-keygen ./RegPrivateKey.pem
```
你会被要求选择Navicat的语言以及输入主版本号。之后会随机生成一个 __序列号__。
```console
$ ./navicat-keygen ./RegPrivateKey.pem
***************************************************
* Navicat Keygen by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Which is your Navicat Premium language?
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVG-Z5H9-NK2L-MAZJ
Your name:
```
你可以使用这个 __序列号__ 暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```console
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭注册机__。
7. __断开网络__ 并打开Navicat。
找到`注册`窗口,填入注册机给你的序列号。然后点击`激活`按钮。
8. 一般来说在线激活肯定会失败,这时候Navicat会询问你是否`手动激活`,直接选吧。
9. 在`手动激活`窗口你会得到一个请求码,复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```console
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
Nuk6pouXNhuGnqb2rBbxpDOiCFxhdJF4/gteYA/UZFUwqmhhphn3PAErvlxCtbUCf9Lzw02gfIFog3gmTB1C5JzPdeE5uuD6SAvhlQ7ZVOmdA66dvt6mDDpuf78cGio1Rpkd0D/6dLzgHnFJJPOfPtlIT5ZOLDiWkiSJm8d83+ckMBoMtcvpXCiwDIGb1KfVZwsgLojyrrO5OzakIzd2xQ8r3mEmbVbMl/zD0S5fO4agxEOp2WvpmM1cqom9Egll7kgcQG8A0z1Abqo1PrVBjjOsb/v8wy5V/469G6/uDT4AkZQSz8m/TX9ZQlZE3QBlzrJ+sTEkpMVhw3h3u6l4JQ==
Request Info:
{"K":"NAVGZ5H9NK2LMAZJ", "DI":"NGVlZjdjOTViMzYyMWI0", "P":"MAC"}
Response Info:
{"K":"NAVGZ5H9NK2LMAZJ","DI":"NGVlZjdjOTViMzYyMWI0","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1564415636}
License:
Vd4QUzEw6DPNpJLYVKV6ZNDny0gsZWCXbKyrf2nF27iTM35YUBouXEcAB/Vy355V2z++7iXe/coKmV4kNZbywlBchI5ts7gOHnhXWzBYQ3yKsBYKob/7sxaiw7CXCmhM4mPLMzrp5okewCWjBjb51keZ4SA3F6j8HGIVYiZW3CAZtkjxs9uUoXvVIJr+Gt83TgU+sqiC4oSplokopAql2zWPieA9KuhPoCKiGLMvuQwv0wWWPc2HorY0AHAetsyZ8MN4utZ2ylQ9z/ZojwX1KViyh3xxnjWF7xXJljIdBA4tCi4QDqDLvTuICfUV7VeKzOUY+ZKCO0xGxkTe1HVwog==
```
10. 如果不出意外,你会得到一个看似用Base64编码的激活码。
直接复制它,并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。
如果没什么意外的话应该能成功激活。
-17
View File
@@ -1,17 +0,0 @@
#!/usr/bin/env bash
cd `dirname "$0"`
navicat_root=`pwd`
# Wine environment variables
WINEDIR="wine"
export LANG="en_US.UTF-8"
export PATH="$navicat_root/$WINEDIR/bin":"$navicat_root":"$navicat_root/$WINEDIR/drive_c/windows":"$PATH"
export LD_LIBRARY_PATH="$navicat_root/$WINEDIR/lib":"$navicat_root/lib":"$LD_LIBRARY_PATH"
export WINEDLLPATH="$navicat_root/$WINEDIR/lib/wine"
export WINELOADER="$navicat_root/$WINEDIR/bin/wine64"
export WINESERVER="$navicat_root/$WINEDIR/bin/wineserver"
export WINEPREFIX="$HOME/.navicat64"
export WINEDEBUG=-all # suppress all wine debug info
exec "${WINELOADER:-wine}" "navicat-keygen.exe" "-text" "RegPrivateKey.pem"
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
cd `dirname "$0"`
navicat_root=`pwd`
# Wine environment variables
WINEDIR="wine"
export LANG="en_US.UTF-8"
export PATH="$navicat_root/$WINEDIR/bin":"$navicat_root":"$navicat_root/$WINEDIR/drive_c/windows":"$PATH"
export LD_LIBRARY_PATH="$navicat_root/$WINEDIR/lib":"$navicat_root/lib":"$LD_LIBRARY_PATH"
export WINEDLLPATH="$navicat_root/$WINEDIR/lib/wine"
export WINELOADER="$navicat_root/$WINEDIR/bin/wine64"
export WINESERVER="$navicat_root/$WINEDIR/bin/wineserver"
export WINEPREFIX="$HOME/.navicat64"
export WINEDEBUG=-all # suppress all wine debug info
# 将斜线替换为反斜线
navicat_root_back_slash=${navicat_root//\//\\}
# 前缀
prefix='Z:\'
# 后缀
suffix='\Navicat'
# wine环境中的navicat路径
navicat_path="$prefix$navicat_root_back_slash$suffix"
# wine执行navicat-patcher.exe
exec "${WINELOADER:-wine}" "navicat-patcher.exe" "$navicat_path"
+18 -31
View File
@@ -1,48 +1,36 @@
#pragma once
#include <windows.h>
#include "xstring.hpp"
#include <vector>
#include <stddef.h> // NOLINT
#include <stdint.h> // NOLINT
namespace nkg {
class Exception {
private:
PCTSTR _SourceFile;
SIZE_T _SourceLine;
PCTSTR _Message;
std::vector<std::xstring> _Hints;
const char* pvt_File;
const char* pvt_Message;
size_t pvt_Line;
public:
Exception(PCTSTR SourceFile, SIZE_T SourceLine, PCTSTR CustomMessage) noexcept :
_SourceFile(SourceFile),
_SourceLine(SourceLine),
_Message(CustomMessage) {}
Exception(const char* File, size_t Line, const char* Message) noexcept :
pvt_File(File),
pvt_Message(Message),
pvt_Line(Line) {}
[[nodiscard]]
auto File() const noexcept {
return _SourceFile;
}
[[nodiscard]]
auto Line() const noexcept {
return _SourceLine;
const char* File() const noexcept {
return pvt_File;
}
[[nodiscard]]
auto Message() const noexcept {
return _Message;
}
auto& AddHint(const std::xstring& Hint) {
_Hints.emplace_back(Hint);
return *this;
size_t Line() const noexcept {
return pvt_Line;
}
[[nodiscard]]
const auto& Hints() const noexcept {
return _Hints;
const char* Message() const noexcept {
return pvt_Message;
}
[[nodiscard]]
@@ -51,16 +39,15 @@ namespace nkg {
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept {
virtual intptr_t ErrorCode() const noexcept {
return 0;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept {
virtual const char* ErrorString() const noexcept {
return nullptr;
}
virtual ~Exception() = default;
};
}
+15 -19
View File
@@ -1,44 +1,40 @@
#pragma once
#include "Exception.hpp"
#include <openssl/err.h>
#include "Exception.hpp"
namespace nkg {
class OpensslError final : public Exception {
private:
unsigned long _ErrorCode;
std::xstring _ErrorString;
unsigned long pvt_ErrorCode;
public:
OpensslError(PCTSTR SourceFile, SIZE_T SourceLine, unsigned long OpensslErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(OpensslErrorCode)
{
static bool CryptoStringsLoaded = false;
if (CryptoStringsLoaded == false) {
ERR_load_crypto_strings();
CryptoStringsLoaded = true;
}
_ErrorString = std::xstring(std::xstring_extension{}, ERR_reason_error_string(_ErrorCode), CP_UTF8);
}
OpensslError(const char* File, unsigned Line, unsigned long ErrorCode, const char* Message) noexcept :
Exception(File, Line, Message),
pvt_ErrorCode(ErrorCode) {}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual intptr_t ErrorCode() const noexcept override {
return pvt_ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
ERR_load_crypto_strings();
return ERR_reason_error_string(pvt_ErrorCode);
}
};
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "Exception.hpp"
#include <string.h> // NOLINT
namespace nkg {
class SystemError final : public Exception {
private:
int pvt_ErrorCode;
public:
SystemError(const char* File, unsigned Line, int ErrorCode, const char* Message) noexcept :
Exception(File, Line, Message),
pvt_ErrorCode(ErrorCode) {}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual intptr_t ErrorCode() const noexcept override {
return pvt_ErrorCode;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
return strerror(pvt_ErrorCode);
}
};
}
-28
View File
@@ -1,28 +0,0 @@
#pragma once
#include "Exception.hpp"
namespace nkg {
class UserAbortionError final : public Exception {
public:
UserAbortionError(PCTSTR SourceFile, SIZE_T SourceLine, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage) {}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept override {
return false;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return 0;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return nullptr;
}
};
}
-49
View File
@@ -1,49 +0,0 @@
#pragma once
#include "Exception.hpp"
namespace nkg {
class Win32Error final : public Exception {
private:
DWORD _ErrorCode;
std::xstring _ErrorString;
public:
Win32Error(PCTSTR SourceFile, SIZE_T SourceLine, DWORD Win32ErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(Win32ErrorCode)
{
PTSTR Text = NULL;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL,
Win32ErrorCode,
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
reinterpret_cast<PTSTR>(&Text),
0,
NULL
);
if (Text) {
_ErrorString = Text;
LocalFree(Text);
}
}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
}
};
}
+239 -230
View File
@@ -1,261 +1,270 @@
#pragma once
#include <openssl/opensslv.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include "Exception.hpp"
#include <string>
#include "ExceptionOpenssl.hpp"
#include "ResourceOwned.hpp"
#include "ResourceTraitsOpenssl.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\common\\RSACipher.hpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
enum class RSAKeyType {
PrivateKey,
PublicKey
};
namespace nkg {
enum class RSAKeyFormat {
PEM,
PKCS1
};
enum class RSAKeyType {
PrivateKey,
PublicKey
};
class RSACipher {
private:
ResourceOwned<OpensslRSATraits> pvt_RsaObj;
enum class RSAKeyFormat {
PEM,
PKCS1
};
class RSACipher final : private ResourceOwned<OpensslRSATraits> {
private:
template<RSAKeyType __Type, RSAKeyFormat __Format>
static void _WriteRSAToBIO(RSA* lpRSA, BIO* lpBIO) {
if constexpr (__Type == RSAKeyType::PrivateKey) {
if (PEM_write_bio_RSAPrivateKey(lpBIO, lpRSA, nullptr, nullptr, 0, nullptr, nullptr) == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_write_bio_RSAPrivateKey failed."));
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
static void pvt_WriteRSAToBIO(RSA* lpRSA, BIO* lpBIO) {
if constexpr (__Type == RSAKeyType::PrivateKey) {
if (PEM_write_bio_RSAPrivateKey(lpBIO, lpRSA, nullptr, nullptr, 0, nullptr, nullptr) == 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PEM_write_bio_RSAPrivateKey failed.");
}
if constexpr (__Type == RSAKeyType::PublicKey) {
if constexpr (__Format == RSAKeyFormat::PEM) {
if (PEM_write_bio_RSA_PUBKEY(lpBIO, lpRSA) == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_write_bio_RSA_PUBKEY failed."));
}
} else {
if constexpr (__Format == RSAKeyFormat::PEM) {
if (PEM_write_bio_RSA_PUBKEY(lpBIO, lpRSA) == 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PEM_write_bio_RSA_PUBKEY failed.");
}
if constexpr (__Format == RSAKeyFormat::PKCS1) {
if (PEM_write_bio_RSAPublicKey(lpBIO, lpRSA) == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_write_bio_RSAPublicKey failed."));
}
} else if constexpr (__Format == RSAKeyFormat::PKCS1) {
if (PEM_write_bio_RSAPublicKey(lpBIO, lpRSA) == 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PEM_write_bio_RSAPublicKey failed.");
}
} else {
static_assert(__Format == RSAKeyFormat::PEM || __Format == RSAKeyFormat::PKCS1);
__builtin_unreachable();
}
static_assert(__Type == RSAKeyType::PrivateKey || __Type == RSAKeyType::PublicKey);
}
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
[[nodiscard]]
static RSA* _ReadRSAFromBIO(BIO* lpBIO) {
RSA* lpRSA;
template<RSAKeyType _Type, RSAKeyFormat _Format>
[[nodiscard]]
static RSA* pvt_ReadRSAFromBIO(BIO* lpBIO) {
RSA* lpRSA;
if constexpr (__Type == RSAKeyType::PrivateKey) {
lpRSA = PEM_read_bio_RSAPrivateKey(lpBIO, nullptr, nullptr, nullptr);
if constexpr (_Type == RSAKeyType::PrivateKey) {
lpRSA = PEM_read_bio_RSAPrivateKey(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PEM_read_bio_RSAPrivateKey failed.");
}
} else {
if constexpr (_Format == RSAKeyFormat::PEM) {
lpRSA = PEM_read_bio_RSA_PUBKEY(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_read_bio_RSAPrivateKey failed."))
.AddHint(TEXT("Are you sure that you DO provide a valid RSA private key file?"));
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, " -> PEM_read_bio_RSA_PUBKEY failed.");
}
}
if constexpr (__Type == RSAKeyType::PublicKey) {
if constexpr (__Format == RSAKeyFormat::PEM) {
lpRSA = PEM_read_bio_RSA_PUBKEY(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_read_bio_RSA_PUBKEY failed."))
.AddHint(TEXT("Are you sure that you DO provide a valid RSA public key file with PEM format?"));
}
}
if constexpr (__Format == RSAKeyFormat::PKCS1) {
lpRSA = PEM_read_bio_RSAPublicKey(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_read_bio_RSAPublicKey failed."))
.AddHint(TEXT("Are you sure that you DO provide a valid RSA public key file with PKCS1 format?"));
}
}
static_assert(__Format == RSAKeyFormat::PEM || __Format == RSAKeyFormat::PKCS1);
}
static_assert(__Type == RSAKeyType::PrivateKey || __Type == RSAKeyType::PublicKey);
return lpRSA;
}
public:
RSACipher() : ResourceOwned<OpensslRSATraits>(RSA_new()) {
if (IsValid() == false) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_new failed."));
}
}
[[nodiscard]]
size_t Bits() const {
if (Get()->n == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA modulus has not been set."));
} else {
return BN_num_bits(Get()->n);
}
}
void GenerateKey(int bits, unsigned int e = RSA_F4) {
ResourceOwned<OpensslBNTraits> bn_e(BN_new());
if (bn_e.IsValid() == false) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("BN_new failed."));
}
if (!BN_set_word(bn_e, e)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BN_set_word failed."));
}
if (!RSA_generate_key_ex(Get(), bits, bn_e, nullptr)) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_generate_key_ex failed."));
}
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ExportKeyToFile(const std::xstring& FileName) const {
ResourceOwned<OpensslBIOTraits> BioFile(BIO_new_file(FileName.explicit_string(CP_UTF8).c_str(), "w"));
if (BioFile.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new_file failed."));
}
_WriteRSAToBIO<__Type, __Format>(Get(), BioFile);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
[[nodiscard]]
std::string ExportKeyString() const {
ResourceOwned<OpensslBIOTraits> BioMemory(BIO_new(BIO_s_mem()));
long StringLength;
const char* StringChars = nullptr;
if (BioMemory.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new failed."));
}
_WriteRSAToBIO<__Type, __Format>(Get(), BioMemory);
StringLength = BIO_get_mem_data(BioMemory.Get(), &StringChars);
return std::string(StringChars, StringLength);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyFromFile(const std::xstring& FileName) {
ResourceOwned<OpensslBIOTraits> BioFile(BIO_new_file(FileName.explicit_string(CP_UTF8).c_str(), "r"));
if (BioFile.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new_file failed."));
}
TakeOver(_ReadRSAFromBIO<__Type, __Format>(BioFile));
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyString(const std::string& KeyString) {
ResourceOwned<OpensslBIOTraits> BioMemory(BIO_new(BIO_s_mem()));
if (BioMemory.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new failed."));
}
if (BIO_puts(BioMemory.Get(), KeyString.c_str()) <= 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_puts failed."));
}
TakeOver(_ReadRSAFromBIO<__Type, __Format>(BioMemory));
}
template<RSAKeyType __Type = RSAKeyType::PublicKey>
size_t Encrypt(const void* lpFrom, size_t cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
if (cbFrom > INT_MAX) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Length overflowed."));
}
if constexpr (__Type == RSAKeyType::PrivateKey) {
BytesWritten = RSA_private_encrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_private_encrypt failed."));
} else if constexpr (_Format == RSAKeyFormat::PKCS1) {
lpRSA = PEM_read_bio_RSAPublicKey(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PEM_read_bio_RSAPublicKey failed.");
}
} else {
BytesWritten = RSA_public_encrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_public_encrypt failed."));
}
static_assert(_Format == RSAKeyFormat::PEM || _Format == RSAKeyFormat::PKCS1);
__builtin_unreachable();
}
return BytesWritten;
}
template<RSAKeyType __Type = RSAKeyType::PrivateKey>
size_t Decrypt(const void* lpFrom, size_t cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
return lpRSA;
}
if (cbFrom > INT_MAX) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Length overflowed."));
}
public:
if constexpr (__Type == RSAKeyType::PrivateKey) {
BytesWritten = RSA_private_decrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_private_decrypt failed."))
.AddHint(TEXT("Are your sure you DO provide a correct private key?"));
}
} else {
BytesWritten = RSA_public_decrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_public_decrypt failed."))
.AddHint(TEXT("Are your sure you DO provide a correct public key?"));
}
}
return BytesWritten;
RSACipher() : pvt_RsaObj(OpensslRSATraits{}, RSA_new()) {
if (pvt_RsaObj.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_new failed.");
}
};
}
}
[[nodiscard]]
size_t Bits() const {
#if (OPENSSL_VERSION_NUMBER & 0xffff0000) == 0x10000000 // openssl 1.0.x
if (pvt_RsaObj->n == nullptr) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "RSA modulus has not been set.");
} else {
return BN_num_bits(pvt_RsaObj->n);
}
#elif (OPENSSL_VERSION_NUMBER & 0xffff0000) == 0x10100000 // openssl 1.1.x
return RSA_bits(pvt_RsaObj);
#else
#error "Unexpected openssl version!"
#endif
}
void GenerateKey(int bits, unsigned int e = RSA_F4) {
ResourceOwned bn_e(OpensslBNTraits{}, BN_new());
if (bn_e.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "BN_new failed.");
}
if (!BN_set_word(bn_e, e)) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BN_set_word failed.");
}
if (!RSA_generate_key_ex(pvt_RsaObj, bits, bn_e, nullptr)) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_generate_key_ex failed.");
}
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ExportKeyToFile(const std::string& FileName) const {
ResourceOwned BioFile(OpensslBIOTraits{}, BIO_new_file(FileName.c_str(), "w"));
if (BioFile.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new_file failed.");
}
pvt_WriteRSAToBIO<__Type, __Format>(pvt_RsaObj, BioFile);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
[[nodiscard]]
std::string ExportKeyString() const {
ResourceOwned BioMemory(OpensslBIOTraits{}, BIO_new(BIO_s_mem()));
long StringLength;
const char* StringChars = nullptr;
if (BioMemory.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
pvt_WriteRSAToBIO<__Type, __Format>(pvt_RsaObj, BioMemory);
StringLength = BIO_get_mem_data(BioMemory, &StringChars);
return std::string(StringChars, StringLength);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyFromFile(const std::string& FileName) {
ResourceOwned BioFile(OpensslBIOTraits{}, BIO_new_file(FileName.c_str(), "r"));
if (BioFile.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new_file failed.");
}
pvt_RsaObj.TakeOver(pvt_ReadRSAFromBIO<__Type, __Format>(BioFile));
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyString(const std::string& KeyString) {
ResourceOwned BioMemory(OpensslBIOTraits{}, BIO_new(BIO_s_mem()));
RSA* NewRsaObj;
if (BioMemory.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
if (BIO_puts(BioMemory, KeyString.c_str()) <= 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_puts failed.");
}
pvt_RsaObj.TakeOver(pvt_ReadRSAFromBIO<__Type, __Format>(BioMemory));
}
template<RSAKeyType __Type = RSAKeyType::PublicKey>
size_t Encrypt(const void* lpFrom, size_t cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
if (cbFrom > INT_MAX) {
// NOLINTNEXTLINE: allow exceptions that is not derived lpFrom std::exception
throw nkg::Exception(__FILE__, __LINE__, "Length overflowed.");
}
if constexpr (__Type == RSAKeyType::PrivateKey) {
BytesWritten = RSA_private_encrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
pvt_RsaObj,
Padding
);
if (BytesWritten == -1) {
// NOLINTNEXTLINE: allow exceptions that is not derived lpFrom std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_private_encrypt failed.");
}
} else {
BytesWritten = RSA_public_encrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
pvt_RsaObj,
Padding
);
if (BytesWritten == -1) {
// NOLINTNEXTLINE: allow exceptions that is not derived lpFrom std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_public_encrypt failed.");
}
}
return BytesWritten;
}
template<RSAKeyType __Type = RSAKeyType::PrivateKey>
size_t Decrypt(const void* lpFrom, int cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
if (cbFrom > INT_MAX) {
// NOLINTNEXTLINE: allow exceptions that is not derived lpFrom std::exception
throw nkg::Exception(__FILE__, __LINE__, "Length overflowed.");
}
if constexpr (__Type == RSAKeyType::PrivateKey) {
BytesWritten = RSA_private_decrypt(
cbFrom,
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
pvt_RsaObj,
Padding
);
if (BytesWritten == -1) {
// NOLINTNEXTLINE: allow exceptions that is not derived lpFrom std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_private_decrypt failed.");
}
} else {
BytesWritten = RSA_public_decrypt(
cbFrom,
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
pvt_RsaObj,
Padding
);
if (BytesWritten == -1) {
// NOLINTNEXTLINE: allow exceptions that is not derived lpFrom std::exception
throw nkg::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_public_decrypt failed.");
}
}
return BytesWritten;
}
};
+74 -83
View File
@@ -9,37 +9,29 @@ private:
using __HandleType = typename __ResourceTraits::HandleType;
static_assert(std::is_pod_v<__HandleType>);
__HandleType _Handle;
__LambdaReleasor _Releasor;
__HandleType pvt_Handle;
__LambdaReleasor pvt_Releasor;
public:
ResourceOwned(__LambdaReleasor&& Releasor) noexcept :
_Handle(__ResourceTraits::InvalidValue),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
ResourceOwned(const __HandleType& Handle, __LambdaReleasor&& Releasor) noexcept :
_Handle(Handle),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
//
// Construct from custom releasor.
// `_Handle` will be set to an invalid value.
// ``pvt_Handle` will be set to an invalid value.
//
ResourceOwned(__ResourceTraits, __LambdaReleasor&& Releasor) noexcept :
_Handle(__ResourceTraits::InvalidValue),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
pvt_Handle(__ResourceTraits::InvalidValue),
pvt_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
//
// Construct from handle given and custom releasor.
//
ResourceOwned(__ResourceTraits, const __HandleType& Handle, __LambdaReleasor&& Releasor) noexcept :
_Handle(Handle),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
pvt_Handle(Handle),
pvt_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
// Because it takes `pvt_Handle` exclusively.
//
ResourceOwned(const ResourceOwned<__ResourceTraits, __LambdaReleasor>& Other) = delete;
@@ -47,90 +39,92 @@ public:
// ResourceOwned allows to move.
//
ResourceOwned(ResourceOwned<__ResourceTraits, __LambdaReleasor>&& Other) noexcept :
_Handle(Other._Handle),
_Releasor(std::move(Other._Releasor))
pvt_Handle(Other.pvt_Handle),
pvt_Releasor(std::move(Other.pvt_Releasor))
{
Other._Handle = __ResourceTraits::InvalidValue;
Other.pvt_Handle = __ResourceTraits::InvalidValue;
}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
// Because it takes `pvt_Handle` exclusively.
//
ResourceOwned<__ResourceTraits, __LambdaReleasor>& operator=(const ResourceOwned<__ResourceTraits, __LambdaReleasor>& Other) = delete;
ResourceOwned<__ResourceTraits, __LambdaReleasor>&
operator=(const ResourceOwned<__ResourceTraits, __LambdaReleasor>& Other) = delete;
//
// ResourceOwned allows to move.
//
ResourceOwned<__ResourceTraits, __LambdaReleasor>& operator=(ResourceOwned<__ResourceTraits, __LambdaReleasor>&& Other) noexcept {
_Handle = Other._Handle;
_Releasor = std::move(Other._Releasor);
Other._Handle = __ResourceTraits::InvalidValue;
ResourceOwned<__ResourceTraits, __LambdaReleasor>&
operator=(ResourceOwned<__ResourceTraits, __LambdaReleasor>&& Other) noexcept {
this->pvt_Handle = Other.pvt_Handle;
this->pvt_Releasor = std::move(Other.pvt_Releasor);
Other.pvt_Handle = __ResourceTraits::InvalidValue;
return *this;
}
[[nodiscard]]
operator const __HandleType&() const noexcept { // NOLINT: Allow implicit conversion.
return _Handle;
return this->pvt_Handle;
}
template<typename __AsType, bool __IsPointer = std::is_pointer_v<__HandleType>, typename = std::enable_if_t<__IsPointer>>
[[nodiscard]]
__AsType As() const noexcept {
return reinterpret_cast<__AsType>(_Handle);
return reinterpret_cast<__AsType>(this->pvt_Handle);
}
template<bool __IsPointer = std::is_pointer_v<__HandleType>, typename = typename std::enable_if_t<__IsPointer>>
[[nodiscard]]
__HandleType operator->() const noexcept {
return _Handle;
return this->pvt_Handle;
}
[[nodiscard]]
bool IsValid() const noexcept {
return __ResourceTraits::IsValid(_Handle);
return __ResourceTraits::IsValid(this->pvt_Handle);
}
[[nodiscard]]
const __HandleType& Get() const noexcept {
return _Handle;
return this->pvt_Handle;
}
template<typename __ReturnType = __HandleType*>
[[nodiscard]]
__ReturnType GetAddressOf() noexcept {
return reinterpret_cast<__ReturnType>(&_Handle);
__ReturnType GetAddress() noexcept {
return reinterpret_cast<__ReturnType>(&this->pvt_Handle);
}
void TakeOver(const __HandleType& Handle) {
if (__ResourceTraits::IsValid(_Handle) == true) {
_Releasor(_Handle);
if (__ResourceTraits::IsValid(this->pvt_Handle) == true) {
this->pvt_Releasor(this->pvt_Handle);
}
_Handle = Handle;
this->pvt_Handle = Handle;
}
void Discard() noexcept {
_Handle = __ResourceTraits::InvalidValue;
this->pvt_Handle = __ResourceTraits::InvalidValue;
}
[[nodiscard]]
__HandleType Transfer() noexcept {
__HandleType t = _Handle;
_Handle = __ResourceTraits::InvalidValue;
__HandleType t = this->pvt_Handle;
this->pvt_Handle = __ResourceTraits::InvalidValue;
return t;
}
void Release() {
if (__ResourceTraits::IsValid(_Handle)) {
_Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
if (__ResourceTraits::IsValid(this->pvt_Handle)) {
this->pvt_Releasor(this->pvt_Handle);
this->pvt_Handle = __ResourceTraits::InvalidValue;
}
}
~ResourceOwned() {
if (__ResourceTraits::IsValid(_Handle)) {
_Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
if (__ResourceTraits::IsValid(this->pvt_Handle)) {
this->pvt_Releasor(this->pvt_Handle);
this->pvt_Handle = __ResourceTraits::InvalidValue;
}
}
};
@@ -142,32 +136,27 @@ private:
using __HandleType = typename __ResourceTraits::HandleType;
static_assert(std::is_pod_v<__HandleType>);
__HandleType _Handle;
__HandleType pvt_Handle;
public:
ResourceOwned() noexcept :
_Handle(__ResourceTraits::InvalidValue) {}
ResourceOwned(const __HandleType& Handle) noexcept :
_Handle(Handle) {}
//
// Construct from custom releasor.
// `_Handle` will be set to an invalid value.
// ``pvt_Handle` will be set to an invalid value.
//
explicit ResourceOwned(__ResourceTraits) noexcept :
_Handle(__ResourceTraits::InvalidValue) {}
explicit
ResourceOwned(__ResourceTraits) noexcept :
pvt_Handle(__ResourceTraits::InvalidValue) {}
//
// Construct from handle given and custom releasor.
//
ResourceOwned(__ResourceTraits, const __HandleType& Handle) noexcept :
_Handle(Handle) {}
pvt_Handle(Handle) {}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
// Because it takes `pvt_Handle` exclusively.
//
ResourceOwned(const ResourceOwned<__ResourceTraits, void>& Other) = delete;
@@ -175,87 +164,90 @@ public:
// ResourceOwned allows to move.
//
ResourceOwned(ResourceOwned<__ResourceTraits, void>&& Other) noexcept :
_Handle(Other._Handle) {
Other._Handle = __ResourceTraits::InvalidValue;
pvt_Handle(Other.pvt_Handle)
{
Other.pvt_Handle = __ResourceTraits::InvalidValue;
}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
// Because it takes `pvt_Handle` exclusively.
//
ResourceOwned<__ResourceTraits, void>& operator=(const ResourceOwned<__ResourceTraits, void>& Other) = delete;
ResourceOwned<__ResourceTraits, void>&
operator=(const ResourceOwned<__ResourceTraits, void>& Other) = delete;
//
// ResourceOwned allows to move.
//
ResourceOwned<__ResourceTraits, void>& operator=(ResourceOwned<__ResourceTraits, void>&& Other) noexcept {
_Handle = Other._Handle;
Other._Handle = __ResourceTraits::InvalidValue;
ResourceOwned<__ResourceTraits, void>&
operator=(ResourceOwned<__ResourceTraits, void>&& Other) noexcept {
this->pvt_Handle = Other.pvt_Handle;
Other.pvt_Handle = __ResourceTraits::InvalidValue;
return *this;
}
[[nodiscard]]
operator const __HandleType&() const noexcept { // NOLINT: Allow implicit conversion.
return _Handle;
return this->pvt_Handle;
}
template<typename __AsType, bool __IsPointer = std::is_pointer_v<__HandleType>, typename = typename std::enable_if_t<__IsPointer>>
[[nodiscard]]
__AsType As() const noexcept {
return reinterpret_cast<__AsType>(_Handle);
return reinterpret_cast<__AsType>(this->pvt_Handle);
}
template<bool __IsPointer = std::is_pointer_v<__HandleType>, typename = typename std::enable_if_t<__IsPointer>>
[[nodiscard]]
__HandleType operator->() const noexcept {
return _Handle;
return this->pvt_Handle;
}
[[nodiscard]]
bool IsValid() const noexcept {
return __ResourceTraits::IsValid(_Handle);
return __ResourceTraits::IsValid(this->pvt_Handle);
}
[[nodiscard]]
const __HandleType& Get() const noexcept {
return _Handle;
return this->pvt_Handle;
}
template<typename __ReturnType = __HandleType*>
[[nodiscard]]
__ReturnType GetAddressOf() noexcept {
return reinterpret_cast<__ReturnType>(&_Handle);
__ReturnType GetAddress() noexcept {
return reinterpret_cast<__ReturnType>(&this->pvt_Handle);
}
void TakeOver(const __HandleType& Handle) {
if (__ResourceTraits::IsValid(_Handle) == true) {
__ResourceTraits::Releasor(_Handle);
if (__ResourceTraits::IsValid(this->pvt_Handle) == true) {
__ResourceTraits::Releasor(this->pvt_Handle);
}
_Handle = Handle;
this->pvt_Handle = Handle;
}
void Discard() noexcept {
_Handle = __ResourceTraits::InvalidValue;
this->pvt_Handle = __ResourceTraits::InvalidValue;
}
[[nodiscard]]
__HandleType Transfer() noexcept {
__HandleType t = _Handle;
_Handle = __ResourceTraits::InvalidValue;
__HandleType t = this->pvt_Handle;
this->pvt_Handle = __ResourceTraits::InvalidValue;
return t;
}
void Release() {
if (__ResourceTraits::IsValid(_Handle)) {
__ResourceTraits::Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
if (__ResourceTraits::IsValid(this->pvt_Handle)) {
__ResourceTraits::Releasor(this->pvt_Handle);
this->pvt_Handle = __ResourceTraits::InvalidValue;
}
}
~ResourceOwned() {
if (__ResourceTraits::IsValid(_Handle)) {
__ResourceTraits::Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
if (__ResourceTraits::IsValid(this->pvt_Handle)) {
__ResourceTraits::Releasor(this->pvt_Handle);
this->pvt_Handle = __ResourceTraits::InvalidValue;
}
}
};
@@ -310,4 +302,3 @@ struct CppDynamicArrayTraits {
delete[] Handle;
}
};
-47
View File
@@ -1,47 +0,0 @@
#pragma once
#include <windows.h>
struct GenericHandleTraits {
using HandleType = HANDLE;
static inline const HandleType InvalidValue = NULL;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
CloseHandle(Handle);
}
};
struct FileHandleTraits {
using HandleType = HANDLE;
static inline const HandleType InvalidValue = INVALID_HANDLE_VALUE;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
CloseHandle(Handle);
}
};
struct MapViewHandleTraits {
using HandleType = PVOID;
static inline const HandleType InvalidValue = NULL;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
UnmapViewOfFile(Handle);
}
};
-9
View File
@@ -1,9 +0,0 @@
#pragma once
#include <stdint.h>
#include <vector>
namespace std {
using bytearray = vector<uint8_t>;
}
-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<ItemsProjectGuid>{290c5d5e-52d2-4fef-909f-27fd95ae0af9}</ItemsProjectGuid>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectCapability Include="SourceItemsFromImports" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="$(MSBuildThisFileDirectory)bytearray.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)Exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ExceptionOpenssl.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ExceptionUser.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ExceptionWin32.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ResourceOwned.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ResourceTraitsOpenssl.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ResourceTraitsWin32.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)RSACipher.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)xstring.hpp" />
</ItemGroup>
</Project>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
</Project>
-288
View File
@@ -1,288 +0,0 @@
#pragma once
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <string>
#include <utility>
#include <stdexcept>
#include <system_error>
namespace std {
struct xstring_extension {};
#if defined(_UNICODE) || defined(UNICODE)
class xstring final : public wstring {
public:
using wstring::wstring;
using wstring::operator=;
xstring(const wstring& wstr) : wstring(wstr) {}
xstring(wstring&& wstr) : wstring(std::move(wstr)) {}
xstring(xstring_extension, const string& str, DWORD CodePage = CP_ACP) {
auto len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(static_cast<size_t>(len) - 1);
len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
xstring(xstring_extension, const char* lpstr, DWORD CodePage = CP_ACP) {
auto len = MultiByteToWideChar(CodePage, 0, lpstr, -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(static_cast<size_t>(len) - 1);
len = MultiByteToWideChar(CodePage, 0, lpstr, -1, data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
#else
class xstring final : public string {
public:
using string::string;
using string::operator=;
xstring(const string& str) : string(str) {}
xstring(string&& str) : string(std::move(str)) {}
xstring(xstring_extension, const string& str, DWORD CodePage = CP_ACP) {
if (CodePage == CP_ACP || CodePage == GetACP()) {
assign(str);
} else {
std::wstring wstr;
auto len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
}
xstring(xstring_extension, const char* lpstr, DWORD CodePage = CP_ACP) {
if (CodePage == CP_ACP || CodePage == GetACP()) {
assign(lpstr);
} else {
std::wstring wstr;
auto len = MultiByteToWideChar(CodePage, 0, lpstr, -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CodePage, 0, lpstr, -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
}
xstring(xstring_extension, const wstring& wstr) {
auto len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
xstring(xstring_extension, const wchar_t* lpwstr) {
auto len = WideCharToMultiByte(CP_ACP, 0, lpwstr, -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, lpwstr, -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
#endif
std::string explicit_string(DWORD CodePage = CP_ACP) const {
#if defined(_UNICODE) || defined(UNICODE)
std::string str;
auto len = WideCharToMultiByte(CodePage, 0, c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
str.resize(static_cast<size_t>(len) - 1);
len = WideCharToMultiByte(CodePage, 0, c_str(), -1, str.data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
return str;
#else
if (CodePage == CP_ACP || CodePage == GetACP()) {
return *this;
} else {
std::string str;
std::wstring wstr;
auto len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
len = WideCharToMultiByte(CodePage, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
str.resize(len - 1);
len = WideCharToMultiByte(CodePage, 0, wstr.c_str(), -1, str.data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
return str;
}
#endif
}
std::wstring explicit_wstring() const {
#if defined(_UNICODE) || defined(UNICODE)
return *this;
#else
std::wstring wstr;
auto len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
return wstr;
#endif
}
template<typename... __Ts>
static xstring format(const xstring& Format, __Ts&&... Args) {
xstring s;
auto len = _sctprintf(Format.c_str(), std::forward<__Ts>(Args)...);
if (len == -1) {
throw std::invalid_argument("_sctprintf failed.");
}
s.resize(len);
_sntprintf_s(s.data(), s.length() + 1, _TRUNCATE, Format.c_str(), std::forward<__Ts>(Args)...);
return s;
}
template<typename... __Ts>
static xstring format(PCTSTR lpszFormat, __Ts&& ... Args) {
xstring s;
auto len = _sctprintf(lpszFormat, std::forward<__Ts>(Args)...);
if (len == -1) {
throw std::invalid_argument("_sctprintf failed.");
}
s.resize(len);
_sntprintf_s(s.data(), s.length() + 1, _TRUNCATE, lpszFormat, std::forward<__Ts>(Args)...);
return s;
}
};
}
-284
View File
@@ -1,284 +0,0 @@
# Navicat Keygen - How does it work?
[中文版](how-does-it-work.zh-CN.md)
## 1. Keyword Explanation.
* __Navicat Activation Public Key__
It is a __RSA-2048__ public key that Navicat used to encrypt or decrypt offline activation information.
It is stored in __navicat.exe__ as a kind of resource called __RCData__. The resource name is `"ACTIVATIONPUBKEY"`. You can see it by a software called [___Resource Hacker___](http://www.angusj.com/resourcehacker/). The public key is
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
If you have the corresponding private key, you can tell me. I would be very appreciated for your generous.
__NOTICE:__
Start from __Navicat Premium 12.0.25__, Navicat do not load this public key from resource in `navicat.exe`. Instead, the public key is stored in `libcc.dll` and has been encrypted. To avoid being replaced easily, the public key is split into 5 parts:
The following content is discovered from `libcc.dll` of __Navicat Premium x64 12.0.25 Simplified Chinese version__. The SHA256 value of `libcc.dll` is `607e0a84c75966b00f3d12fa833e91d159e4f51ac51b6ba66f98d0c3cbefdce0`.
I __DO NOT__ guarantee that offset values are absolutely correct in other versions. But __char strings__ and __immediate values__ are highly possible to be found.
1. At file offset `+0x01A12090` in `libcc.dll`, stored as __char string__:
```
"D75125B70767B94145B47C1CB3C0755E
7CCB8825C5DCE0C58ACF944E08280140
9A02472FAFFD1CD77864BB821AE36766
FEEDE6A24F12662954168BFA314BD950
32B9D82445355ED7BC0B880887D650F5"
```
2. At file offset `+0x0059D799` in `libcc.dll`, stored as __immediate value__ in a instruction:
```
0xFE 0xEA 0xBC 0x01
```
In decimal: `29158142`
3. At file offset `+0x01A11DA0` in `libcc.dll`, stored as __char string__:
```
"E1CED09B9C2186BF71A70C0FE2F1E0AE
F3BD6B75277AAB20DFAF3D110F75912B
FB63AC50EC4C48689D1502715243A79F
39FF2DE2BF15CE438FF885745ED54573
850E8A9F40EE2FF505EB7476F95ADB78
3B28CA374FAC4632892AB82FB3BF4715
FCFE6E82D03731FC3762B6AAC3DF1C3B
C646FE9CD3C62663A97EE72DB932A301
312B4A7633100C8CC357262C39A2B3A6
4B224F5276D5EDBDF0804DC3AC4B8351
62BB1969EAEBADC43D2511D6E0239287
81B167A48273B953378D3D2080CC0677
7E8A2364F0234B81064C5C739A8DA28D
C5889072BF37685CBC94C2D31D0179AD
86D8E3AA8090D4F0B281BE37E0143746
E6049CCC06899401264FA471C016A96C
79815B55BBC26B43052609D9D175FBCD
E455392F10E51EC162F51CF732E6BB39
1F56BBFD8D957DF3D4C55B71CEFD54B1
9C16D458757373E698D7E693A8FC3981
5A8BF03BA05EA8C8778D38F9873D62B4
460F41ACF997C30E7C3AF025FA171B5F
5AD4D6B15E95C27F6B35AD61875E5505
449B4E"
```
4. At file offset `+0x0059D77F` in `libcc.dll`, stored as __immediate value__ in a instruction:
```
0x59 0x08 0x01 0x00
```
In decimal: `67673`
5. At file offset `+ 0x1A11D8C` in `libcc.dll`, stored as __char string__:
```
"92933"
```
Then output encrypted public key with format `"%s%d%s%d%s"`. The order is the same as it lists:
```
D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933
```
This encrypted public key can be decrypted by my another repo: [how-does-navicat-encrypt-password](https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password), while the key used is `b'23970790'`.
Example:
```cmd
E:\GitHub>git clone https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password.git
...
E:\GitHub>cd how-does-navicat-encrypt-password\python3
E:\GitHub\how-does-navicat-encrypt-password\python3>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from NavicatCrypto import *
>>> cipher = Navicat11Crypto(b'23970790')
>>> print(cipher.DecryptString('D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933'))
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
__NOTICE:__
Start from __Navicat Premium 12.1.11__, Navicat do not load the public key through the method I talked before. Of course, the public key is still stored in `libcc.dll`. When Navicat starts, it encrypts the public key by an 8-bytes-long XOR key and stores the ciphertext in static area. When verifing __Activation Code__, Navicat will regenerate the 8-bytes-long XOR key and decrypts the ciphertext in static area to get the public key.
In `libcc.dll`, x64 version, you can find some instructions that looks like:
```asm
xor eax, 'M'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'B'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'j'
mov byte_xxxxxx, al
...
...
```
* __Request Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the cipher text of __Offline Activation Request Information__ encrypted by __Navicat Activation Public Key__.
* __Offline Activation Request Information__
It is just a JSON-style ASCII string which contains 3 items. They are `"K"`, `"DI"` and `"P"` respectively, which represent __snKey__, __DeviceIdentifier__ (related with your machine), __Platform__ (OS Type).
Like
```
{"K": "xxxxxxxxxxxxxxxx", "DI": "yyyyyyyyyyyyy", "P": "WIN8"}
```
* __Activation Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the cipher text of the __Offline Activation Response Information__ encrypted by __Navicat Activation Private Key__. So far, we don't know the official activation private key and we have to replace it in `navicat.exe` and `libcc.dll`.
* __Offline Activation Response Information__
Just like __Offline Activation Request Information__, it is also a JSON-style ASCII string. But it contains 5 items. They are `"K"`, `"N"`, `"O"`, `"T"` and `"DI"` respectively.
`"K"` and `"DI"` has the same meaning that is mentioned in __Offline Activation Request Information__ and must be the same with the corresponding items in __Offline Activation Request Information__.
`"N"`, `"O"`, `"T"` represent __Name__, __Organization__, __Timestamp__ respectively. __Name__ and __Organization__ are UTF-8 strings and the type of __Timestamp__ can be string or integer. (Thanks for discoveries from @Wizr, issue #10)
`"T"` can be omitted.
* __snKey__
It is a 4-block-long string, while every block is 4-chars-long.
__snKey__ is generated by 10-bytes-long data. In order to explain it easily, I use __uint8_t data[10]__ to represent the 10-bytes-long data.
1. __data[0]__ and __data[1]__ must be `0x68` and `0x2A` respectively.
These two bytes are Naivcat signature number.
2. __data[2]__, __data[3]__ and __data[4]__ can be any byte. Just set them whatever you want.
3. __data[5]__ and __data[6]__ are product language signatures.
| Language | data[5] | data[6] | Discoverer |
|------------|:---------:|:---------:|-----------------|
| English | 0xAC | 0x88 | |
| 简体中文 | 0xCE | 0x32 | |
| 繁體中文 | 0xAA | 0x99 | |
| 日本語 | 0xAD | 0x82 | @dragonflylee |
| Polski | 0xBB | 0x55 | @dragonflylee |
| Español | 0xAE | 0x10 | @dragonflylee |
| Français | 0xFA | 0x20 | @Deltafox79 |
| Deutsch | 0xB1 | 0x60 | @dragonflylee |
| 한국어 | 0xB5 | 0x60 | @dragonflylee |
| Русский | 0xEE | 0x16 | @dragonflylee |
| Português | 0xCD | 0x49 | @dragonflylee |
4. __data[7]__ is Navicat product ID. (Thanks @dragonflylee and @Deltafox79)
|Product Name |Enterprise|Standard|Educational|Essentials|
|----------------------|:--------:|:------:|:---------:|:--------:|
|Navicat Report Viewer |0x0B | | | |
|Navicat Data Modeler 3| |0x84 |0x85 | |
|Navicat Premium |0x65 | |0x66 |0x67 |
|Navicat MySQL |0x68 |0x69 |0x6A |0x6B |
|Navicat PostgreSQL |0x6C |0x6D |0x6E |0x6F |
|Navicat Oracle |0x70 |0x71 |0x72 |0x73 |
|Navicat SQL Server |0x74 |0x75 |0x76 |0x77 |
|Navicat SQLite |0x78 |0x79 |0x7A |0x7B |
|Navicat MariaDB |0x7C |0x7D |0x7E |0x7F |
|Navicat MongoDB |0x80 |0x81 |0x82 | |
5. High 4 bits of __data[8]__ represents __major version number__.
Low 4 bits is unknown, but we can use it to delay activation deadline. Possible values are `0000` or `0001`.
__Example:__
For __Navicat 12 x64__: High 4 bits must be `1100`, which is the binary of number `12`.
For __Navicat 11 x64__: High 4 bits must be `1011`, which is the binary of number `11`.
6. __data[9]__ is unknown, but you can set it by `0xFD`, `0xFC` or `0xFB` if you want to use __not-for-resale license__.
According to symbol information in __Navicat 12 for Mac x64__ version:
* `0xFB` is __Not-For-Resale-30-days__ license.
* `0xFC` is __Not-For-Resale-90-days__ license.
* `0xFD` is __Not-For-Resale-365-days__ license.
* `0xFE` is __Not-For-Resale__ license.
* `0xFF` is __Site__ license.
After `uint8_t data[10]` is ready, Navicat uses __DES__ with __ECB mode__ to encrypt the last 8 bytes of `uint8_t data[10]` which are from __data[2]__ to __data[9]__.
The DES key is:
```cpp
unsigned char DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
```
Then use Base32 to encode `uint8_t data[10]` whose encode table is
```cpp
char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
```
After encoding, you will get a 16-char-long string starting with `"NAV"`.
Finally, divide the 16-char-long string to four 4-chars-long blocks and join them with `"-"` then you will get __snKey__.
## 2. Activation Process
1. Check whether __snKey__ that user inputs is valid.
2. After user clicks `Activate`, Navicat will start online activation first. If fails, user can choose offline activation.
3. Navicat will use the __snKey__ that user inputs and some information collected from user's machine to generate __Offline Activation Request Information__. Then Navicat will encrypt it by __Navicat Activation Public Key__ and return a Base64-encoded string as __Request Code__.
4. In legal way, the __Request Code__ should be sent to Navicat official activation server by a Internet-accessible computer. And Navicat official activation server will return a legal __Activation Code__.
But now, we use keygen to play the official activation server's role.
1. According to the __Request Code__, get `"DI"` value and `"K"` value.
2. Fill __Offline Activation Response Information__ with `"K"` value, name, organization name, `"DI"` value and, if need, `"T"` value.
3. Encrypt __Offline Activation Response Information__ by __Navicat Activation Private Key__ and you will get 256-byte-long data.
4. Encode the 256-byte-long data by Base64. The result is __Activation Code__.
5. After user input __Activation Code__, offline activation is done successfully.
-282
View File
@@ -1,282 +0,0 @@
# Navicat Keygen - 注册机是怎么工作的?
## 1. 关键词解释.
* __Navicat激活公钥__
这是一个2048位的RSA公钥,Navicat使用这个公钥来完成相关激活信息的加密和解密。
这个公钥被作为 __RCData__ 类型的资源储存在 __navicat.exe__ 当中。资源名为`"ACTIVATIONPUBKEY"`。你可以使用一个叫[Resource Hacker](http://www.angusj.com/resourcehacker/)的软件来查看它。这个公钥的具体内容为:
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
如果您有相应的私钥并乐意公开的话欢迎联系我,我将非常感谢您的慷慨。
__注意:__
从 __Navicat Premium 12.0.25__ 开始,Navicat不再从`navicat.exe`的资源中加载私钥。事实上,公钥转为从`libcc.dll`中加载,并且已经被加密。与此同时,为了防止被轻松地替换,加密的公钥被分到5个地方储存:
以下内容是从 __Navicat Premium x64 12.0.25 简体中文版__ 的`libcc.dll`中发现的,`libcc.dll`的SHA256值为`607e0a84c75966b00f3d12fa833e91d159e4f51ac51b6ba66f98d0c3cbefdce0`。我不保证在Navicat的其他版本中相关偏移量和下述的相同,但相关的 __字符串__ 以及 __立即数__ 是很可能找得到的。
1. 在`libcc.dll`中,文件偏移量`+0x01A12090`的地方,储存了加密公钥的第一部分,以 __字符串__ 的形式储存:
```
"D75125B70767B94145B47C1CB3C0755E
7CCB8825C5DCE0C58ACF944E08280140
9A02472FAFFD1CD77864BB821AE36766
FEEDE6A24F12662954168BFA314BD950
32B9D82445355ED7BC0B880887D650F5"
```
2. 在`libcc.dll`中,文件偏移量`+0x0059D799`的地方,储存了加密公钥的第二部分,以 __立即数__ 的形式储存在一条指令中:
```
0xFE 0xEA 0xBC 0x01
```
相应的十进制值为: `29158142`
3. 在`libcc.dll`中,文件偏移量`+0x01A11DA0`的地方,储存了加密公钥的第三部分,以 __字符串__ 的形式储存:
```
"E1CED09B9C2186BF71A70C0FE2F1E0AE
F3BD6B75277AAB20DFAF3D110F75912B
FB63AC50EC4C48689D1502715243A79F
39FF2DE2BF15CE438FF885745ED54573
850E8A9F40EE2FF505EB7476F95ADB78
3B28CA374FAC4632892AB82FB3BF4715
FCFE6E82D03731FC3762B6AAC3DF1C3B
C646FE9CD3C62663A97EE72DB932A301
312B4A7633100C8CC357262C39A2B3A6
4B224F5276D5EDBDF0804DC3AC4B8351
62BB1969EAEBADC43D2511D6E0239287
81B167A48273B953378D3D2080CC0677
7E8A2364F0234B81064C5C739A8DA28D
C5889072BF37685CBC94C2D31D0179AD
86D8E3AA8090D4F0B281BE37E0143746
E6049CCC06899401264FA471C016A96C
79815B55BBC26B43052609D9D175FBCD
E455392F10E51EC162F51CF732E6BB39
1F56BBFD8D957DF3D4C55B71CEFD54B1
9C16D458757373E698D7E693A8FC3981
5A8BF03BA05EA8C8778D38F9873D62B4
460F41ACF997C30E7C3AF025FA171B5F
5AD4D6B15E95C27F6B35AD61875E5505
449B4E"
```
4. 在`libcc.dll`中,文件偏移量`+0x0059D77F`的地方,储存了加密公钥的第四部分,以 __立即数__ 的形式储存在一条指令中:
```
0x59 0x08 0x01 0x00
```
相应的十进制值为: `67673`
5. 在`libcc.dll`中,文件偏移量`+0x01A11D8C`的地方,储存了加密公钥的第五部分,以 __字符串__ 的形式储存:
```
"92933"
```
这五部分按照`"%s%d%s%d%s"`的形式输出则为加密的公钥,顺序和上述的顺序相同,具体的输出为:
```
D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933
```
这个加密的公钥可以用我的另外一个repo[how-does-navicat-encrypt-password](https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password))解密,其中密钥为`b'23970790'`。
例如:
```cmd
E:\GitHub>git clone https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password.git
...
E:\GitHub>cd how-does-navicat-encrypt-password\python3
E:\GitHub\how-does-navicat-encrypt-password\python3>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from NavicatCrypto import *
>>> cipher = Navicat11Crypto(b'23970790')
>>> print(cipher.DecryptString('D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933'))
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
__注意:__
从 __Navicat Premium 12.1.11__ 开始,Navicat不再用上面说的方法加载密钥。当然密钥还是储存在`libcc.dll`文件中。当Navicat启动时,它会用8字节长的XOR密钥来加密公钥,并储存到一个静态数据区中。当验证 __激活码__ 时,Navicat会重新生成一样的8字节XOR密钥,并解密在静态储存区中的密文,从而获取公钥。
在`libcc.dll`,x64版本中,你会看到如下的几条指令:
```asm
xor eax, 'M'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'B'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'j'
mov byte_xxxxxx, al
...
...
```
* __请求码__
这是一个Base64编码的字符串,代表的是长度为256字节的数据。这256字节的数据是 __离线激活信息__ 用 __Navicat激活公钥__ 加密的密文。
* __离线激活请求信息__
这是一个JSON风格的字符串。它包含了3个Key:`"K"`、`"DI"`和`"P"`,分别代表 __序列号__、__设备识别码__(与你的电脑硬件信息相关)和 __平台__ (其实就是操作系统类型)。
例如:
```
{"K": "xxxxxxxxxxxxxxxx", "DI": "yyyyyyyyyyyyy", "P": "WIN8"}
```
* __激活码__
这是一个Base64编码的字符串,代表的是长度为256字节的数据。这256字节的数据是 __离线激活回复信息__ 用 __Navicat激活私钥__ 加密的密文。目前我们不知道官方的 __Navicat激活私钥__,所以我们得替换掉软件里的公钥。
* __离线激活回复信息__
和 __离线激活请求信息__ 一样,它也是一个JSON风格的字符串。但是它包含5个Key,分别为`"K"`、`"N"`、`"O"`、`"T"` 和 `"DI"`.
`"K"` 和 `"DI"` 的意义与 __离线激活请求信息__ 中的相同,且Value必须与 __离线激活请求信息__ 中的相同。
`"N"`、`"O"`、`"T"` 分别代表 __注册名__、__组织__、__授权时间__。
__注册名__ 和 __组织__ 的值类型为UTF-8编码的字符串。__授权时间__ 的值类型可以为字符串或整数(感谢@Wizr在issue #10中的报告)。
`"T"` 可以被省略。
* __序列号__
这是一个被分为了4个部分的字符串,其中每个部分都是4个字符长。
__序列号__ 是通过10个字节的数据来生成的。为了表达方便,我用 __uint8_t data[10]__ 来表示这10个字节。
1. __data[0]__ 和 __data[1]__ 必须分别为 `0x68` 和 `0x2A`。
这两个字节为Navicat的标志数。
2. __data[2]__、__data[3]__ 和 __data[4]__ 可以是任意字节,你想设成什么都行。
3. __data[5]__ 和 __data[6]__ 是Navicat的语言标志,值如下:
| 语言类型 | data[5] | data[6] | 发现者 |
|------------|:---------:|:---------:|-----------------|
| English | 0xAC | 0x88 | |
| 简体中文 | 0xCE | 0x32 | |
| 繁體中文 | 0xAA | 0x99 | |
| 日本語 | 0xAD | 0x82 | @dragonflylee |
| Polski | 0xBB | 0x55 | @dragonflylee |
| Español | 0xAE | 0x10 | @dragonflylee |
| Français | 0xFA | 0x20 | @Deltafox79 |
| Deutsch | 0xB1 | 0x60 | @dragonflylee |
| 한국어 | 0xB5 | 0x60 | @dragonflylee |
| Русский | 0xEE | 0x16 | @dragonflylee |
| Português | 0xCD | 0x49 | @dragonflylee |
4. __data[7]__ 是Navicat产品ID。(感谢 @dragonflylee 和 @Deltafox79提供的数据)
|产品名 |Enterprise|Standard|Educational|Essentials|
|----------------------|:--------:|:------:|:---------:|:--------:|
|Navicat Report Viewer |0x0B | | | |
|Navicat Data Modeler 3| |0x84 |0x85 | |
|Navicat Premium |0x65 | |0x66 |0x67 |
|Navicat MySQL |0x68 |0x69 |0x6A |0x6B |
|Navicat PostgreSQL |0x6C |0x6D |0x6E |0x6F |
|Navicat Oracle |0x70 |0x71 |0x72 |0x73 |
|Navicat SQL Server |0x74 |0x75 |0x76 |0x77 |
|Navicat SQLite |0x78 |0x79 |0x7A |0x7B |
|Navicat MariaDB |0x7C |0x7D |0x7E |0x7F |
|Navicat MongoDB |0x80 |0x81 |0x82 | |
5. __data[8]__ 的高4位代表 __版本号__。低4位未知,但可以用来延长激活期限,可取的值有`0000`和`0001`。
例如:
对于 __Navicat 12__: 高4位必须是`1100`,为`12`的二进制形式。
对于 __Navicat 11__: 高4位必须是`1011`,为`11`的二进制形式。
6. __data[9]__ 目前暂未知,但如果你想要 __not-for-resale license__ 的话可以设成`0xFD`、`0xFC`或`0xFB`。
根据 __Navicat 12 for Mac x64__ 版本残留的符号信息可知:
* `0xFB`是 __Not-For-Resale-30-days__ license.
* `0xFC`是 __Not-For-Resale-90-days__ license.
* `0xFD`是 __Not-For-Resale-365-days__ license.
* `0xFE`是 __Not-For-Resale__ license.
* `0xFF`是 __Site__ license.
之后Navicat使用 __ECB__ 模式的 __DES__ 算法来加密 __data[10]__ 的后8字节,也就是 __data[2]__ 到 __data[9]__ 的部分。
相应的DES密钥为:
```cpp
unsigned char DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
```
之后使用Base32编码 __data[10]__,其中编码表改为:
```cpp
char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
```
编码之后你应该会得到一个16字节长的字符串,并且以"NAV"打头。
将16字节的字符串分成4个4字节的小块,然后用`"-"`连接就可以得到 __序列号__。
## 2. 激活过程
1. 检查用户输入的 __序列号__ 是否合法。
2. 在用户点击了`激活`按钮之后,Navicat会先尝试在线激活。如果失败,用户可以选择离线激活。
3. Navicat会使用用户输入的 __序列号__ 以及从用户电脑收集来的信息生成 __离线激活请求信息__,然后用 __Navicat激活公钥__ 加密,并将密文用Base64编码,最后得到 __请求码__。
4. 正常流程下,__请求码__ 应该通过可联网的电脑发送给Navicat的官方激活服务器。之后Navicat的官方激活服务器会返回一个合法的 __激活码__。
但现在我们使用注册机来扮演官方激活服务器的角色,只是Navicat软件里的激活公钥得换成自己的公钥:
1. 根据 __请求码__, 获得`"DI"`值和`"K"`值。
2. 用`"K"`值、用户名、组织名和`"DI"`值填写 __离线激活回复信息__
3. 用自己的2048位RSA私钥加密 __离线激活回复信息__,你将会得到256字节的密文。
4. 用Base64编码这256字节的密文,就可以得到 __激活码__
5. 在Navicat软件中填入 __激活码__ 即可完成离线激活。
-56
View File
@@ -1,56 +0,0 @@
# Navicat Keygen - How to build?
[中文版](how-to-build.zh-CN.md)
## 1. Prerequisites
1. Please make sure that you have __Visual Studio 2019__ or the higher. Because this is a VS2019 project.
2. Please make sure you have installed `vcpkg` and the following libraries:
* `capstone[x86]:x64-windows-static`
* `capstone[x86]:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `openssl-windows:x64-windows-static`
* `openssl-windows:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
is installed.
You can install them by:
```console
$ vcpkg install capstone[x86]:x64-windows-static
$ vcpkg install capstone[x86]:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install openssl-windows:x64-windows-static
$ vcpkg install openssl-windows:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
```
3. Your `vcpkg` has been integrated into your __Visual Studio__, which means you have run
```console
$ vcpkg integrate install
```
successfully.
## 2. Build
1. Open this project in __Visual Studio__.
2. Select `Release` configuration.
3. Select `Win32` to build keygen/patcher for 32-bits Navicat.
Or select `x64` to build keygen/patcher for 64-bits Navicat.
4. Select __Build > Build Solution__.
You will see executable files in `bin/` directory.
-50
View File
@@ -1,50 +0,0 @@
# Navicat Keygen - 如何编译?
## 1. 前提条件
1. 请确保你有 __Visual Studio 2019__ 或者更高版本。因为这是一个VS2019项目。
2. 请确保你安装了 `vcpkg` 以及下面几个库:
* `capstone[x86]:x64-windows-static`
* `capstone[x86]:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `openssl-windows:x64-windows-static`
* `openssl-windows:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
你可以通过下面的命令来安装它们:
```console
$ vcpkg install capstone[x86]:x64-windows-static
$ vcpkg install capstone[x86]:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install openssl-windows:x64-windows-static
$ vcpkg install openssl-windows:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
```
3. 你的 `vcpkg` 已经和你的 __Visual Studio__ 集成了,即你曾成功运行了:
```console
$ vcpkg integrate install
```
## 2. 编译
1. 在 __Visual Studio__ 打开这个项目。
2. 选择 `Release` 配置。
3. 选择 `Win32` 来生成供32位Navicat使用的keygen/patcher。
或者选择 `x64` 来生成供64位Navicat使用的keygen/patcher。
4. 选择 __生成 > 生成解决方案__。
生成完成后,你会在 `bin/` 文件夹下看到编译后的keygen/patcher。
-257
View File
@@ -1,257 +0,0 @@
# Navicat Keygen - How to use? (Linux)
[中文版](how-to-use.linux.zh-CN.md)
* Maintainer(s): zenuo, DoubleLabyrinth
---
> You can download [Screen recoding](image/Screen_recording.mp4) for references.
1. Switch to the path you extracted the installation package. Run Navicat, for initialization:
```console
$ cd ~/navicat121_premium_en_x64
$ ./start_navicat
```
When running for the first time, you will be prompted with the following two windows, click "Cancel" to:
![](image/Screenshot_2019-04-30_12-31-33.png)
![](image/Screenshot_2019-04-30_12-31-52.png)
Until the `Registration` window appears, select `Trial`, close Navicat after loading is complete, and execute `Step 2`:
![](image/Screenshot_2019-04-30_12-32-43.png)
2. Download the latest release [from here](https://github.com/DoubleLabyrinth/navicat-keygen/releases), and extract:
> The 64-bit executable file is downloaded here. If you use 32-bit, please download the corresponding version.
```console
$ curl -O -L https://github.com/DoubleLabyrinth/navicat-keygen/releases/latest/download/navicat-keygen-for-x64.zip
$ unzip navicat-keygen-for-x64.zip
```
3. Download `navicat-pacther.sh` and `navicat-keygen.sh`:
```console
$ curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-patcher.sh
$ chmod +x navicat-patcher.sh
$ curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-keygen.sh
$ chmod +x navicat-keygen.sh
```
4. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `navicat.exe` or `libcc.dll`.
> Please turn off `Navicat` when performing this step.
```console
$ ./navicat-patcher.sh
```
It has been tested on __Navicat Premium 12.1.22 Simplified Chinese version__. The following is an example of output:
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
5. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```console
$ ./navicat-keygen.sh
```
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
6. __Set up__ a invalid proxy. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
7. Online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
8. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
9. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully. Don't forget to close the proxy that we just set up.
-255
View File
@@ -1,255 +0,0 @@
# Navicat Keygen - 如何使用这个注册机? (Linux)
* 维护者:zenuo, DoubleLabyrinth
---
> 可下载[录屏文件](image/Screen_recording.mp4)参考
1. 切换到解压安装包的路径,本示例解压到了 `家目录`,运行Navicat,使其初始化环境:
```console
$ cd ~/navicat121_premium_en_x64
$ ./start_navicat
```
首次启动时,会提示如下两个窗口,点击“Cancel”即可:
![](image/Screenshot_2019-04-30_12-31-33.png)
![](image/Screenshot_2019-04-30_12-31-52.png)
直至出现 `Registration` 窗口,选择 `Trial`,待加载完成后关闭Navicat,执行 `步骤2`
![](image/Screenshot_2019-04-30_12-32-43.png)
2. [从这里](https://github.com/DoubleLabyrinth/navicat-keygen/releases)下载最新的release,并且解压:
> 此处下载的是64位的可执行文件,若您使用32位,请下载对应版本
```console
$ curl -O -L https://github.com/DoubleLabyrinth/navicat-keygen/releases/latest/download/navicat-keygen-for-x64.zip
$ unzip navicat-keygen-for-x64.zip
```
3. 下载 `navicat-pacther.sh` 和 `navicat-keygen.sh`
```console
$ curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-patcher.sh
$ chmod +x navicat-patcher.sh
$ curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-keygen.sh
$ chmod +x navicat-keygen.sh
```
4. 使用 `navicat-patcher.exe` 替换掉 `navicat.exe` 和 `libcc.dll` 里的Navicat激活公钥。
> 执行此步骤时,请将Navicat关闭
```console
$ ./navicat-patcher.sh
```
__Navicat Premium 12.1.22 简体中文版已通过测试__。下面将是一份样例输出:
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
5. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```console
$ ./navicat-keygen.sh
```
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号。
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
你可以使用这个序列号暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
6. 配置一个不存在的`代理`。找到`注册`窗口,并填入keygen给你的序列号。然后点击`激活`按钮。
7. 在线激活失败,这时候Navicat会询问你是否`手动激活`,直接选吧。
8. 在`手动激活`窗口你会得到一个请求码,复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
9. 如果不出意外,你会得到一个看似用Base64编码的激活码。直接复制它,并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。别忘了关闭我们刚刚设置的不存在的代理哦。
-256
View File
@@ -1,256 +0,0 @@
# Navicat Keygen - How to use? (Windows)
[中文版](how-to-use.windows.zh-CN.md)
1. Download the latest release [from here](https://github.com/DoubleLabyrinth/navicat-keygen/releases).
2. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `navicat.exe` or `libcc.dll`.
```
navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]` Run patcher without applying any patches.
__This parameter is optional.__
* `<Navicat Installation Path>`: The full path to Navicat installation folder.
__This parameter must be specified.__
* `[RSA-2048 PEM File Path]`: The full path or relative path to a RSA-2048 private key file.
__This parameter is optional.__ If not specified, `navicat-patcher.exe` will generate a new RSA-2048 private key file `RegPrivateKey.pem` at current directory.
__Example: (in cmd.exe)__
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 12"
```
It has been tested on __Navicat Premium 12.1.22 Simplified Chinese version__. The following is an example of output.
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
3. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>
```
* `<-bin|-text>`: Must be `-bin` or `-text`.
If `-bin` is specified, `navicat-keygen.exe` will finally generate `license_file`. It is used for Navicat old activation method only.
If `-text` is specified, `navicat-keygen.exe` will finally generate a Base64-style string which is __Activation Code__. It is used for Navicat new activation method.
__This parameter must be specified.__
* `[-adv]`: Enable advanced mode.
__This parameter is optional.__ If specified, `navicat-keygen.exe` will ask you input Navicat product ID number, language signature numbers. It is for future use generally.
* `<RSA-2048 PrivateKey(PEM file)>`: The full path or relative path to a RSA-2048 private key file.
__This parameter must be specified.__
__Example: (in cmd.exe)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
4. __Disconnect your network__ and open Navicat. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
5. Generally online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
6. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
7. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully.
-254
View File
@@ -1,254 +0,0 @@
# Navicat Keygen - 如何使用这个注册机? (Windows)
1. [从这里](https://github.com/DoubleLabyrinth/navicat-keygen/releases)下载最新的release。
2. 使用`navicat-patcher.exe`替换掉`navicat.exe``libcc.dll`里的Navicat激活公钥。
```
navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]`: 运行patcher但不对Navicat程序做任何修改。
__这个参数是可选的。__
* `<Navicat Installation Path>`: Navicat的完整安装路径。
__这个参数必须指定。__
* `[RSA-2048 PEM File Path]`: RSA-2048私钥文件的完整路径或相对路径。
__这个参数是可选的。__ 如果未指定,`navicat-patcher.exe`将会在当前目录生成一个新的RSA-2048私钥文件。
__例如:(在cmd.exe中)__
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 12"
```
__Navicat Premium 12.1.22 简体中文版已通过测试__。下面将是一份样例输出:
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
3. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>
```
* `<-bin|-text>`: 必须是`-bin`或`-text`。
如果指定了`-bin``navicat-keygen.exe`最终将生成`license_file`文件。这个选项是给Navicat旧激活方式使用的。
如果指定了`-text``navicat-keygen.exe`最终将生成Base64样式的激活码。这个选项是给Navicat新激活方式使用的。
__这个参数必须指定。__
* `[-adv]`: 开启高级模式。
__这个参数是可选的。__ 如果指定了这个参数,`navicat-keygen.exe`将会要求你手工填写产品ID号、语言标识号。这个选项一般是给以后用的。
* `<RSA-2048 PrivateKey(PEM file)>`: RSA-2048私钥文件的完整路径或相对路径。
__这个参数必须指定。__
__例如:(在cmd.exe中)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号。
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
你可以使用这个序列号暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
4. __断开网络__ 并打开Navicat。找到`注册`窗口,并填入keygen给你的序列号。然后点击`激活`按钮。
5. 一般来说在线激活肯定会失败,这时候Navicat会询问你是否`手动激活`,直接选吧。
6. 在`手动激活`窗口你会得到一个请求码,复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
4. 如果不出意外,你会得到一个看似用Base64编码的激活码。直接复制它,并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

-48
View File
@@ -1,48 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-keygen", "navicat-keygen\navicat-keygen.vcxproj", "{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-patcher", "navicat-patcher\navicat-patcher.vcxproj", "{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "common", "common\common.vcxitems", "{290C5D5E-52D2-4FEF-909F-27FD95AE0AF9}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
common\common.vcxitems*{290c5d5e-52d2-4fef-909f-27fd95ae0af9}*SharedItemsImports = 9
common\common.vcxitems*{7ee03ef3-d58d-4b53-913d-4a4dc8a29e34}*SharedItemsImports = 4
common\common.vcxitems*{ba201764-eecf-4da8-bcad-7cfba301fc9c}*SharedItemsImports = 4
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x64.ActiveCfg = Debug|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x64.Build.0 = Debug|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x86.ActiveCfg = Debug|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x86.Build.0 = Debug|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x64.ActiveCfg = Release|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x64.Build.0 = Release|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x86.ActiveCfg = Release|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x86.Build.0 = Release|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x64.ActiveCfg = Debug|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x64.Build.0 = Debug|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x86.ActiveCfg = Debug|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x86.Build.0 = Debug|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x64.ActiveCfg = Release|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x64.Build.0 = Release|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x86.ActiveCfg = Release|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CB1D6B65-6AEA-44E4-8698-0AEBDBC63CD2}
EndGlobalSection
EndGlobal
+66
View File
@@ -0,0 +1,66 @@
#include <vector>
#include <string>
#include <openssl/evp.h>
#include "../common/Exception.hpp"
#include "../common/ResourceOwned.hpp"
#include "../common/ResourceTraitsOpenssl.hpp"
std::string base64_encode(const std::vector<uint8_t>& bindata) {
ResourceOwned b64(OpensslBIOTraits{}, BIO_new(BIO_f_base64()));
if (b64.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
ResourceOwned mem(OpensslBIOTraits{}, BIO_new(BIO_s_mem()));
if (mem.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
BIO_push(b64, mem);
if (BIO_write(b64, bindata.data(), bindata.size()) != bindata.size()) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_write failed.");
}
if (BIO_flush(b64) != 1) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_flush failed.");
}
const char* data = nullptr;
auto len = BIO_get_mem_data(mem, &data);
BIO_pop(b64);
return std::string(data, len);
}
std::vector<uint8_t> base64_decode(const std::string& ascdata) {
ResourceOwned b64(OpensslBIOTraits{}, BIO_new(BIO_f_base64()));
if (b64.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
ResourceOwned mem(OpensslBIOTraits{}, BIO_new_mem_buf(ascdata.c_str(), -1));
if (mem.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
BIO_push(b64, mem);
std::vector<uint8_t> bindata(ascdata.length() / 4 * 3 + 1);
bindata.resize(BIO_read(b64, bindata.data(), bindata.size()));
BIO_pop(b64);
return bindata;
}
-92
View File
@@ -1,92 +0,0 @@
#pragma once
#include <Exception.hpp>
#include <ExceptionWin32.hpp>
#include <xstring.hpp>
#include <bytearray.hpp>
#include <wincrypt.h>
#pragma comment(lib, "Crypt32")
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\Base64.hpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
std::xstring Base64Encode(const std::bytearray& Bytes) {
if (Bytes.empty()) {
return std::xstring();
} else {
DWORD cchBase64String = 0;
std::xstring Base64String;
auto bResult = CryptBinaryToString(
Bytes.data(),
static_cast<DWORD>(Bytes.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
NULL,
&cchBase64String
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptBinaryToString failed."));
}
Base64String.resize(cchBase64String - 1);
bResult = CryptBinaryToString(
Bytes.data(),
static_cast<DWORD>(Bytes.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
Base64String.data(),
&cchBase64String
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptBinaryToString failed."));
}
return Base64String;
}
}
std::bytearray Base64Decode(const std::xstring& Base64String) {
if (Base64String.empty()) {
return std::bytearray();
} else {
DWORD cbBytes = 0;
std::bytearray Bytes;
auto bResult = CryptStringToBinary(
Base64String.c_str(),
NULL,
CRYPT_STRING_BASE64,
NULL,
&cbBytes,
NULL,
NULL
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptStringToBinary failed."))
.AddHint(TEXT("Are you sure it is a Base64 string?"));
}
Bytes.resize(cbBytes);
bResult = CryptStringToBinary(
Base64String.c_str(),
NULL,
CRYPT_STRING_BASE64,
Bytes.data(),
&cbBytes,
NULL,
NULL
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptStringToBinary failed."));
}
return Bytes;
}
}
}
-152
View File
@@ -1,152 +0,0 @@
#include "SerialNumberGenerator.hpp"
#include <ExceptionUser.hpp>
#include <iostream>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\CollectInformation.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace std {
#if defined(_UNICODE) || defined(UNICODE)
static auto& xcin = wcin;
static auto& xcout = wcout;
static auto& xcerr = wcerr;
#else
static auto& xcin = cin;
static auto& xcout = cout;
static auto& xcerr = cerr;
#endif
}
namespace nkg {
[[nodiscard]]
static int ReadInt(int MinVal, int MaxVal, PCTSTR lpszPrompt, PCTSTR lpszErrorMessage) {
int val;
std::xstring s;
while (true) {
std::xcout << lpszPrompt;
if (!std::getline(std::xcin, s)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
}
if (s.empty())
continue;
try {
val = std::stoi(s, nullptr, 0);
if (MinVal <= val && val <= MaxVal) {
return val;
} else {
throw std::invalid_argument("");
}
} catch (std::invalid_argument&) {
std::xcout << lpszErrorMessage << std::endl;
}
}
}
[[nodiscard]]
static int ReadInt(int MinVal, int MaxVal, int DefaultVal, PCTSTR lpszPrompt, PCTSTR lpszErrorMessage) {
int val;
std::xstring s;
while (true) {
std::xcout << lpszPrompt;
if (!std::getline(std::xcin, s)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
}
if (s.empty()) {
return DefaultVal;
}
try {
val = std::stoi(s, nullptr, 0);
if (MinVal <= val && val <= MaxVal) {
return val;
} else {
throw std::invalid_argument("");
}
} catch (std::invalid_argument&) {
std::xcout << lpszErrorMessage << std::endl;
}
}
}
[[nodiscard]]
SerialNumberGenerator CollectInformationNormal() {
SerialNumberGenerator Generator;
std::xcout << TEXT("[*] Select Navicat product:") << std::endl;
std::xcout << TEXT(" 0. DataModeler") << std::endl;
std::xcout << TEXT(" 1. Premium") << std::endl;
std::xcout << TEXT(" 2. MySQL") << std::endl;
std::xcout << TEXT(" 3. PostgreSQL") << std::endl;
std::xcout << TEXT(" 4. Oracle") << std::endl;
std::xcout << TEXT(" 5. SQLServer") << std::endl;
std::xcout << TEXT(" 6. SQLite") << std::endl;
std::xcout << TEXT(" 7. MariaDB") << std::endl;
std::xcout << TEXT(" 8. MongoDB") << std::endl;
std::xcout << TEXT(" 9. ReportViewer") << std::endl;
std::xcout << std::endl;
Generator.SetProductSignature(
static_cast<NavicatProductType>(ReadInt(0, 9, TEXT("(Input index)> "), TEXT("Invalid index.")))
);
std::xcout << std::endl;
std::xcout << TEXT("[*] Select product language:") << std::endl;
std::xcout << TEXT(" 0. English") << std::endl;
std::xcout << TEXT(" 1. Simplified Chinese") << std::endl;
std::xcout << TEXT(" 2. Traditional Chinese") << std::endl;
std::xcout << TEXT(" 3. Japanese") << std::endl;
std::xcout << TEXT(" 4. Polish") << std::endl;
std::xcout << TEXT(" 5. Spanish") << std::endl;
std::xcout << TEXT(" 6. French") << std::endl;
std::xcout << TEXT(" 7. German") << std::endl;
std::xcout << TEXT(" 8. Korean") << std::endl;
std::xcout << TEXT(" 9. Russian") << std::endl;
std::xcout << TEXT(" 10. Portuguese") << std::endl;
std::xcout << std::endl;
Generator.SetLanguageSignature(
static_cast<NavicatLanguage>(ReadInt(0, 10, TEXT("(Input index)> "), TEXT("Invalid index.")))
);
std::xcout << std::endl;
std::xcout << TEXT("[*] Input major version number:") << std::endl;
Generator.SetVersion(
static_cast<BYTE>(ReadInt(0, 15, 12, TEXT("(range: 0 ~ 15, default: 12)> "), TEXT("Invalid number.")))
);
std::xcout << std::endl;
return Generator;
}
[[nodiscard]]
SerialNumberGenerator CollectInformationAdvanced() {
SerialNumberGenerator Generator;
std::xcout << TEXT("[*] Navicat Product Signature:") << std::endl;
Generator.SetProductSignature(
static_cast<BYTE>(ReadInt(0x00, 0xff, TEXT("(range: 0x00 ~ 0xFF)> "), TEXT("Invalid number.")))
);
std::xcout << std::endl;
std::xcout << TEXT("[*] Navicat Language Signature 0:") << std::endl;
auto s1 = static_cast<BYTE>(ReadInt(0x00, 0xff, TEXT("(range: 0x00 ~ 0xFF)> "), TEXT("Invalid number.")));
std::xcout << std::endl;
std::xcout << TEXT("[*] Navicat Language Signature 1:") << std::endl;
auto s2 = static_cast<BYTE>(ReadInt(0x00, 0xff, TEXT("(range: 0x00 ~ 0xFF)> "), TEXT("Invalid number.")));
Generator.SetLanguageSignature(s1, s2);
std::xcout << std::endl;
std::xcout << TEXT("[*] Input major version number:") << std::endl;
Generator.SetVersion(
static_cast<BYTE>(ReadInt(0, 15, 12, TEXT("(range: 0 ~ 15, default: 12)> "), TEXT("Invalid number.")))
);
std::xcout << std::endl;
return Generator;
}
}
+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include <openssl/crypto.h>
#include <openssl/des.h>
#include <memory.h>
class DESCipher {
private:
DES_cblock _Key;
DES_key_schedule _Schedule;
public:
DESCipher() noexcept : _Key{}, _Schedule{} {}
void SetKey(const void* pKey) noexcept {
memcpy(&_Key, pKey, sizeof(_Key));
DES_set_odd_parity(&_Key);
DES_set_key(&_Key, &_Schedule);
}
void Clear() noexcept {
OPENSSL_cleanse(&_Key, sizeof(_Key));
OPENSSL_cleanse(&_Schedule, sizeof(_Schedule));
}
void EncryptBlock(void* lpBuffer) noexcept {
DES_cblock block;
DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(lpBuffer), &block, &_Schedule, DES_ENCRYPT);
memcpy(lpBuffer, &block, sizeof(block));
}
void DecryptBlock(void* lpBuffer) noexcept {
DES_cblock block;
DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(lpBuffer), &block, &_Schedule, DES_DECRYPT);
memcpy(lpBuffer, &block, sizeof(block));
}
~DESCipher() noexcept {
Clear();
}
};
-241
View File
@@ -1,241 +0,0 @@
#include <ExceptionUser.hpp>
#include <ResourceOwned.hpp>
#include <ResourceTraitsWin32.hpp>
#include <xstring.hpp>
#include <bytearray.hpp>
#include <RSACipher.hpp>
#include "Base64.hpp"
#include "SerialNumberGenerator.hpp"
#include <iostream>
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\GenerateLicense.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace std {
#if defined(_UNICODE) || defined(UNICODE)
static auto & xcin = wcin;
static auto& xcout = wcout;
static auto& xcerr = wcerr;
#else
static auto& xcin = cin;
static auto& xcout = cout;
static auto& xcerr = cerr;
#endif
}
namespace nkg {
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator) {
std::xstring username;
std::xstring organization;
std::string utf8username;
std::string utf8organization;
std::xstring b64RequestCode;
std::bytearray RequestCode;
std::string utf8RequestInfo;
std::string utf8ResponseInfo;
std::bytearray ResponseCode;
std::xstring b64ResponseCode;
std::xcout << TEXT("[*] Your name: ");
if (!std::getline(std::xcin, username)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8username = username.explicit_string(CP_UTF8);
}
std::xcout << TEXT("[*] Your organization: ");
if (!std::getline(std::xcin, organization)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8organization = organization.explicit_string(CP_UTF8);
}
std::xcout << TEXT("[*] Input request code in Base64: (Input empty line to end)") << std::endl;
while (true) {
std::xstring temp;
if (!std::getline(std::xcin, temp)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
}
if (temp.empty()) {
break;
}
b64RequestCode.append(temp);
}
RequestCode = Base64Decode(b64RequestCode);
utf8RequestInfo.resize((Cipher.Bits() + 7) / 8);
Cipher.Decrypt(RequestCode.data(), RequestCode.size(), utf8RequestInfo.data(), RSA_PKCS1_PADDING);
while (utf8RequestInfo.back() == '\x00') {
utf8RequestInfo.pop_back();
}
std::xcout << TEXT("[*] Request Info:") << std::endl;
std::xcout << std::xstring(std::xstring_extension{}, utf8RequestInfo, CP_UTF8) << std::endl;
std::xcout << std::endl;
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//
// Begin to parse
//
json.Parse(utf8RequestInfo.c_str());
//
// Remove "Platform" info
//
json.RemoveMember("P");
//
// Set "Name" info
//
N_Key.SetString("N", 1);
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
//
// Set "Organization" info
//
O_Key.SetString("O", 1);
O_Value.SetString(utf8organization.c_str(), static_cast<rapidjson::SizeType>(utf8organization.length()));
//
// Set "Time" info
//
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
//
// Add "Name", "Organization" and "Time"
//
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Response info is too long."));
}
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
std::xcout << TEXT("[*] Response Info:") << std::endl;
std::xcout << std::xstring(std::xstring_extension{}, utf8ResponseInfo, CP_UTF8) << std::endl;
std::xcout << std::endl;
ResponseCode.resize((Cipher.Bits() + 7) / 8);
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
b64ResponseCode = Base64Encode(ResponseCode);
std::xcout << TEXT("[*] Activation Code:") << std::endl;
std::xcout << b64ResponseCode << std::endl;
std::xcout << std::endl;
}
void GenerateLicenseBinary(const RSACipher& Cipher, const SerialNumberGenerator& Generator) {
ResourceOwned hLicenseFile(FileHandleTraits{});
std::string utf8SerialNumber = Generator.GetSerialNumberShort().explicit_string(CP_UTF8);
std::xstring username;
std::xstring organization;
std::string utf8username;
std::string utf8organization;
std::string utf8ResponseInfo;
std::bytearray ResponseCode;
std::xcout << TEXT("[*] Your name: ");
if (!std::getline(std::xcin, username)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8username = username.explicit_string(CP_UTF8);
}
std::xcout << TEXT("[*] Your organization: ");
if (!std::getline(std::xcin, organization)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8organization = organization.explicit_string(CP_UTF8);
}
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::Value K_Key;
rapidjson::Value K_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Parse("{}");
K_Key.SetString("K", 1);
K_Value.SetString(utf8SerialNumber.c_str(), static_cast<rapidjson::SizeType>(utf8SerialNumber.length()));
N_Key.SetString("N", 1);
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
O_Key.SetString("O", 1);
O_Value.SetString(utf8organization.c_str(), static_cast<rapidjson::SizeType>(utf8organization.length()));
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
json.AddMember(K_Key, K_Value, json.GetAllocator());
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Response info is too long."));
}
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
std::xcout << TEXT("[*] Response Info:") << std::endl;
std::xcout << std::xstring(std::xstring_extension{}, utf8ResponseInfo, CP_UTF8) << std::endl;
std::xcout << std::endl;
ResponseCode.resize((Cipher.Bits() + 7) / 8);
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
hLicenseFile.TakeOver(
CreateFile(
TEXT("license_file"),
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
)
);
if (hLicenseFile.IsValid() == false) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFile failed."));
}
DWORD NumberOfBytesWritten;
if (!WriteFile(hLicenseFile, ResponseCode.data(), static_cast<DWORD>(ResponseCode.size()), &NumberOfBytesWritten, NULL)) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("WriteFile failed."));
}
std::xcout << TEXT("[+] license_file has been generated.") << std::endl;
}
}
+195
View File
@@ -0,0 +1,195 @@
#pragma once
#include <string>
#include <random>
#include "DESCipher.hpp"
class NavicatKeygen {
public:
enum class Language {
English,
SimplifiedChinese,
TraditionalChinese,
Japanese,
Polish,
Spanish,
French,
German,
Korean,
Russian,
Portuguese
};
enum class Product {
DataModeler,
Premium,
MySQL,
PostgreSQL,
Oracle,
SQLServer,
SQLite,
MariaDB,
MongoDB,
ReportViewer
};
private:
std::random_device rand_dev;
std::default_random_engine rand_eng;
std::uniform_int_distribution<int> rand;
uint8_t data[10];
public:
NavicatKeygen() : rand_eng(rand_dev()), rand(0, UINT8_MAX), data{} {
data[0] = 0x68;
data[1] = 0x2A;
}
void SetLanguageSignature(Language _language) {
switch (_language) {
case Language::English:
data[5] = 0xAC; // Must be 0xAC for English version.
data[6] = 0x88; // Must be 0x88 for English version.
break;
case Language::SimplifiedChinese:
data[5] = 0xCE; // Must be 0xCE for Simplified Chinese version.
data[6] = 0x32; // Must be 0x32 for Simplified Chinese version.
break;
case Language::TraditionalChinese:
data[5] = 0xAA; // Must be 0xAA for Traditional Chinese version.
data[6] = 0x99; // Must be 0x99 for Traditional Chinese version.
break;
case Language::Japanese:
data[5] = 0xAD; // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
data[6] = 0x82; // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
break;
case Language::Polish:
data[5] = 0xBB; // Must be 0xBB for Polish version. Discoverer: @dragonflylee
data[6] = 0x55; // Must be 0x55 for Polish version. Discoverer: @dragonflylee
break;
case Language::Spanish:
data[5] = 0xAE; // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
data[6] = 0x10; // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
break;
case Language::French:
data[5] = 0xFA; // Must be 0xFA for French version. Discoverer: @Deltafox79
data[6] = 0x20; // Must be 0x20 for French version. Discoverer: @Deltafox79
break;
case Language::German:
data[5] = 0xB1; // Must be 0xB1 for German version. Discoverer: @dragonflylee
data[6] = 0x60; // Must be 0x60 for German version. Discoverer: @dragonflylee
break;
case Language::Korean:
data[5] = 0xB5; // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
data[6] = 0x60; // Must be 0x60 for Korean version. Discoverer: @dragonflylee
break;
case Language::Russian:
data[5] = 0xEE; // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
data[6] = 0x16; // Must be 0x60 for Russian version. Discoverer: @dragonflylee
break;
case Language::Portuguese:
data[5] = 0xCD; // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
break;
}
}
void SetLanguageSignature(uint8_t value0, uint8_t value1) {
data[5] = value0;
data[6] = value1;
}
void SetProductSignature(Product _product) {
switch (_product) {
case Product::DataModeler:
data[7] = 0x47;
break;
case Product::Premium:
data[7] = 0x65;
break;
case Product::MySQL:
data[7] = 0x68;
break;
case Product::PostgreSQL:
data[7] = 0x6C;
break;
case Product::Oracle:
data[7] = 0x70;
break;
case Product::SQLServer:
data[7] = 0x74;
break;
case Product::SQLite:
data[7] = 0x78;
break;
case Product::MariaDB:
data[7] = 0x7C;
break;
case Product::MongoDB:
data[7] = 0x80;
break;
case Product::ReportViewer:
data[7] = 0xb;
default:
break;
}
}
void SetProductSignature(uint8_t value) {
data[7] = value;
}
void SetVersion(uint8_t version) {
data[8] = version << 4;
}
void Generate() {
static uint8_t DESKey[] = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
DESCipher cipher;
data[2] = static_cast<uint8_t>(rand(rand_eng));
data[3] = static_cast<uint8_t>(rand(rand_eng));
data[4] = static_cast<uint8_t>(rand(rand_eng));
data[9] = 0x32;
cipher.SetKey(&DESKey);
cipher.EncryptBlock(data + 2);
}
std::string GetKey() const {
static const char EncodeTable[] = "ABCDEFGH8JKLMN9PQRSTUVWXYZ234567";
std::string Key;
Key.resize(16);
Key[0] = EncodeTable[data[0] >> 3];
Key[1] = EncodeTable[(data[0] & 0x07) << 2 | data[1] >> 6];
Key[2] = EncodeTable[data[1] >> 1 & 0x1F];
Key[3] = EncodeTable[(data[1] & 0x1) << 4 | data[2] >> 4];
Key[4] = EncodeTable[(data[2] & 0xF) << 1 | data[3] >> 7];
Key[5] = EncodeTable[data[3] >> 2 & 0x1F];
Key[6] = EncodeTable[(data[3] << 3 & 0x1F) | data[4] >> 5];
Key[7] = EncodeTable[data[4] & 0x1F];
Key[8] = EncodeTable[data[5] >> 3];
Key[9] = EncodeTable[(data[5] & 0x07) << 2 | data[6] >> 6];
Key[10] = EncodeTable[data[6] >> 1 & 0x1F];
Key[11] = EncodeTable[(data[6] & 0x1) << 4 | data[7] >> 4];
Key[12] = EncodeTable[(data[7] & 0xF) << 1 | data[8] >> 7];
Key[13] = EncodeTable[data[8] >> 2 & 0x1F];
Key[14] = EncodeTable[(data[8] << 3 & 0x1F) | data[9] >> 5];
Key[15] = EncodeTable[data[9] & 0x1F];
return Key;
}
std::string GetFormatedKey() const {
std::string Key = GetKey();
Key.insert(Key.begin() + 4, '-');
Key.insert(Key.begin() + 5 + 4, '-');
Key.insert(Key.begin() + 10 + 4, '-');
return Key;
}
};
-195
View File
@@ -1,195 +0,0 @@
#include "SerialNumberGenerator.hpp"
#include <Exception.hpp>
#include <openssl/des.h>
#include <NTSecAPI.h>
#include <iostream>
#pragma comment(lib, "Advapi32")
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\NavicatKeygen.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace std {
#if defined(_UNICODE) || defined(UNICODE)
static auto & xcin = wcin;
static auto& xcout = wcout;
static auto& xcerr = wcerr;
#else
static auto& xcin = cin;
static auto& xcout = cout;
static auto& xcerr = cerr;
#endif
}
namespace nkg {
SerialNumberGenerator::SerialNumberGenerator() noexcept :
_Data{ 0x68 , 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32 } {}
void SerialNumberGenerator::SetLanguageSignature(NavicatLanguage Language) noexcept {
switch (Language) {
case NavicatLanguage::English:
_Data[5] = 0xAC; // Must be 0xAC for English version.
_Data[6] = 0x88; // Must be 0x88 for English version.
break;
case NavicatLanguage::SimplifiedChinese:
_Data[5] = 0xCE; // Must be 0xCE for Simplified Chinese version.
_Data[6] = 0x32; // Must be 0x32 for Simplified Chinese version.
break;
case NavicatLanguage::TraditionalChinese:
_Data[5] = 0xAA; // Must be 0xAA for Traditional Chinese version.
_Data[6] = 0x99; // Must be 0x99 for Traditional Chinese version.
break;
case NavicatLanguage::Japanese:
_Data[5] = 0xAD; // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
_Data[6] = 0x82; // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Polish:
_Data[5] = 0xBB; // Must be 0xBB for Polish version. Discoverer: @dragonflylee
_Data[6] = 0x55; // Must be 0x55 for Polish version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Spanish:
_Data[5] = 0xAE; // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
_Data[6] = 0x10; // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
break;
case NavicatLanguage::French:
_Data[5] = 0xFA; // Must be 0xFA for French version. Discoverer: @Deltafox79
_Data[6] = 0x20; // Must be 0x20 for French version. Discoverer: @Deltafox79
break;
case NavicatLanguage::German:
_Data[5] = 0xB1; // Must be 0xB1 for German version. Discoverer: @dragonflylee
_Data[6] = 0x60; // Must be 0x60 for German version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Korean:
_Data[5] = 0xB5; // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
_Data[6] = 0x60; // Must be 0x60 for Korean version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Russian:
_Data[5] = 0xEE; // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
_Data[6] = 0x16; // Must be 0x60 for Russian version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Portuguese:
_Data[5] = 0xCD; // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
_Data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
break;
}
}
void SerialNumberGenerator::SetLanguageSignature(BYTE LanguageSignature0, BYTE LanguageSignature1) noexcept {
_Data[5] = LanguageSignature0;
_Data[6] = LanguageSignature1;
}
void SerialNumberGenerator::SetProductSignature(NavicatProductType ProductType) noexcept {
switch (ProductType) {
case NavicatProductType::DataModeler:
_Data[7] = 0x84;
break;
case NavicatProductType::Premium:
_Data[7] = 0x65;
break;
case NavicatProductType::MySQL:
_Data[7] = 0x68;
break;
case NavicatProductType::PostgreSQL:
_Data[7] = 0x6C;
break;
case NavicatProductType::Oracle:
_Data[7] = 0x70;
break;
case NavicatProductType::SQLServer:
_Data[7] = 0x74;
break;
case NavicatProductType::SQLite:
_Data[7] = 0x78;
break;
case NavicatProductType::MariaDB:
_Data[7] = 0x7C;
break;
case NavicatProductType::MongoDB:
_Data[7] = 0x80;
break;
case NavicatProductType::ReportViewer:
_Data[7] = 0xb;
default:
break;
}
}
void SerialNumberGenerator::SetProductSignature(BYTE ProductSignature) noexcept {
_Data[7] = ProductSignature;
}
void SerialNumberGenerator::SetVersion(BYTE Version) {
if (Version < 0x10) {
_Data[8] = static_cast<BYTE>(Version << 4);
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid version for Navicat."));
}
}
void SerialNumberGenerator::Generate() {
static const TCHAR EncodeTable[] = TEXT("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");
RtlGenRandom(_Data + 2, 3);
const_DES_cblock key = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
DES_key_schedule schedule;
DES_set_key_unchecked(&key, &schedule);
DES_ecb_encrypt(
reinterpret_cast<const_DES_cblock*>(_Data + 2),
reinterpret_cast<const_DES_cblock*>(_Data + 2),
&schedule,
DES_ENCRYPT
);
_SerialNumberShort.resize(16);
_SerialNumberShort[0] = EncodeTable[_Data[0] >> 3];
_SerialNumberShort[1] = EncodeTable[(_Data[0] & 0x07) << 2 | _Data[1] >> 6];
_SerialNumberShort[2] = EncodeTable[_Data[1] >> 1 & 0x1F];
_SerialNumberShort[3] = EncodeTable[(_Data[1] & 0x1) << 4 | _Data[2] >> 4];
_SerialNumberShort[4] = EncodeTable[(_Data[2] & 0xF) << 1 | _Data[3] >> 7];
_SerialNumberShort[5] = EncodeTable[_Data[3] >> 2 & 0x1F];
_SerialNumberShort[6] = EncodeTable[_Data[3] << 3 & 0x1F | _Data[4] >> 5];
_SerialNumberShort[7] = EncodeTable[_Data[4] & 0x1F];
_SerialNumberShort[8] = EncodeTable[_Data[5] >> 3];
_SerialNumberShort[9] = EncodeTable[(_Data[5] & 0x07) << 2 | _Data[6] >> 6];
_SerialNumberShort[10] = EncodeTable[_Data[6] >> 1 & 0x1F];
_SerialNumberShort[11] = EncodeTable[(_Data[6] & 0x1) << 4 | _Data[7] >> 4];
_SerialNumberShort[12] = EncodeTable[(_Data[7] & 0xF) << 1 | _Data[8] >> 7];
_SerialNumberShort[13] = EncodeTable[_Data[8] >> 2 & 0x1F];
_SerialNumberShort[14] = EncodeTable[_Data[8] << 3 & 0x1F | _Data[9] >> 5];
_SerialNumberShort[15] = EncodeTable[_Data[9] & 0x1F];
_SerialNumberLong = std::xstring::format(
TEXT("%.4s-%.4s-%.4s-%.4s"),
_SerialNumberShort.c_str() + 0,
_SerialNumberShort.c_str() + 4,
_SerialNumberShort.c_str() + 8,
_SerialNumberShort.c_str() + 12
);
}
[[nodiscard]]
const std::xstring& SerialNumberGenerator::GetSerialNumberShort() const noexcept {
return _SerialNumberShort;
}
[[nodiscard]]
const std::xstring& SerialNumberGenerator::GetSerialNumberLong() const noexcept {
return _SerialNumberLong;
}
void SerialNumberGenerator::ShowInConsole() const {
std::xcout << TEXT("[*] Serial number:") << std::endl;
std::xcout << _SerialNumberLong << std::endl;
std::xcout << std::endl;
}
}
-64
View File
@@ -1,64 +0,0 @@
#pragma once
#include <windows.h>
#include <xstring.hpp>
namespace nkg {
enum class NavicatLanguage {
English,
SimplifiedChinese,
TraditionalChinese,
Japanese,
Polish,
Spanish,
French,
German,
Korean,
Russian,
Portuguese
};
enum class NavicatProductType {
DataModeler,
Premium,
MySQL,
PostgreSQL,
Oracle,
SQLServer,
SQLite,
MariaDB,
MongoDB,
ReportViewer
};
class SerialNumberGenerator {
private:
BYTE _Data[10];
std::xstring _SerialNumberShort;
std::xstring _SerialNumberLong;
public:
SerialNumberGenerator() noexcept;
void SetLanguageSignature(NavicatLanguage Language) noexcept;
void SetLanguageSignature(BYTE LanguageSignature0, BYTE LanguageSignature1) noexcept;
void SetProductSignature(NavicatProductType ProductType) noexcept;
void SetProductSignature(BYTE ProductSignature) noexcept;
void SetVersion(BYTE Version);
void Generate();
[[nodiscard]]
const std::xstring& GetSerialNumberShort() const noexcept;
[[nodiscard]]
const std::xstring& GetSerialNumberLong() const noexcept;
void ShowInConsole() const;
};
}
-117
View File
@@ -1,117 +0,0 @@
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <Exception.hpp>
#include <ExceptionUser.hpp>
#include <RSACipher.hpp>
#include "SerialNumberGenerator.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\_tmain.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
using fnCollectInformation = SerialNumberGenerator();
using fnGenerateLicense = void(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
SerialNumberGenerator CollectInformationNormal();
SerialNumberGenerator CollectInformationAdvanced();
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
void GenerateLicenseBinary(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
}
static void Welcome() {
_putts(TEXT("***************************************************"));
_putts(TEXT("* Navicat Keygen by @DoubleLabyrinth *"));
_putts(TEXT("* Version: 4.0 *"));
_putts(TEXT("***************************************************"));
_putts(TEXT(""));
}
static void Help() {
_putts(TEXT("Usage:"));
_putts(TEXT(" navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>"));
_putts(TEXT(""));
_putts(TEXT(" <-bin|-text> Specify \"-bin\" to generate \"license_file\" used by Navicat 11."));
_putts(TEXT(" Specify \"-text\" to generate base64-encoded activation code."));
_putts(TEXT(" This parameter must be specified."));
_putts(TEXT(""));
_putts(TEXT(" [-adv] Enable advance mode."));
_putts(TEXT(" This parameter is optional."));
_putts(TEXT(""));
_putts(TEXT(" <RSA-2048 Private Key File> A path to an RSA-2048 private key file."));
_putts(TEXT(" This parameter must be specified."));
_putts(TEXT(""));
_putts(TEXT("Example:"));
_putts(TEXT(" navicat-keygen.exe -text .\\RegPrivateKey.pem"));
}
int _tmain(int argc, PTSTR argv[]) {
Welcome();
if (argc == 3 || argc == 4) {
nkg::fnCollectInformation* lpfnCollectInformation = nullptr;
nkg::fnGenerateLicense* lpfnGenerateLicense = nullptr;
if (_tcsicmp(argv[1], TEXT("-bin")) == 0) {
lpfnGenerateLicense = nkg::GenerateLicenseBinary;
} else if (_tcsicmp(argv[1], TEXT("-text")) == 0) {
lpfnGenerateLicense = nkg::GenerateLicenseText;
} else {
Help();
return -1;
}
if (argc == 4) {
if (_tcsicmp(argv[2], TEXT("-adv")) == 0) {
lpfnCollectInformation = nkg::CollectInformationAdvanced;
} else {
Help();
return -1;
}
} else {
lpfnCollectInformation = nkg::CollectInformationNormal;
}
try {
nkg::RSACipher Cipher;
Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(argv[argc - 1]);
if (Cipher.Bits() != 2048) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA key length mismatches."))
.AddHint(TEXT("You must provide an RSA key whose modulus length is 2048 bits."));
}
auto Generator = lpfnCollectInformation();
Generator.Generate();
Generator.ShowInConsole();
lpfnGenerateLicense(Cipher, Generator);
return 0;
} catch (nkg::UserAbortionError&) {
return -1;
} catch (nkg::Exception& e) {
_tprintf_s(TEXT("[-] %s:%zu ->\n"), e.File(), e.Line());
_tprintf_s(TEXT(" %s\n"), e.Message());
if (e.HasErrorCode()) {
_tprintf_s(TEXT(" %s (0x%zx)\n"), e.ErrorString(), e.ErrorCode());
}
for (auto& Hint : e.Hints()) {
_tprintf_s(TEXT(" Hints: %s\n"), Hint.c_str());
}
return -1;
} catch (std::exception& e) {
_tprintf_s(TEXT("[-] %hs\n"), e.what());
return -1;
}
} else {
Help();
return -1;
}
}
+251
View File
@@ -0,0 +1,251 @@
#include <stddef.h> // NOLINT
#include <stdint.h> // NOLINT
#include <iostream>
#include <vector>
#include <string>
#include "../common/RSACipher.hpp"
#include "NavicatKeygen.hpp"
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
template<int min_num, int max_num>
bool read_int(int& num, const char* prompt, const char* err_msg) {
int temp;
std::string input;
while (true) {
std::cout << prompt;
if (!std::getline(std::cin, input))
return false;
try {
temp = std::stoi(input, nullptr, 0);
if (min_num <= temp && temp <= max_num) {
num = temp;
return true;
} else {
throw std::invalid_argument(err_msg);
}
} catch (...) {
std::cout << err_msg << std::endl;
}
}
}
std::string base64_encode(const std::vector<uint8_t>& bindata);
std::vector<uint8_t> base64_decode(const std::string& ascdata);
void Help() {
std::cout << "***************************************************" << std::endl;
std::cout << "* Navicat Keygen by @DoubleLabyrinth *" << std::endl;
std::cout << "* Version: 4.0 *" << std::endl;
std::cout << "***************************************************" << std::endl;
std::cout << std::endl;
std::cout << "Usage:" << std::endl;
std::cout << " navicat-keygen <RSA-2048 Private Key File>" << std::endl;
std::cout << std::endl;
std::cout << " <RSA-2048 Private Key File> Path to a PEM-format RSA-2048 private key file." << std::endl;
std::cout << " This parameter must be specified." << std::endl;
std::cout << std::endl;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
Help();
return -1;
} else {
try {
std::cout << "***************************************************" << std::endl;
std::cout << "* Navicat Keygen by @DoubleLabyrinth *" << std::endl;
std::cout << "* Version: 4.0 *" << std::endl;
std::cout << "***************************************************" << std::endl;
std::cout << std::endl;
RSACipher RsaCipher;
int select_num;
NavicatKeygen keygen;
std::string username;
std::string organization;
std::string RequestCode_b64;
std::vector<uint8_t> RequestCode;
char RequestInfo[256] = {};
char ResponseInfo[256] = {};
std::vector<uint8_t> ResponseCode;
std::string ResponseCode_b64;
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
RsaCipher.ImportKeyFromFile<RSAKeyType::PrivateKey, RSAKeyFormat::PEM>(argv[1]);
if (RsaCipher.Bits() != 2048) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Not RSA-2048 private key file.");
}
keygen.SetProductSignature(NavicatKeygen::Product::Premium);
std::cout
<< "Which is your Navicat Premium language?" << std::endl
<< "0. English" << std::endl
<< "1. Simplified Chinese" << std::endl
<< "2. Traditional Chinese" << std::endl
<< "3. Japanese" << std::endl
<< "4. Polish" << std::endl
<< "5. Spanish" << std::endl
<< "6. French" << std::endl
<< "7. German" << std::endl
<< "8. Korean" << std::endl
<< "9. Russian" << std::endl
<< "10. Portuguese" << std::endl
<< std::endl;
if (read_int<0, 10>(select_num, "(Input index)> ", "Invalid index.")) {
keygen.SetLanguageSignature(static_cast<NavicatKeygen::Language>(select_num));
} else {
return -1;
}
std::cout << std::endl;
if (read_int<0, 15>(select_num, "(Input major version number, range: 0 ~ 15, default: 12)> ", "Invalid number.")) {
keygen.SetVersion(static_cast<uint8_t>(select_num));
} else {
return -1;
}
//
// Generate snKey
//
keygen.Generate();
std::cout << std::endl;
std::cout << "Serial number:" << std::endl;
std::cout << keygen.GetFormatedKey() << std::endl;
std::cout << std::endl;
//
// Get user name
//
std::cout << "Your name: ";
if (!std::getline(std::cin, username)) {
return -1;
}
//
// Get organization name
//
std::cout << "Your organization: ";
if (!std::getline(std::cin, organization)) {
return -1;
}
std::cout << std::endl;
//
// Get request code in base64
//
std::cout << "Input request code (in Base64), input empty line to end:" << std::endl;
while (true) {
std::string temp;
if (!std::getline(std::cin, temp))
return 0;
if (temp.empty())
break;
RequestCode_b64 += temp;
}
//
// Get request code in raw bytes
//
RequestCode = base64_decode(RequestCode_b64);
if (RequestCode.size() > ((RsaCipher.Bits() + 7) / 8)) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Request code is too long.");
}
//
// Decrypt to get request info
//
RsaCipher.Decrypt(RequestCode.data(), static_cast<int>(RequestCode.size()), RequestInfo, RSA_PKCS1_PADDING);
//
// print out request info
//
std::cout << "Request Info:" << std::endl;
std::cout << RequestInfo << std::endl;
std::cout << std::endl;
//
// Generate response info
//
json.Parse(RequestInfo);
json.RemoveMember("P"); // remove Platform info
N_Key.SetString("N", 1);
N_Value.SetString(username.c_str(), static_cast<rapidjson::SizeType>(username.length()));
O_Key.SetString("O", 1);
O_Value.SetString(organization.c_str(), static_cast<rapidjson::SizeType>(organization.length()));
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned>(std::time(nullptr)));
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Response info is too long.");
}
//
// print out response info
//
memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());
std::cout << "Response Info:" << std::endl;
std::cout << ResponseInfo << std::endl;
std::cout << std::endl;
//
// encrypt response info
//
ResponseCode.resize((RsaCipher.Bits() + 7) / 8);
RsaCipher.Encrypt<RSAKeyType::PrivateKey>(ResponseInfo, static_cast<int>(strlen(ResponseInfo)), ResponseCode.data(), RSA_PKCS1_PADDING);
//
// encode encrypted response info in base64 format
//
ResponseCode_b64 = base64_encode(ResponseCode);
//
// print out activation code
//
std::cout << "License:" << std::endl;
std::cout << ResponseCode_b64 << std::endl;
return 0;
} catch (nkg::Exception& e) {
std::cout << "[-] " << e.File() << ":" << e.Line() << " ->" << std::endl;
std::cout << " " << e.Message() << std::endl;
if (e.HasErrorCode()) {
std::cout << " " << e.ErrorString() << std::endl;
}
return -1;
}
}
}
-181
View File
@@ -1,181 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>navicatkeygen</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<VcpkgTriplet Condition="'$(Platform)'=='Win32'">x86-windows-static</VcpkgTriplet>
<VcpkgTriplet Condition="'$(Platform)'=='x64'">x64-windows-static</VcpkgTriplet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
<Import Project="..\common\common.vcxitems" Label="Shared" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CollectInformation.cpp" />
<ClCompile Include="GenerateLicense.cpp" />
<ClCompile Include="SerialNumberGenerator.cpp" />
<ClCompile Include="_tmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Base64.hpp" />
<ClInclude Include="SerialNumberGenerator.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="_tmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="SerialNumberGenerator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CollectInformation.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="GenerateLicense.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Base64.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="SerialNumberGenerator.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
</Project>
+63 -85
View File
@@ -1,98 +1,76 @@
#include "CapstoneDisassembler.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\CapstoneDisassembler.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
CapstoneDisassembler CapstoneDisassembler::Create(cs_arch ArchType, cs_mode Mode) {
CapstoneDisassembler NewDisassembler;
namespace nkg {
CapstoneDisassembler::CapstoneDisassembler(const CapstoneEngine& Engine) :
ResourceOwned<CapstoneInsnTraits>(cs_malloc(Engine)),
_Engine(Engine),
_CurrentState{},
_NextState{},
_lpCurrentInsn(nullptr)
{
if (IsValid() == false) {
throw CapstoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), cs_errno(Engine), TEXT("cs_malloc failed."));
}
auto err = cs_open(ArchType, Mode, NewDisassembler.pvt_Handle.GetAddress());
if (err != CS_ERR_OK) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::CapstoneError(__FILE__, __LINE__, err, "cs_open failed.");
}
CapstoneDisassembler::CapstoneDisassembler(CapstoneDisassembler&& Other) noexcept :
ResourceOwned<CapstoneInsnTraits>(static_cast<ResourceOwned<CapstoneInsnTraits>&&>(Other)),
_Engine(Other._Engine),
_CurrentState(Other._CurrentState),
_NextState(Other._NextState),
_lpCurrentInsn(Other._lpCurrentInsn) {}
CapstoneDisassembler& CapstoneDisassembler::SetContext(const CapstoneContext& Ctx) noexcept {
_lpCurrentInsn = nullptr;
_CurrentState.lpMachineCode = nullptr;
_CurrentState.cbMachineCode = 0;
_CurrentState.Address = 0;
_NextState = Ctx;
return *this;
NewDisassembler.pvt_Insn.TakeOver(cs_malloc(NewDisassembler.pvt_Handle));
if (NewDisassembler.pvt_Insn.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::CapstoneError(__FILE__, __LINE__, cs_errno(NewDisassembler.pvt_Handle), "cs_malloc failed.");
}
[[nodiscard]]
const CapstoneContext& CapstoneDisassembler::GetContext() const noexcept {
return _NextState;
return NewDisassembler;
}
void CapstoneDisassembler::Option(cs_opt_type Type, size_t Value) {
auto err = cs_option(pvt_Handle, Type, Value);
if (err != CS_ERR_OK) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::CapstoneError(__FILE__, __LINE__, err, "cs_option failed.");
}
[[nodiscard]]
bool CapstoneDisassembler::Next() noexcept {
bool bSucceed;
CapstoneContext backup = _NextState;
pvt_CurrentInsn = nullptr;
bSucceed = cs_disasm_iter(_Engine.Get(), reinterpret_cast<const uint8_t**>(&_NextState.lpMachineCode), &_NextState.cbMachineCode, &_NextState.Address, Get());
if (bSucceed) {
if (_lpCurrentInsn == nullptr) {
_lpCurrentInsn = Get();
}
_CurrentState = backup;
} else {
_lpCurrentInsn = nullptr;
}
return bSucceed;
}
[[nodiscard]]
const cs_insn* CapstoneDisassembler::GetInstruction() const noexcept {
return _lpCurrentInsn;
}
[[nodiscard]]
const CapstoneContext& CapstoneDisassembler::GetInstructionContext() const noexcept {
return _CurrentState;
}
CapstoneEngine::CapstoneEngine(cs_arch ArchType, cs_mode Mode) {
auto err = cs_open(ArchType, Mode, GetAddressOf());
if (err != CS_ERR_OK) {
throw CapstoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, TEXT("cs_open failed."));
}
}
void CapstoneEngine::Option(cs_opt_type Type, cs_opt_value Value) {
auto err = cs_option(Get(), Type, Value);
if (err != CS_ERR_OK) {
throw CapstoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, TEXT("cs_option failed."));
}
}
const char* CapstoneEngine::GetRegisterName(unsigned int reg_id) const noexcept {
return cs_reg_name(Get(), reg_id);
}
[[nodiscard]]
CapstoneDisassembler CapstoneEngine::CreateDisassembler() const {
return CapstoneDisassembler(*this);
pvt_Insn.TakeOver(cs_malloc(pvt_Handle));
if (pvt_Insn.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::CapstoneError(__FILE__, __LINE__, cs_errno(pvt_Handle), "cs_malloc failed.");
}
}
void CapstoneDisassembler::SetContext(uintptr_t lpOpcode, size_t cbOpcode, uint64_t Address) noexcept {
pvt_CurrentCtx.pbOpcode = reinterpret_cast<const uint8_t*>(lpOpcode);
pvt_CurrentCtx.cbOpcode = cbOpcode;
pvt_CurrentCtx.Address = Address;
pvt_CurrentInsn = nullptr;
}
void CapstoneDisassembler::SetContext(const void* lpOpcode, size_t cbOpcode, uint64_t Address) noexcept {
pvt_CurrentCtx.pbOpcode = reinterpret_cast<const uint8_t*>(lpOpcode);
pvt_CurrentCtx.cbOpcode = cbOpcode;
pvt_CurrentCtx.Address = Address;
pvt_CurrentInsn = nullptr;
}
const CapstoneDisassembler::Context& CapstoneDisassembler::GetContext() const noexcept {
return pvt_CurrentCtx;
}
const cs_insn* CapstoneDisassembler::GetInstruction() const noexcept {
return pvt_CurrentInsn;
}
CapstoneDisassembler::Context CapstoneDisassembler::GetInstructionContext() const noexcept {
Context CtxOfInsn = {};
CtxOfInsn.pbOpcode = pvt_CurrentCtx.pbOpcode - pvt_CurrentInsn->size;
CtxOfInsn.cbOpcode = pvt_CurrentCtx.cbOpcode + pvt_CurrentInsn->size;
CtxOfInsn.Address = pvt_CurrentCtx.Address - pvt_CurrentInsn->size;
return CtxOfInsn;
}
bool CapstoneDisassembler::Next() noexcept {
bool bSucceed = cs_disasm_iter(pvt_Handle, &pvt_CurrentCtx.pbOpcode, &pvt_CurrentCtx.cbOpcode, &pvt_CurrentCtx.Address, pvt_Insn);
if (bSucceed) {
if (pvt_CurrentInsn == nullptr) pvt_CurrentInsn = pvt_Insn.Get();
} else {
pvt_CurrentInsn = nullptr;
}
return bSucceed;
}
+33 -45
View File
@@ -1,61 +1,49 @@
#pragma once
#include "ExceptionCapstone.hpp"
#include <ResourceOwned.hpp>
#include <capstone/capstone.h>
#include "../common/ResourceOwned.hpp"
#include "ResourceTraitsCapstone.hpp"
namespace nkg {
class CapstoneDisassembler {
public:
struct CapstoneContext {
const void* lpMachineCode;
size_t cbMachineCode;
uint64_t Address;
struct Context {
const uint8_t* pbOpcode;
size_t cbOpcode;
uint64_t Address;
};
class CapstoneEngine;
private:
class CapstoneDisassembler : private ResourceOwned<CapstoneInsnTraits> {
friend class CapstoneEngine;
private:
ResourceOwned<CapstoneHandleTraits> pvt_Handle;
ResourceOwned<CapstoneInsnTraits> pvt_Insn;
Context pvt_CurrentCtx;
cs_insn* pvt_CurrentInsn;
const CapstoneEngine& _Engine;
CapstoneContext _CurrentState;
CapstoneContext _NextState;
cs_insn* _lpCurrentInsn;
CapstoneDisassembler() noexcept :
pvt_Handle(CapstoneHandleTraits{}),
pvt_Insn(CapstoneInsnTraits{}),
pvt_CurrentCtx{},
pvt_CurrentInsn(nullptr) {}
public:
CapstoneDisassembler(const CapstoneEngine& Engine);
[[nodiscard]]
static CapstoneDisassembler Create(cs_arch ArchType, cs_mode Mode);
public:
void Option(cs_opt_type Type, size_t Value);
CapstoneDisassembler(CapstoneDisassembler&& Other) noexcept;
void SetContext(uintptr_t lpOpcode, size_t cbOpcode, uint64_t Address = 0) noexcept ;
CapstoneDisassembler& SetContext(const CapstoneContext& Ctx) noexcept;
void SetContext(const void* lpOpcode, size_t cbOpcode, uint64_t Address = 0) noexcept;
[[nodiscard]]
const CapstoneContext& GetContext() const noexcept;
[[nodiscard]]
const Context& GetContext() const noexcept;
[[nodiscard]]
bool Next() noexcept;
[[nodiscard]]
const cs_insn* GetInstruction() const noexcept;
[[nodiscard]]
const cs_insn* GetInstruction() const noexcept;
[[nodiscard]]
const CapstoneContext& GetInstructionContext() const noexcept;
};
class CapstoneEngine : private ResourceOwned<CapstoneHandleTraits> {
friend class CapstoneDisassembler;
public:
CapstoneEngine(cs_arch ArchType, cs_mode Mode);
void Option(cs_opt_type Type, cs_opt_value Value);
const char* GetRegisterName(unsigned int reg_id) const noexcept;
[[nodiscard]]
CapstoneDisassembler CreateDisassembler() const;
};
}
[[nodiscard]]
Context GetInstructionContext() const noexcept;
[[nodiscard]]
bool Next() noexcept;
};
+12 -11
View File
@@ -1,5 +1,5 @@
#pragma once
#include <Exception.hpp>
#include "../common/Exception.hpp"
#include <capstone/capstone.h>
namespace nkg {
@@ -7,29 +7,30 @@ namespace nkg {
class CapstoneError final : public Exception {
private:
cs_err _ErrorCode;
std::xstring _ErrorString;
cs_err pvt_ErrorCode;
public:
CapstoneError(PCTSTR SourceFile, SIZE_T SourceLine, cs_err CapstoneErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(CapstoneErrorCode),
_ErrorString(std::xstring_extension{}, cs_strerror(CapstoneErrorCode), CP_UTF8) {}
CapstoneError(const char* File, unsigned Line, cs_err ErrorCode, const char* Message) noexcept :
Exception(File, Line, Message),
pvt_ErrorCode(ErrorCode) {}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual intptr_t ErrorCode() const noexcept override {
return pvt_ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
return cs_strerror(pvt_ErrorCode);
}
};
+12 -12
View File
@@ -1,5 +1,5 @@
#pragma once
#include <Exception.hpp>
#include "../common/Exception.hpp"
#include <keystone/keystone.h>
namespace nkg {
@@ -7,31 +7,31 @@ namespace nkg {
class KeystoneError final : public Exception {
private:
ks_err _ErrorCode;
std::xstring _ErrorString;
ks_err pvt_ErrorCode;
public:
KeystoneError(PCTSTR SourceFile, SIZE_T SourceLine, ks_err KeystoneErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(KeystoneErrorCode),
_ErrorString(std::xstring_extension{}, ks_strerror(KeystoneErrorCode), CP_UTF8) {}
KeystoneError(const char* File, unsigned Line, ks_err ErrorCode, const char* Message) noexcept :
Exception(File, Line, Message),
pvt_ErrorCode(ErrorCode) {}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual intptr_t ErrorCode() const noexcept override {
return pvt_ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
return ks_strerror(pvt_ErrorCode);
}
};
}
+70
View File
@@ -0,0 +1,70 @@
#include <string.h> // NOLINT
#include "ExceptionCapstone.hpp"
#include "CapstoneDisassembler.hpp"
#include "X64ImageInterpreter.hpp"
namespace nkg {
bool IsResolvedTo(const X64ImageInterpreter& Image, const void* StubHelperProc, const char *Symbol) {
CapstoneDisassembler Disassembler = CapstoneDisassembler::Create(CS_ARCH_X86, CS_MODE_64);
Disassembler.Option(CS_OPT_DETAIL, CS_OPT_ON);
// A stub-helper proc must look like:
// push xxxxh;
// jmp loc_xxxxxxxx
// which should be 10 bytes long.
Disassembler.SetContext(StubHelperProc, 10);
if (Disassembler.Next() == false) {
return false;
}
auto insn = Disassembler.GetInstruction();
if (strcasecmp(insn->mnemonic, "push") != 0 || insn->detail->x86.operands[0].type != X86_OP_IMM) {
return false;
}
auto bind_opcode_offset = static_cast<uint32_t>(insn->detail->x86.operands[0].imm);
if (Image.CommandOf<LC_DYLD_INFO_ONLY>() == nullptr) {
return false;
}
auto bind_opcode_ptr =
Image.ImageOffset<uint8_t*>(Image.CommandOf<LC_DYLD_INFO_ONLY>()->lazy_bind_off) +
bind_opcode_offset;
while ((*bind_opcode_ptr & BIND_OPCODE_MASK) != BIND_OPCODE_DONE) {
switch (*bind_opcode_ptr & BIND_OPCODE_MASK) {
case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: // 0x10
case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: // 0x30
case BIND_OPCODE_SET_TYPE_IMM: // 0x50
case BIND_OPCODE_DO_BIND: // 0x90
case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: // 0xB0
++bind_opcode_ptr;
break;
case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: // 0x20
case BIND_OPCODE_SET_ADDEND_SLEB: // 0x60
case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: // 0x70
case BIND_OPCODE_ADD_ADDR_ULEB: // 0x80
case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: // 0xA0
while (*(++bind_opcode_ptr) & 0x80u);
++bind_opcode_ptr;
break;
case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: // 0x40
return strcmp(reinterpret_cast<const char *>(bind_opcode_ptr + 1), Symbol) == 0;
case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: // 0xC0
//
// This opcode is too rare to appear,
// It is okay to dismiss this opcode
//
return false;
default:
return false;
}
}
return false;
}
}
+96
View File
@@ -0,0 +1,96 @@
#include <stddef.h> // NOLINT
#include <stdint.h> // NOLINT
#include <stdio.h> // NOLINT
#include <signal.h> // NOLINT
#include <setjmp.h> // NOLINT
static jmp_buf env;
static void SIGSEGV_Handler(int sig) {
siglongjmp(env, 1);
}
//
// read byte(s) at address `p` as __Type to `out`
// succeed if return true, otherwise return false
//
template<typename __Type>
static inline bool ProbeForRead(const void* p, void* out) {
int r = sigsetjmp(env, 1);
if (r == 0) {
*reinterpret_cast<__Type*>(out) = *reinterpret_cast<const __Type*>(p);
return true;
} else {
return false;
}
}
//
// Print memory data in [from, to) at least
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
namespace nkg {
void PrintMemory(const void *from, const void *to, const void *base) {
auto start = reinterpret_cast<const uint8_t *>(from);
auto end = reinterpret_cast<const uint8_t *>(to);
auto base_ptr = reinterpret_cast<const uint8_t *>(base);
if (start >= end)
return;
while (reinterpret_cast<uintptr_t>(start) % 16)
start--;
while (reinterpret_cast<uintptr_t>(end) % 16)
end++;
void (*prev_handler)(int) = signal(SIGSEGV, SIGSEGV_Handler);
while (start < end) {
uint16_t value[16] = {};
if (base_ptr) {
uintptr_t d = start >= base ? start - base_ptr : base_ptr - start;
if (start >= base) {
printf("+0x%.*zx ", static_cast<int>(2 * sizeof(void *)), d);
} else {
printf("-0x%.*zx ", static_cast<int>(2 * sizeof(void *)), d);
}
} else {
printf("0x%.*zx ", static_cast<int>(2 * sizeof(void *)), reinterpret_cast<uintptr_t >(start));
}
for (int i = 0; i < 16; ++i) {
if (start + i < from) {
printf(" ");
value[i] = 0xfffe;
} else if (ProbeForRead<uint8_t>(start + i, value + i)) {
printf("%02x ", value[i]);
} else {
printf("?? ");
value[i] = 0xffff;
}
}
printf(" ");
for (int i = 0; i < 16; ++i) { // NOLINT
if (0x20 <= value[i] && value[i] < 0x7f) {
printf("%c", value[i]);
} else if (value[i] == 0xfffe) {
printf(" ");
} else {
printf(".");
}
}
printf("\n");
start += 0x10;
}
signal(SIGSEGV, prev_handler);
}
}
-342
View File
@@ -1,342 +0,0 @@
#include "ImageInterpreter.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\ImageInterpreter.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
ImageInterpreter::ImageInterpreter() :
_DosHeader(nullptr),
_NtHeaders(nullptr),
_SectionHeaderTable(nullptr),
_VsFixedFileInfo(nullptr) {}
[[nodiscard]]
ImageInterpreter ImageInterpreter::ParseImage(PVOID ImageBase, bool DisableRelocationParsing) {
ImageInterpreter NewImage;
NewImage._DosHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(ImageBase);
if (NewImage._DosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (DOS signature check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid WinPE file?"));
}
NewImage._NtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(
reinterpret_cast<uint8_t*>(ImageBase) + NewImage._DosHeader->e_lfanew
);
if (NewImage._NtHeaders->Signature != IMAGE_NT_SIGNATURE) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (NT signature check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid WinPE file?"));
}
#if defined(_M_AMD64)
if (NewImage._NtHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Optional header magic check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 64-bits WinPE file?"));
}
if (NewImage._NtHeaders->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Machine check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 64-bits WinPE file?"));
}
#elif defined(_M_IX86)
if (NewImage._NtHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Optional header magic check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 32-bits WinPE file?"));
}
if (NewImage._NtHeaders->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Machine check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 32-bits WinPE file?"));
}
#else
#error "Unsupported architecture."
#endif
NewImage._SectionHeaderTable = reinterpret_cast<PIMAGE_SECTION_HEADER>(
reinterpret_cast<char*>(&NewImage._NtHeaders->OptionalHeader) + NewImage._NtHeaders->FileHeader.SizeOfOptionalHeader
);
for (WORD i = 0; i < NewImage._NtHeaders->FileHeader.NumberOfSections; ++i) {
uint64_t SectionName = *reinterpret_cast<uint64_t*>(NewImage._SectionHeaderTable[i].Name);
if (NewImage._SectionNameTable.find(SectionName) == NewImage._SectionNameTable.end()) {
NewImage._SectionNameTable[SectionName] = i;
}
NewImage._SectionRvaTable[NewImage._SectionHeaderTable[i].VirtualAddress] = i;
NewImage._SectionFileOffsetTable[NewImage._SectionHeaderTable[i].PointerToRawData] = i;
}
if (!DisableRelocationParsing && NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress != 0) {
auto RelocTableRva = NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
auto RelocTable = NewImage.RvaToPointer<PIMAGE_BASE_RELOCATION>(RelocTableRva);
while (RelocTable->VirtualAddress != 0) {
uintptr_t Rva = RelocTable->VirtualAddress;
PWORD RelocItems = reinterpret_cast<PWORD>(RelocTable + 1);
DWORD RelocItemsCount = (RelocTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
for (DWORD i = 0; i < RelocItemsCount; ++i) {
auto RelocType = RelocItems[i] >> 12;
switch (RelocType) {
case IMAGE_REL_BASED_ABSOLUTE:
break;
case IMAGE_REL_BASED_HIGH:
case IMAGE_REL_BASED_LOW:
case IMAGE_REL_BASED_HIGHADJ:
NewImage._RelocationRvaTable[Rva + (RelocItems[i] & 0x0fff)] = 2;
break;
case IMAGE_REL_BASED_HIGHLOW:
NewImage._RelocationRvaTable[Rva + (RelocItems[i] & 0x0fff)] = 4;
break;
#if defined(IMAGE_REL_BASED_DIR64)
case IMAGE_REL_BASED_DIR64:
NewImage._RelocationRvaTable[Rva + (RelocItems[i] & 0x0fff)] = 8;
break;
#endif
default:
break;
}
}
RelocTable = reinterpret_cast<PIMAGE_BASE_RELOCATION>(&RelocItems[RelocItemsCount]);
}
}
if (NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress) {
uintptr_t ResourceRva = NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
auto ResourceTypeTable =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DIRECTORY>(ResourceRva);
auto ResourceTypeNameEntries =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(ResourceTypeTable + 1);
auto ResourceTypeIdEntries =
ResourceTypeNameEntries + ResourceTypeTable->NumberOfNamedEntries;
bool VS_FII_Ok = false;
for (WORD i = 0; i < ResourceTypeTable->NumberOfIdEntries && !VS_FII_Ok; ++i) {
if (ResourceTypeIdEntries[i].Id == reinterpret_cast<uintptr_t>(RT_VERSION) && ResourceTypeIdEntries[i].DataIsDirectory) {
auto ResourceNameTable =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DIRECTORY>(ResourceRva + ResourceTypeIdEntries[i].OffsetToDirectory);
auto ResourceNameNameEntries =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(ResourceNameTable + 1);
auto ResourceNameIdEntries =
ResourceNameNameEntries + ResourceNameTable->NumberOfNamedEntries;
for (WORD j = 0; j < ResourceNameTable->NumberOfIdEntries && !VS_FII_Ok; ++j) {
if (ResourceNameIdEntries[j].Id == VS_VERSION_INFO && ResourceNameIdEntries[j].DataIsDirectory) {
auto ResourceLangTable =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DIRECTORY>(ResourceRva + ResourceNameIdEntries[j].OffsetToDirectory);
auto ResourceLangNameEntries =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(ResourceLangTable + 1);
auto ResourceLangIdEntries =
ResourceLangNameEntries + ResourceLangTable->NumberOfNamedEntries;
for (WORD k = 0; k < ResourceLangTable->NumberOfIdEntries && !VS_FII_Ok; ++k) {
if (ResourceLangIdEntries[k].Id == MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) && !ResourceLangIdEntries[k].DataIsDirectory) {
auto ResourceDataEntry =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DATA_ENTRY>(ResourceRva + ResourceLangIdEntries[k].OffsetToData);
auto VsVersionInfo = NewImage.RvaToPointer<PBYTE>(ResourceDataEntry->OffsetToData);
auto VsVersionInfoszKey = reinterpret_cast<PWSTR>(VsVersionInfo + 6);
if (_wcsicmp(VsVersionInfoszKey, L"VS_VERSION_INFO") == 0) {
auto p = reinterpret_cast<PBYTE>(VsVersionInfoszKey + _countof(L"VS_VERSION_INFO"));
while (NewImage.PointerToRva(p) % sizeof(DWORD)) {
++p;
}
if (reinterpret_cast<VS_FIXEDFILEINFO*>(p)->dwSignature == VS_FFI_SIGNATURE) {
NewImage._VsFixedFileInfo = reinterpret_cast<VS_FIXEDFILEINFO*>(p);
VS_FII_Ok = true;
}
}
}
}
}
}
}
}
}
return NewImage;
}
[[nodiscard]]
PIMAGE_DOS_HEADER ImageInterpreter::ImageDosHeader() const noexcept {
return _DosHeader;
}
[[nodiscard]]
PIMAGE_NT_HEADERS ImageInterpreter::ImageNtHeaders() const noexcept {
return _NtHeaders;
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionTable() const noexcept {
return _SectionHeaderTable;
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeader(size_t Idx) const {
if (Idx < _NtHeaders->FileHeader.NumberOfSections) {
return _SectionHeaderTable + Idx;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Idx is out of range."));
}
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeaderByName(PCSTR lpszSectionName) const {
uint64_t NameValue = 0;
for (int i = 0; i < sizeof(NameValue) && lpszSectionName[i]; ++i)
reinterpret_cast<PSTR>(&NameValue)[i] = lpszSectionName[i];
auto it = _SectionNameTable.find(NameValue);
if (it == _SectionNameTable.end()) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Target section header is not found."))
.AddHint(std::xstring::format(TEXT("lpszSectionName = %s"), lpszSectionName));
}
return &_SectionHeaderTable[it->second];
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeaderByRva(uintptr_t Rva) const {
auto it = _SectionRvaTable.upper_bound(Rva);
if (it != _SectionRvaTable.begin()) {
--it;
}
auto SectionHeader = &_SectionHeaderTable[it->second];
uintptr_t SectionRvaBegin = SectionHeader->VirtualAddress;
uintptr_t SectionRvaEnd = SectionRvaBegin + SectionHeader->Misc.VirtualSize;
if (SectionRvaBegin <= Rva && Rva < SectionRvaEnd) {
return SectionHeader;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Target section header is not found."))
.AddHint(std::xstring::format(TEXT("Rva = 0x%zx"), Rva));
}
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeaderByVa(uintptr_t Va) const {
return ImageSectionHeaderByRva(Va - _NtHeaders->OptionalHeader.ImageBase);
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeaderByFileOffset(uintptr_t FileOffset) const {
auto it = _SectionFileOffsetTable.upper_bound(FileOffset);
if (it != _SectionFileOffsetTable.begin()) {
--it;
}
auto SectionHeader = &_SectionHeaderTable[it->second];
uintptr_t SectionFileOffsetBegin = SectionHeader->PointerToRawData;
uintptr_t SectionFileOffsetEnd = SectionFileOffsetBegin + SectionHeader->SizeOfRawData;
if (SectionFileOffsetBegin <= FileOffset && FileOffset < SectionFileOffsetEnd) {
return SectionHeader;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Target section header is not found."))
.AddHint(std::xstring::format(TEXT("FileOffset = 0x%zx"), FileOffset));
}
}
[[nodiscard]]
uintptr_t ImageInterpreter::RvaToVa(uintptr_t Rva) const noexcept {
return Rva + _NtHeaders->OptionalHeader.ImageBase;
}
[[nodiscard]]
uintptr_t ImageInterpreter::RvaToFileOffset(uintptr_t Rva) const {
auto SectionHeader = ImageSectionHeaderByRva(Rva);
return SectionHeader->PointerToRawData + (Rva - static_cast<uintptr_t>(SectionHeader->VirtualAddress));
}
[[nodiscard]]
uintptr_t ImageInterpreter::FileOffsetToRva(uintptr_t FileOffset) const {
auto SectionHeader = ImageSectionHeaderByFileOffset(FileOffset);
return SectionHeader->VirtualAddress + (FileOffset - SectionHeader->PointerToRawData);
}
[[nodiscard]]
uintptr_t ImageInterpreter::FileOffsetToVa(uintptr_t FileOffset) const {
return FileOffsetToRva(FileOffset) + _NtHeaders->OptionalHeader.ImageBase;
}
[[nodiscard]]
uintptr_t ImageInterpreter::VaToRva(uintptr_t Va) const noexcept {
return Va - _NtHeaders->OptionalHeader.ImageBase;
}
[[nodiscard]]
uintptr_t ImageInterpreter::VaToFileOffset(uintptr_t Va) const {
return ImageSectionHeaderByVa(Va)->PointerToRawData;
}
[[nodiscard]]
bool ImageInterpreter::IsRvaRangeInRelocTable(uintptr_t Rva, size_t Size) const {
auto it = _RelocationRvaTable.upper_bound(Rva);
if (it != _RelocationRvaTable.begin()) {
--it;
}
return it->first <= Rva && Rva < it->first + it->second;
}
[[nodiscard]]
bool ImageInterpreter::IsVaRangeInRelocTable(uintptr_t Va, size_t Size) const {
return IsRvaRangeInRelocTable(VaToRva(Va), Size);
}
[[nodiscard]]
bool ImageInterpreter::IsFileOffsetRangeInRelocTable(uintptr_t FileOffset, size_t Size) const {
return IsRvaRangeInRelocTable(FileOffsetToRva(FileOffset), Size);
}
[[nodiscard]]
DWORD ImageInterpreter::ImageFileMajorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwFileVersionMS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
[[nodiscard]]
DWORD ImageInterpreter::ImageFileMinorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwFileVersionLS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
[[nodiscard]]
DWORD ImageInterpreter::ImageProductMajorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwProductVersionMS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
[[nodiscard]]
DWORD ImageInterpreter::ImageProductMinorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwProductVersionLS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
[[nodiscard]]
size_t ImageInterpreter::NumberOfSections() const noexcept {
return _NtHeaders->FileHeader.NumberOfSections;
}
}
-238
View File
@@ -1,238 +0,0 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <Exception.hpp>
#include <windows.h>
#include <map>
#include <utility>
#include <type_traits>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\ImageInterpreter.hpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
class ImageInterpreter {
private:
PIMAGE_DOS_HEADER _DosHeader;
PIMAGE_NT_HEADERS _NtHeaders;
PIMAGE_SECTION_HEADER _SectionHeaderTable;
std::map<uint64_t, size_t> _SectionNameTable;
std::map<uintptr_t, size_t> _SectionRvaTable;
std::map<uintptr_t, size_t> _SectionFileOffsetTable;
std::map<uintptr_t, size_t> _RelocationRvaTable;
VS_FIXEDFILEINFO* _VsFixedFileInfo;
ImageInterpreter();
public:
[[nodiscard]]
static ImageInterpreter ParseImage(PVOID PtrToImageBase, bool DisableRelocationParsing = false);
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageBase() const noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__PtrType>(_DosHeader);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageOffset(size_t Offset) const noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__PtrType>(reinterpret_cast<char*>(_DosHeader) + Offset);
}
[[nodiscard]]
PIMAGE_DOS_HEADER ImageDosHeader() const noexcept;
[[nodiscard]]
PIMAGE_NT_HEADERS ImageNtHeaders() const noexcept;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionTable() const noexcept;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeader(size_t Idx) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeaderByName(PCSTR lpszSectionName) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeaderByRva(uintptr_t Rva) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeaderByVa(uintptr_t Va) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeaderByFileOffset(uintptr_t FileOffset) const;
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionView(PIMAGE_SECTION_HEADER SectionHeader, size_t Offset = 0) const noexcept {
return ImageOffset<__PtrType>(SectionHeader->PointerToRawData + Offset);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionViewByName(PCSTR lpszSectionName, size_t Offset = 0) const {
return ImageOffset<__PtrType>(ImageSectionHeaderByName(lpszSectionName)->PointerToRawData + Offset);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionViewByRva(uintptr_t Rva, size_t Offset = 0) const {
return ImageOffset<__PtrType>(ImageSectionHeaderByRva(Rva)->PointerToRawData + Offset);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionViewByVa(uintptr_t Va, size_t Offset = 0) const {
return ImageOffset<__PtrType>(ImageSectionHeaderByVa(Va)->PointerToRawData + Offset);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionViewByFileOffset(uintptr_t FileOffset, size_t Offset = 0) const {
return ImageOffset<__PtrType>(ImageSectionHeaderByFileOffset(FileOffset)->PointerToRawData + Offset);
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PIMAGE_SECTION_HEADER SectionHeader, __Hint&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto begin = ImageSectionView<const uint8_t*>(SectionHeader);
auto end = begin + SectionHeader->Misc.VirtualSize;
for (; begin < end; ++begin) {
if (Hint(begin) == true) {
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(begin));
}
}
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Data is not found."));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PIMAGE_SECTION_HEADER SectionHeader, size_t Offset, __Hint&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto begin = ImageSectionView<const uint8_t*>(SectionHeader) + Offset;
auto end = begin + SectionHeader->Misc.VirtualSize;
for (; begin < end; ++begin) {
if (Hint(begin) == true) {
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(begin));
}
}
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Data is not found."));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PCSTR lpszSectionName, __Hint&& Hint) const {
return SearchSection<__ReturnType>(ImageSectionHeaderByName(lpszSectionName), std::forward<__Hint>(Hint));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PCSTR lpszSectionName, size_t Offset, __Hint&& Hint) const {
return SearchSection<__ReturnType>(ImageSectionHeaderByName(lpszSectionName), Offset, std::forward<__Hint>(Hint));
}
[[nodiscard]]
uintptr_t RvaToVa(uintptr_t Rva) const noexcept;
[[nodiscard]]
uintptr_t RvaToFileOffset(uintptr_t Rva) const;
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType RvaToPointer(uintptr_t Rva) const {
static_assert(std::is_pointer_v<__PtrType>);
return ImageOffset<__PtrType>(RvaToFileOffset(Rva));
}
[[nodiscard]]
uintptr_t FileOffsetToRva(uintptr_t FileOffset) const;
[[nodiscard]]
uintptr_t FileOffsetToVa(uintptr_t FileOffset) const;
template<typename __PtrType>
[[nodiscard]]
__PtrType FileOffsetToPointer(uintptr_t FileOffset) const noexcept {
return ImageOffset<__PtrType>(FileOffset);
}
[[nodiscard]]
uintptr_t VaToRva(uintptr_t Va) const noexcept;
[[nodiscard]]
uintptr_t VaToFileOffset(uintptr_t Va) const;
template<typename __PtrType>
[[nodiscard]]
__PtrType VaToPointer(uintptr_t Va) const noexcept {
return RvaToPointer<__PtrType>(VaToRva(Va));
}
template<typename __PtrType>
[[nodiscard]]
uintptr_t PointerToFileOffset(__PtrType Ptr) const noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<const volatile char*>(Ptr) - reinterpret_cast<const volatile char*>(_DosHeader);
}
template<typename __PtrType>
[[nodiscard]]
uintptr_t PointerToRva(__PtrType Ptr) const {
return FileOffsetToRva(PointerToFileOffset(Ptr));
}
template<typename __PtrType>
[[nodiscard]]
uintptr_t PointerToVa(__PtrType Ptr) const {
return FileOffsetToVa(PointerToFileOffset(Ptr));
}
[[nodiscard]]
bool IsRvaRangeInRelocTable(uintptr_t Rva, size_t Size) const;
[[nodiscard]]
bool IsVaRangeInRelocTable(uintptr_t Va, size_t Size) const;
[[nodiscard]]
bool IsFileOffsetRangeInRelocTable(uintptr_t FileOffset, size_t Size) const;
template<typename __PtrType>
[[nodiscard]]
bool IsFileOffsetRangeInRelocTable(__PtrType Ptr, size_t Size) const {
return IsRvaRangeInRelocTable(PointerToRva(Ptr), Size);
}
[[nodiscard]]
DWORD ImageFileMajorVersion() const;
[[nodiscard]]
DWORD ImageFileMinorVersion() const;
[[nodiscard]]
DWORD ImageProductMajorVersion() const;
[[nodiscard]]
DWORD ImageProductMinorVersion() const;
[[nodiscard]]
size_t NumberOfSections() const noexcept;
};
}
+41 -35
View File
@@ -1,44 +1,50 @@
#include "KeystoneAssembler.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\KeystoneAssembler.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
[[nodiscard]]
KeystoneAssembler KeystoneAssembler::Create(ks_arch ArchType, ks_mode Mode) {
KeystoneAssembler NewAssembler;
namespace nkg {
KeystoneAssembler::KeystoneAssembler(const KeystoneEngine& Engine) noexcept :
_Engine(Engine) {}
[[nodiscard]]
std::vector<uint8_t> KeystoneAssembler::GenerateMachineCode(const char* AssemblyCode, uint64_t Address) const {
ResourceOwned pbMachineCode(KeystoneMallocTraits{});
size_t cbMachineCode = 0;
size_t InstructionsProcessed = 0;
if (ks_asm(_Engine, AssemblyCode, Address, pbMachineCode.GetAddressOf(), &cbMachineCode, &InstructionsProcessed) != 0) {
throw KeystoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ks_errno(_Engine), TEXT("ks_asm failed."));
}
return std::vector<uint8_t>(pbMachineCode.Get(), pbMachineCode.Get() + cbMachineCode);
auto err = ks_open(ArchType, Mode, NewAssembler.pvt_Engine.GetAddress());
if (err != KS_ERR_OK) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::KeystoneError(__FILE__, __LINE__, err, "ks_open failed.");
}
KeystoneEngine::KeystoneEngine(ks_arch ArchType, ks_mode Mode) {
auto err = ks_open(ArchType, Mode, GetAddressOf());
if (err != KS_ERR_OK) {
throw KeystoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, TEXT("ks_open failed."));
}
}
return NewAssembler;
}
void KeystoneEngine::Option(ks_opt_type Type, ks_opt_value Value) {
auto err = ks_option(Get(), Type, Value);
if (err != KS_ERR_OK) {
throw KeystoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, TEXT("ks_option failed."));
}
}
KeystoneAssembler KeystoneEngine::CreateAssembler() const {
return KeystoneAssembler(*this);
void KeystoneAssembler::Option(ks_opt_type Type, size_t Value) {
auto err = ks_option(pvt_Engine, Type, Value);
if (err != KS_ERR_OK) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::KeystoneError(__FILE__, __LINE__, err, "ks_open failed.");
}
}
[[nodiscard]]
std::vector<uint8_t> KeystoneAssembler::GenerateOpcode(const char *AssemblyCode, uint64_t Address) const {
ResourceOwned pbOpcode(KeystoneMallocTraits{});
size_t cbOpCode = 0;
size_t InstructionsProcessed = 0;
if (ks_asm(pvt_Engine, AssemblyCode, Address, pbOpcode.GetAddress(), &cbOpCode, &InstructionsProcessed) != 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::KeystoneError(__FILE__, __LINE__, ks_errno(pvt_Engine), "ks_asm failed.");
}
return std::vector<uint8_t>(pbOpcode.Get(), pbOpcode.Get() + cbOpCode);
}
[[nodiscard]]
std::vector<uint8_t> KeystoneAssembler::GenerateOpcode(const std::string& AssemblyCode, uint64_t Address) const {
ResourceOwned pbOpcode(KeystoneMallocTraits{});
size_t cbOpCode = 0;
size_t InstructionsProcessed = 0;
if (ks_asm(pvt_Engine, AssemblyCode.c_str(), Address, pbOpcode.GetAddress(), &cbOpCode, &InstructionsProcessed) != 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::KeystoneError(__FILE__, __LINE__, ks_errno(pvt_Engine), "ks_asm failed.");
}
return std::vector<uint8_t>(pbOpcode.Get(), pbOpcode.Get() + cbOpCode);
}
+17 -28
View File
@@ -1,39 +1,28 @@
#pragma once
#include "ExceptionKeystone.hpp"
#include <ResourceOwned.hpp>
#include <keystone/keystone.h>
#include "../common/ResourceOwned.hpp"
#include "ResourceTraitsKeystone.hpp"
#include <vector>
#include <string>
namespace nkg {
class KeystoneAssembler {
private:
class KeystoneEngine;
ResourceOwned<KeystoneHandleTraits> pvt_Engine;
class KeystoneAssembler {
friend class KeystoneEngine;
private:
KeystoneAssembler() noexcept :
pvt_Engine(KeystoneHandleTraits{}) {}
public:
const KeystoneEngine& _Engine;
[[nodiscard]]
static KeystoneAssembler Create(ks_arch ArchType, ks_mode Mode);
KeystoneAssembler(const KeystoneEngine& Engine) noexcept;
void Option(ks_opt_type Type, size_t Value);
public:
[[nodiscard]]
std::vector<uint8_t> GenerateOpcode(const char* AssemblyCode, uint64_t Address = 0) const;
[[nodiscard]]
std::vector<uint8_t> GenerateMachineCode(const char* AssemblyCode, uint64_t Address = 0) const;
};
class KeystoneEngine : private ResourceOwned<KeystoneHandleTraits> {
friend class KeystoneAssembler;
public:
KeystoneEngine(ks_arch ArchType, ks_mode Mode);
void Option(ks_opt_type Type, ks_opt_value Value);
[[nodiscard]]
KeystoneAssembler CreateAssembler() const;
};
}
[[nodiscard]]
std::vector<uint8_t> GenerateOpcode(const std::string& AssemblyCode, uint64_t Address = 0) const;
};
-176
View File
@@ -1,176 +0,0 @@
#include <stddef.h>
#include <stdint.h>
#include <tchar.h>
#include <windows.h>
#include <ExceptionWin32.hpp>
#include <xstring.hpp>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\Misc.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
template<typename __Type>
static inline bool ProbeForRead(const void* p, void* out) {
__try {
*reinterpret_cast<__Type*>(out) = *reinterpret_cast<const __Type*>(p);
return true;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
}
//
// Print memory data in [lpMemBegin, lpMemEnd)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMemBegin, const void* lpMemEnd, const void* lpBase) noexcept {
auto pbBegin = reinterpret_cast<const uint8_t*>(lpMemBegin);
auto pbEnd = reinterpret_cast<const uint8_t*>(lpMemEnd);
auto pbBase = reinterpret_cast<const uint8_t*>(lpBase);
if (pbBegin >= pbEnd)
return;
while (reinterpret_cast<uintptr_t>(pbBegin) % 16)
pbBegin--;
while (reinterpret_cast<uintptr_t>(pbEnd) % 16)
pbEnd++;
while (pbBegin < pbEnd) {
uint16_t Values[16] = {};
if (pbBase) {
uintptr_t d = pbBegin >= lpBase ? pbBegin - pbBase : pbBase - pbBegin;
if (pbBegin >= lpBase) {
_tprintf_s(TEXT("+0x%.*zx "), static_cast<int>(2 * sizeof(void*)), d);
} else {
_tprintf_s(TEXT("-0x%.*zx "), static_cast<int>(2 * sizeof(void*)), d);
}
} else {
_tprintf_s(TEXT("0x%.*zx "), static_cast<int>(2 * sizeof(void*)), reinterpret_cast<uintptr_t>(pbBegin));
}
for (int i = 0; i < 16; ++i) {
if (pbBegin + i < lpMemBegin || pbBegin + i >= lpMemEnd) {
_tprintf_s(TEXT(" "));
Values[i] = 0xfffe;
} else if (ProbeForRead<uint8_t>(pbBegin + i, Values + i)) {
_tprintf_s(TEXT("%02x "), Values[i]);
} else {
_tprintf_s(TEXT("?? "));
Values[i] = 0xffff;
}
}
_tprintf_s(TEXT(" "));
for (int i = 0; i < 16; ++i) { // NOLINT
if (0x20 <= Values[i] && Values[i] < 0x7f) {
_tprintf_s(TEXT("%c"), Values[i]);
} else if (Values[i] == 0xfffe) {
_tprintf_s(TEXT(" "));
} else {
_tprintf_s(TEXT("."));
}
}
_tprintf_s(TEXT("\n"));
pbBegin += 0x10;
}
}
//
// Print memory data in [lpMem, lpMem + cbMem)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMem, size_t cbMem, const void* lpBase) noexcept {
PrintMemory(lpMem, reinterpret_cast<const uint8_t*>(lpMem) + cbMem, lpBase);
}
void PrintBytes(const void* lpMemBegin, const void* lpMemEnd) noexcept {
auto pbMemBegin = reinterpret_cast<const uint8_t*>(lpMemBegin);
auto pbMemEnd = reinterpret_cast<const uint8_t*>(lpMemEnd);
if (pbMemBegin < pbMemEnd) {
uint8_t v;
if (ProbeForRead<uint8_t>(pbMemBegin, &v)) {
_tprintf_s(TEXT("%.2x"), v);
} else {
_tprintf_s(TEXT("??"));
}
++pbMemBegin;
}
while (pbMemBegin < pbMemEnd) {
uint8_t v;
if (ProbeForRead<uint8_t>(pbMemBegin, &v)) {
_tprintf_s(TEXT(" %.2x"), v);
} else {
_tprintf_s(TEXT(" ??"));
}
++pbMemBegin;
}
}
void PrintBytes(const void* lpMem, size_t cbMem) noexcept {
PrintBytes(lpMem, reinterpret_cast<const char*>(lpMem) + cbMem);
}
[[nodiscard]]
bool IsValidDirectoryPath(PCTSTR lpszDirectoryPath) noexcept {
DWORD Attribute = GetFileAttributes(lpszDirectoryPath);
return Attribute != INVALID_FILE_ATTRIBUTES && (Attribute & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
[[nodiscard]]
bool IsValidFilePath(PCTSTR lpszFilePath) noexcept {
DWORD Attribute = GetFileAttributes(lpszFilePath);
return Attribute != INVALID_FILE_ATTRIBUTES && (Attribute & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
[[nodiscard]]
bool IsWineEnvironment() noexcept {
static bool Checked = false;
static bool IsWineEnv = false;
if (Checked == false) {
auto hNtdll = GetModuleHandle(TEXT("ntdll.dll"));
IsWineEnv = hNtdll && GetProcAddress(hNtdll, "wine_get_version") != nullptr;
Checked = true;
}
return IsWineEnv;
}
std::xstring GetCurrentWorkingDirectory() {
std::xstring CurrentDirectory;
auto s = ::GetCurrentDirectory(0, NULL);
if (s == 0) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("GetCurrentDirectory failed"));
}
CurrentDirectory.resize(static_cast<size_t>(s) - 1);
s = ::GetCurrentDirectory(s, CurrentDirectory.data());
if (s == 0) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("GetCurrentDirectory failed"));
}
return CurrentDirectory;
}
}
-74
View File
@@ -1,74 +0,0 @@
#pragma once
#include <stddef.h>
#include <tchar.h>
#include <windows.h>
#include <type_traits>
#include <xstring.hpp>
#define LOG_SUCCESS(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[+] " fmt "\n"), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[+] " fmt "\n"), __VA_ARGS__)
#define LOG_FAILURE(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[-] " fmt "\n"), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[-] " fmt "\n"), __VA_ARGS__)
#define LOG_HINT(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[*] " fmt "\n"), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[*] " fmt "\n"), __VA_ARGS__)
#define LOG_SELECT(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[?] " fmt " "), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[?] " fmt " "), __VA_ARGS__)
namespace nkg {
template<size_t __Len>
constexpr size_t literal_length(const char (&)[__Len]) noexcept {
return __Len - 1;
}
template<typename __PtrType1, typename __PtrType2>
constexpr auto address_delta(__PtrType1 p1, __PtrType2 p2) noexcept {
static_assert(std::is_pointer_v<__PtrType1>);
static_assert(std::is_pointer_v<__PtrType2>);
return reinterpret_cast<const volatile char*>(p1) - reinterpret_cast<const volatile char*>(p2);
}
template<typename __PtrType>
constexpr __PtrType address_offset(__PtrType p, decltype(static_cast<char*>(nullptr) - static_cast<char*>(nullptr)) offset) noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__PtrType>(
const_cast<char*>(reinterpret_cast<const volatile char*>(p)) + offset
);
}
template<typename __ReturnType, typename __PtrType>
constexpr __ReturnType address_offset_cast(__PtrType p, decltype(static_cast<char*>(nullptr) - static_cast<char*>(nullptr)) offset) noexcept {
static_assert(std::is_pointer_v<__ReturnType>);
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__ReturnType>(
const_cast<char*>(reinterpret_cast<const volatile char*>(p)) + offset
);
}
//
// Print memory data in [lpMemBegin, lpMemEnd)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMemBegin, const void* lpMemEnd, const void* lpBase) noexcept;
//
// Print memory data in [lpMem, lpMem + cbMem)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMem, size_t cbMem, const void* lpBase) noexcept;
void PrintBytes(const void* lpMemBegin, const void* lpMemEnd) noexcept;
void PrintBytes(const void* lpMem, size_t cbMem) noexcept;
[[nodiscard]]
bool IsValidDirectoryPath(PCTSTR lpszDirectoryPath) noexcept;
[[nodiscard]]
bool IsValidFilePath(PCTSTR lpszFilePath) noexcept;
[[nodiscard]]
bool IsWineEnvironment() noexcept;
std::xstring GetCurrentWorkingDirectory();
}
-217
View File
@@ -1,217 +0,0 @@
#pragma once
#include <openssl/crypto.h>
#include <openssl/blowfish.h>
#include <openssl/sha.h>
#include <string>
#include <stdexcept>
class Navicat11Crypto {
protected:
using BlockType = uint8_t[BF_BLOCK];
BF_KEY _BlowfishKey;
template<bool __UpperCase = true>
static void _BytesToHex(const void* src, size_t len, char* dst) noexcept {
auto pb_src = reinterpret_cast<const uint8_t*>(src);
for (size_t i = 0; i < len; ++i) {
char h = pb_src[i] >> 4;
char l = pb_src[i] & 0x0F;
if constexpr (__UpperCase) {
h += h >= 10 ? 'A' - 10 : '0';
l += l >= 10 ? 'A' - 10 : '0';
} else {
h += h >= 10 ? 'a' - 10 : '0';
l += l >= 10 ? 'a' - 10 : '0';
}
dst[2 * i] = h;
dst[2 * i + 1] = l;
}
}
static void _HexToBytes(const char* src, size_t len, void* dst) {
auto pb_dst = reinterpret_cast<uint8_t*>(dst);
for (size_t i = 0; i < len; i += 2) {
uint8_t h = src[i];
uint8_t l = src[i + 1];
if ('0' <= h && h <= '9') {
h -= '0';
} else if ('A' <= h && h <= 'F') {
h -= 'A';
} else if ('a' <= h && h <= 'f') {
h -= 'a';
} else {
throw std::invalid_argument("Non-hex character detected.");
}
if ('0' <= l && l <= '9') {
l -= '0';
} else if ('A' <= l && l <= 'F') {
l -= 'A';
} else if ('a' <= l && l <= 'f') {
l -= 'a';
} else {
throw std::invalid_argument("Non-hex character detected.");
}
pb_dst[i / 2] = (h << 4) ^ l;
}
}
static void _XorBlock(BlockType& a, const BlockType& b) noexcept {
reinterpret_cast<uint64_t&>(a) ^= reinterpret_cast<const uint64_t&>(b);
}
[[nodiscard]]
std::string _EncryptString(const void* lpPlaintext, size_t cbPlaintext) const {
std::string Ciphertext;
if (cbPlaintext) {
Ciphertext.resize(2 * cbPlaintext);
alignas(sizeof(BlockType)) BlockType CV = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
alignas(sizeof(BlockType)) BlockType Block;
auto lpPlaintextBlock = reinterpret_cast<const uint8_t*>(lpPlaintext);
auto lpCiphertextHexBlock = Ciphertext.data();
auto BlockCount = cbPlaintext / BF_BLOCK;
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < BlockCount; ++i, lpPlaintextBlock += sizeof(BlockType), lpCiphertextHexBlock += 2 * sizeof(BlockType)) {
memcpy(Block, lpPlaintextBlock, sizeof(BlockType));
_XorBlock(Block, CV);
BF_ecb_encrypt(Block, Block, &_BlowfishKey, BF_ENCRYPT);
_XorBlock(CV, Block);
_BytesToHex(Block, sizeof(Block), lpCiphertextHexBlock);
}
auto LeftByteCount = cbPlaintext % sizeof(BlockType);
if (LeftByteCount) {
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < LeftByteCount; ++i) {
CV[i] ^= lpPlaintextBlock[i];
}
_BytesToHex(CV, LeftByteCount, lpCiphertextHexBlock);
}
}
return Ciphertext;
}
[[nodiscard]]
std::string _DecryptString(const char* lpCiphertext, size_t cbCiphertext) const {
std::string Plaintext;
if (cbCiphertext) {
if (cbCiphertext % 2) {
throw std::invalid_argument("Ciphertext is not a hex string.");
}
Plaintext.resize(cbCiphertext / 2);
alignas(sizeof(BlockType)) BlockType CV = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
alignas(sizeof(BlockType)) BlockType Block;
auto lpPlaintextBlock = Plaintext.data();
auto lpCiphertextHexBlock = lpCiphertext;
auto BlockCount = cbCiphertext / (2 * sizeof(BlockType));
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < BlockCount; ++i, lpPlaintextBlock += sizeof(BlockType), lpCiphertextHexBlock += 2 * sizeof(BlockType)) {
alignas(sizeof(BlockType)) BlockType CiphertextBlock;
_HexToBytes(lpCiphertextHexBlock, 2 * sizeof(BlockType), CiphertextBlock);
memcpy(Block, CiphertextBlock, sizeof(BlockType));
BF_ecb_encrypt(Block, Block, &_BlowfishKey, BF_DECRYPT);
_XorBlock(Block, CV);
_XorBlock(CV, CiphertextBlock);
memcpy(lpPlaintextBlock, Block, sizeof(BlockType));
}
auto LeftHexCount = cbCiphertext % (2 * sizeof(BlockType));
if (LeftHexCount) {
_HexToBytes(lpCiphertextHexBlock, LeftHexCount, Block);
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < LeftHexCount / 2; ++i) {
lpPlaintextBlock[i] = Block[i] ^ CV[i];
}
}
}
return Plaintext;
}
public:
Navicat11Crypto() noexcept {
static const uint8_t PresetKey[SHA_DIGEST_LENGTH] = {
0x42, 0xCE, 0xB2, 0x71, 0xA5, 0xE4, 0x58, 0xB7,
0x4A, 0xEA, 0x93, 0x94, 0x79, 0x22, 0x35, 0x43,
0x91, 0x87, 0x33, 0x40
};
BF_set_key(&_BlowfishKey, sizeof(PresetKey), PresetKey);
}
Navicat11Crypto(const void* lpUserKey, size_t cbUserKey) noexcept {
SetKey(lpUserKey, cbUserKey);
}
Navicat11Crypto(const std::initializer_list<uint8_t>& UserKey) noexcept {
SetKey(UserKey);
}
void SetKey(const void* lpUserKey, size_t cbUserKey) noexcept {
uint8_t MessageDigest[SHA_DIGEST_LENGTH];
BF_set_key(
&_BlowfishKey,
sizeof(MessageDigest),
SHA1(reinterpret_cast<const uint8_t*>(lpUserKey), cbUserKey, MessageDigest)
);
OPENSSL_cleanse(MessageDigest, SHA_DIGEST_LENGTH);
}
void SetKey(const std::initializer_list<uint8_t>& UserKey) noexcept {
uint8_t MessageDigest[SHA_DIGEST_LENGTH];
BF_set_key(
&_BlowfishKey,
sizeof(MessageDigest),
SHA1(UserKey.begin(), UserKey.size(), MessageDigest)
);
OPENSSL_cleanse(MessageDigest, SHA_DIGEST_LENGTH);
}
[[nodiscard]]
std::string EncryptString(const std::string& Plaintext) const {
return _EncryptString(Plaintext.c_str(), Plaintext.length());
}
[[nodiscard]]
std::string DecryptString(const std::string& Ciphertext) const {
return _DecryptString(Ciphertext.c_str(), Ciphertext.length());
}
void Clear() noexcept {
OPENSSL_cleanse(&_BlowfishKey, sizeof(_BlowfishKey));
}
~Navicat11Crypto() noexcept {
Clear();
}
};
+70 -74
View File
@@ -1,82 +1,78 @@
#include "PatchSolutions.hpp"
#include <memory.h>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution0.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
const char PatchSolution0::Keyword[452] =
"-----BEGIN PUBLIC KEY-----\x00"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I\x00"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv\x00"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF\x00"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2\x00"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt\x00"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ\x00"
"awIDAQAB\x00"
"-----END PUBLIC KEY-----\x00";
namespace nkg {
PatchSolution0::PatchSolution0(const X64ImageInterpreter& Image) noexcept :
pvt_Image(Image),
pvt_PatchOffset(X64ImageInterpreter::InvalidOffset) {}
const char PatchSolution0::Keyword[461] =
"-----BEGIN PUBLIC KEY-----\r\n"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I\r\n"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv\r\n"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF\r\n"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2\r\n"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt\r\n"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ\r\n"
"awIDAQAB\r\n"
"-----END PUBLIC KEY-----\r\n";
bool PatchSolution0::FindPatchOffset() noexcept {
try {
pvt_PatchOffset = pvt_Image.SearchSectionOffset("__TEXT", "__cstring", [](const uint8_t* p) {
return memcmp(p, Keyword, sizeof(Keyword) - 1) == 0;
});
[[nodiscard]]
bool PatchSolution0::FindPatchOffset() noexcept {
try {
_PatchOffset = _Image.PointerToFileOffset(
_Image.SearchSection<uint8_t*>(".rsrc", [](const uint8_t* p) {
__try {
return memcmp(p, Keyword, literal_length(Keyword)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
})
);
LOG_SUCCESS(0, "PatchSolution0 ...... Ready to apply");
LOG_HINT(4, "Patch offset = +0x%.8zx", _PatchOffset);
return true;
} catch (nkg::Exception&) {
_PatchOffset = InvalidOffset;
LOG_FAILURE(0, "PatchSolution0 ...... Omitted");
return false;
}
}
[[nodiscard]]
bool PatchSolution0::CheckKey(const RSACipher& Cipher) const noexcept {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
return szPublicKey.length() == literal_length(Keyword);
}
void PatchSolution0::MakePatch(const RSACipher& Cipher) const {
if (_PatchOffset == InvalidOffset) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution0 has not been ready yet."));
}
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution0 *"));
_putts(TEXT("*******************************************************"));
LOG_HINT(0, "Previous:");
PrintMemory(_Image.ImageOffset(_PatchOffset), literal_length(Keyword), _Image.ImageBase());
memcpy(_Image.ImageOffset(_PatchOffset), szPublicKey.c_str(), literal_length(Keyword));
LOG_HINT(0, "After:");
PrintMemory(_Image.ImageOffset(_PatchOffset), literal_length(Keyword), _Image.ImageBase());
_putts(TEXT(""));
printf("[+] PatchSolution0 ...... Ready to apply.\n");
printf(" Keyword offset = +0x%.8x\n", pvt_PatchOffset);
return true;
} catch (...) {
printf("[-] PatchSolution0 ...... Omitted.\n");
return false;
}
}
bool PatchSolution0::CheckKey(const RSACipher& RsaCipher) const noexcept {
try {
if (RsaCipher.Bits() != 2048) {
return false;
}
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto& c : PublicKeyPEM) {
if (c == '\n') c = '\x00';
}
return PublicKeyPEM.length() == sizeof(Keyword) - 1;
} catch (...) {
return false;
}
}
void PatchSolution0::MakePatch(const RSACipher& RsaCipher) const {
if (pvt_PatchOffset == X64ImageInterpreter::InvalidOffset) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PatchSolution0 is not ready.");
}
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto& c : PublicKeyPEM) {
if (c == '\n') c = '\x00';
}
auto pbPatch = pvt_Image.ImageOffset<uint8_t*>(pvt_PatchOffset);
puts("**************************************************************");
puts("* PatchSolution0 *");
puts("**************************************************************");
printf("@+0x%.8x\n", pvt_PatchOffset);
puts("Previous:");
nkg::PrintMemory(pbPatch, pbPatch + sizeof(Keyword), pbPatch);
memcpy(pbPatch, PublicKeyPEM.data(), PublicKeyPEM.size());
puts("After:");
nkg::PrintMemory(pbPatch, pbPatch + sizeof(Keyword), pbPatch);
puts("");
}
+112 -293
View File
@@ -1,308 +1,127 @@
#include "PatchSolutions.hpp"
#include "NavicatCrypto.hpp"
#include <memory.h>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution1.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
const uint8_t PatchSolution1::Keyword[0x188] = {
0xfe, 0xfd, 0xfc, 0xf4, 0xfe, 0xd2, 0xf8, 0xf4, 0xf1, 0xd3, 0xde, 0xc7, 0xdf, 0xd3, 0xd0, 0xfd,
0x8a, 0xc3, 0x85, 0xf4, 0xf6, 0xe9, 0xfc, 0xfc, 0xf2, 0xf5, 0xfa, 0xf5, 0xf6, 0xe9, 0x81, 0xfb,
0xfe, 0xfd, 0xfc, 0xf4, 0xf4, 0xdf, 0xf2, 0xf9, 0xf2, 0xe5, 0xf0, 0xf7, 0xc0, 0x89, 0xdd, 0xcb,
0xf5, 0x87, 0xe6, 0xdd, 0xf4, 0xd9, 0xf8, 0xfb, 0xde, 0xf9, 0xcf, 0xc5, 0x8f, 0x80, 0x80, 0xf3,
0xc2, 0xd0, 0xe2, 0x8f, 0xfa, 0x8a, 0xdd, 0xf3, 0xd7, 0xdc, 0x86, 0xdc, 0xf0, 0x81, 0xc0, 0xea,
0xd0, 0xd9, 0xf9, 0xd8, 0xda, 0xf2, 0xd0, 0xfd, 0xc3, 0xf6, 0xf3, 0x82, 0xf2, 0x81, 0xef, 0xf2,
0xe0, 0xf9, 0xf2, 0xd3, 0x8f, 0xd7, 0xe9, 0xfb, 0xca, 0x86, 0xde, 0xfc, 0xf3, 0xd5, 0xdd, 0xf4,
0xc7, 0x80, 0xf7, 0xd5, 0xf2, 0xc1, 0xde, 0xcc, 0xc0, 0xc7, 0xf0, 0xd0, 0xd0, 0xd1, 0xd7, 0xcc,
0xd2, 0x81, 0xc1, 0x83, 0xdd, 0xd5, 0x8a, 0x8f, 0x81, 0xe1, 0xf4, 0xd9, 0xf3, 0xd7, 0xca, 0xef,
0xf9, 0xdf, 0xe1, 0xee, 0xf0, 0xe9, 0xd1, 0xca, 0xf2, 0xe3, 0xf8, 0xf0, 0x83, 0xde, 0xfb, 0xd7,
0xf1, 0xc4, 0xfa, 0x85, 0xf2, 0xdd, 0xdd, 0xfd, 0x85, 0x86, 0xc7, 0xf9, 0xc4, 0xc9, 0xf4, 0xf8,
0xd4, 0xd9, 0xe6, 0xd2, 0xf6, 0xc1, 0xc1, 0xf9, 0xe0, 0xe4, 0xf7, 0xe4, 0xfd, 0xf1, 0xf6, 0xfc,
0xe1, 0x84, 0xe4, 0xd1, 0xed, 0xfe, 0xdb, 0xe8, 0xdd, 0xe1, 0x85, 0xd0, 0xc5, 0xd2, 0x8a, 0x8e,
0xd5, 0xdd, 0xe3, 0xdb, 0xd0, 0xe1, 0xd0, 0xf6, 0xc6, 0xee, 0xe6, 0xf7, 0xda, 0xf1, 0xdb, 0xc9,
0x8b, 0xee, 0xcd, 0xdf, 0xff, 0xe8, 0xdd, 0xca, 0x82, 0xdb, 0xf1, 0x82, 0xc3, 0xed, 0xc9, 0xcc,
0xc0, 0xf2, 0xd6, 0xdf, 0x83, 0xe9, 0xf3, 0xce, 0xea, 0xfa, 0xdf, 0xf8, 0xd9, 0xff, 0xec, 0x88,
0xe4, 0xe4, 0xfd, 0x80, 0xc5, 0xce, 0xfa, 0xd2, 0xf4, 0xd8, 0x84, 0xff, 0xe5, 0xf3, 0xcb, 0xc2,
0xfe, 0xc0, 0xc4, 0xfa, 0xde, 0xdd, 0xd5, 0xc9, 0xc5, 0xd5, 0xdf, 0xe3, 0xdd, 0xc1, 0xcb, 0xdd,
0xfc, 0xf7, 0x83, 0xf8, 0xda, 0xc1, 0xd4, 0xe3, 0xfe, 0xc2, 0xef, 0xf8, 0xf2, 0xea, 0x8a, 0xd2,
0xc7, 0xf2, 0xf0, 0xc2, 0xfb, 0x89, 0xdc, 0xeb, 0xd1, 0xf7, 0xcc, 0xe2, 0xd1, 0xfc, 0xd4, 0xce,
0xea, 0xcd, 0xe4, 0x87, 0xe0, 0xcc, 0x8d, 0xf5, 0xc7, 0x85, 0x87, 0xda, 0xcf, 0xde, 0x89, 0xcd,
0xe5, 0xfd, 0xe7, 0x83, 0xda, 0xdb, 0xfe, 0xf4, 0x84, 0xec, 0xf6, 0xee, 0xfd, 0xea, 0xf1, 0xf5,
0xf5, 0xfc, 0xe6, 0xd0, 0x86, 0xdf, 0xc3, 0xe2, 0xe4, 0xd5, 0xd7, 0xe4, 0xe4, 0xce, 0xd4, 0xce,
0x82, 0xda, 0xc7, 0xda, 0x80, 0xcb, 0xee, 0x8c, 0xd0, 0xde, 0xcd, 0xda, 0xdd, 0xcd, 0xcc, 0xeb,
0xd2, 0xc3, 0xfc, 0xf2, 0xf6, 0xe9, 0xf8, 0xf8
};
namespace nkg {
PatchSolution1::PatchSolution1(const X64ImageInterpreter& Image) noexcept :
pvt_Image(Image),
pvt_PatchOffset(X64ImageInterpreter::InvalidOffset) {}
static Navicat11Crypto g_NavicatCipher = Navicat11Crypto("23970790", 8);
bool PatchSolution1::FindPatchOffset() noexcept {
uint8_t* pbPatch = nullptr;
const char PatchSolution1::Keyword0[160 + 1] =
"D75125B70767B94145B47C1CB3C0755E"
"7CCB8825C5DCE0C58ACF944E08280140"
"9A02472FAFFD1CD77864BB821AE36766"
"FEEDE6A24F12662954168BFA314BD950"
"32B9D82445355ED7BC0B880887D650F5";
for (size_t i = 0; i < pvt_Image.NumberOfSections(); ++i) {
auto pbSectionView = pvt_Image.SectionView<uint8_t*>(i);
auto cbSectiveView = pvt_Image.ImageSection(i)->size;
const char PatchSolution1::Keyword1[4 + 1] =
"\xfe\xea\xbc\x01";
if (cbSectiveView < sizeof(Keyword)) {
continue;
}
const char PatchSolution1::Keyword2[742 + 1] =
"E1CED09B9C2186BF71A70C0FE2F1E0AE"
"F3BD6B75277AAB20DFAF3D110F75912B"
"FB63AC50EC4C48689D1502715243A79F"
"39FF2DE2BF15CE438FF885745ED54573"
"850E8A9F40EE2FF505EB7476F95ADB78"
"3B28CA374FAC4632892AB82FB3BF4715"
"FCFE6E82D03731FC3762B6AAC3DF1C3B"
"C646FE9CD3C62663A97EE72DB932A301"
"312B4A7633100C8CC357262C39A2B3A6"
"4B224F5276D5EDBDF0804DC3AC4B8351"
"62BB1969EAEBADC43D2511D6E0239287"
"81B167A48273B953378D3D2080CC0677"
"7E8A2364F0234B81064C5C739A8DA28D"
"C5889072BF37685CBC94C2D31D0179AD"
"86D8E3AA8090D4F0B281BE37E0143746"
"E6049CCC06899401264FA471C016A96C"
"79815B55BBC26B43052609D9D175FBCD"
"E455392F10E51EC162F51CF732E6BB39"
"1F56BBFD8D957DF3D4C55B71CEFD54B1"
"9C16D458757373E698D7E693A8FC3981"
"5A8BF03BA05EA8C8778D38F9873D62B4"
"460F41ACF997C30E7C3AF025FA171B5F"
"5AD4D6B15E95C27F6B35AD61875E5505"
"449B4E";
const char PatchSolution1::Keyword3[4 + 1] =
"\x59\x08\x01\x00";
const char PatchSolution1::Keyword4[5 + 1] =
"92933";
[[nodiscard]]
bool PatchSolution1::FindPatchOffset() noexcept {
try {
PIMAGE_SECTION_HEADER SectionHeader_text = _Image.ImageSectionHeaderByName(".text");
PIMAGE_SECTION_HEADER SectionHeader_rdata = _Image.ImageSectionHeaderByName(".rdata");
const uint8_t* pbPatch[_countof(_PatchOffset)] = {};
pbPatch[0] = _Image.SearchSection<const uint8_t*>(SectionHeader_rdata, [](const uint8_t* p) {
__try {
return memcmp(p, Keyword0, sizeof(Keyword0)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
pbPatch[2] = _Image.SearchSection<const uint8_t*>(SectionHeader_rdata, [](const uint8_t* p) {
__try {
return memcmp(p, Keyword2, sizeof(Keyword2)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
pbPatch[4] = _Image.SearchSection<const uint8_t*>(SectionHeader_rdata, [](const uint8_t* p) {
__try {
return memcmp(p, Keyword4, sizeof(Keyword4)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
pbPatch[1] = _Image.SearchSection<const uint8_t*>(SectionHeader_text, [&pbPatch](const uint8_t* p) {
__try {
if (memcmp(p, Keyword1, literal_length(Keyword1)) == 0) {
// Keyword3 must be close to Keyword1
for (auto j = p - 64; j < p + 64; ++j) {
if (memcmp(j, Keyword3, literal_length(Keyword3)) == 0) {
pbPatch[3] = j;
return true;
}
}
}
return false;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = _Image.PointerToFileOffset(pbPatch[i]);
for (size_t j = 0; j < cbSectiveView - sizeof(Keyword); ++j) {
if (memcmp(pbSectionView + j, Keyword, sizeof(Keyword)) == 0) {
pbPatch = pbSectionView + j;
i = pvt_Image.NumberOfSections();
break;
}
_PatchSize[0] = literal_length(Keyword0);
while (pbPatch[0][_PatchSize[0] + 1] == 0 && _PatchSize[0] < literal_length(Keyword0) + literal_length("29158142") - 1) {
++_PatchSize[0];
}
_PatchSize[1] = sizeof(uint32_t);
_PatchSize[2] = literal_length(Keyword2);
while (pbPatch[2][_PatchSize[2] + 1] == 0 && _PatchSize[2] < literal_length(Keyword2) + literal_length("67673") - 1) {
++_PatchSize[2];
}
_PatchSize[3] = sizeof(uint32_t);
_PatchSize[4] = literal_length(Keyword4);
LOG_SUCCESS(0, "PatchSolution1 ...... Ready to apply");
LOG_HINT(4, "[0] Patch offset = +0x%.8zx", _PatchOffset[0]);
LOG_HINT(4, "[1] Patch offset = +0x%.8zx", _PatchOffset[1]);
LOG_HINT(4, "[2] Patch offset = +0x%.8zx", _PatchOffset[2]);
LOG_HINT(4, "[3] Patch offset = +0x%.8zx", _PatchOffset[3]);
LOG_HINT(4, "[4] Patch offset = +0x%.8zx", _PatchOffset[4]);
return true;
} catch (nkg::Exception&) {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
_PatchSize[i] = 0;
}
LOG_FAILURE(0, "PatchSolution1 ...... Omitted");
return false;
}
}
[[nodiscard]]
bool PatchSolution1::CheckKey(const RSACipher& Cipher) const noexcept {
if (_PatchSize[0] && _PatchSize[1] && _PatchSize[2] && _PatchSize[3] && _PatchSize[4]) {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
if (pbPatch == nullptr) {
printf("[-] PatchSolution1 ...... Omitted.\n");
return false;
} else {
pvt_PatchOffset = pbPatch - pvt_Image.ImageBase<uint8_t*>();
auto szPublicKeyEncrypted = g_NavicatCipher.EncryptString(szPublicKey);
if (szPublicKeyEncrypted.length() != 920) {
return false;
}
// we require the chars in [p1, p2) of szPublicKeyEncrypted must be number chars
size_t p1, p2;
p1 = _PatchSize[0];
p2 = literal_length(Keyword0) + literal_length("29158142");
if (('1' <= szPublicKeyEncrypted[p1] && szPublicKeyEncrypted[p1] <= '9') == false) {
return false;
}
for (size_t i = p1 + 1; i < p2; ++i) {
if (('0' <= szPublicKeyEncrypted[i] && szPublicKeyEncrypted[i] <= '9') == false) {
return false;
}
}
// we require the chars in [p1, p2) of szPublicKeyEncrypted must be number chars
p1 = literal_length(Keyword0) + literal_length("29158142") + _PatchSize[2];
p2 = literal_length(Keyword0) + literal_length("29158142") + literal_length(Keyword2) + literal_length("67673");
if (('1' <= szPublicKeyEncrypted[p1] && szPublicKeyEncrypted[p1] <= '9') == false) {
return false;
}
for (size_t i = p1 + 1; i < p2; ++i) {
if (('0' <= szPublicKeyEncrypted[i] && szPublicKeyEncrypted[i] <= '9') == false) {
return false;
}
}
return true;
} else {
return false;
}
}
void PatchSolution1::MakePatch(const RSACipher& Cipher) const {
if (_PatchSize[0] && _PatchSize[1] && _PatchSize[2] && _PatchSize[3] && _PatchSize[4]) {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
auto szPublicKeyEncrypted = g_NavicatCipher.EncryptString(szPublicKey);
//
// p0 p1 p2 p3 p4 p5
// Original encrypted public key layout: |160 chars|8 chars|742 chars|5 chars|5 chars|
// | |
// V V
// ImmValue1 ImmValue3
size_t p0, p1, p2, p3, p4, p5;
p0 = 0;
p1 = _PatchSize[0];
p2 = literal_length(Keyword0) + literal_length("29158142");
p3 = literal_length(Keyword0) + literal_length("29158142") + _PatchSize[2];
p4 = literal_length(Keyword0) + literal_length("29158142") + literal_length(Keyword2) + literal_length("67673");
p5 = literal_length(Keyword0) + literal_length("29158142") + literal_length(Keyword2) + literal_length("67673") + literal_length(Keyword4);
if (szPublicKeyEncrypted.length() != 920) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("szPublicKeyEncrypted.length() != 920"));
}
std::string EncryptedPEM0(szPublicKeyEncrypted.begin() + p0, szPublicKeyEncrypted.begin() + p1);
std::string EncryptedPEM1(szPublicKeyEncrypted.begin() + p1, szPublicKeyEncrypted.begin() + p2);
std::string EncryptedPEM2(szPublicKeyEncrypted.begin() + p2, szPublicKeyEncrypted.begin() + p3);
std::string EncryptedPEM3(szPublicKeyEncrypted.begin() + p3, szPublicKeyEncrypted.begin() + p4);
std::string EncryptedPEM4(szPublicKeyEncrypted.begin() + p4, szPublicKeyEncrypted.begin() + p5);
uint32_t ImmValue1 = std::stoul(EncryptedPEM1.c_str());
uint32_t ImmValue3 = std::stoul(EncryptedPEM3.c_str());
uint8_t* pbPatch[_countof(_PatchOffset)] = {};
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
pbPatch[i] = _Image.FileOffsetToPointer<uint8_t*>(_PatchOffset[i]);
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution1 *"));
_putts(TEXT("*******************************************************"));
// ----------------------------------
// process PatchOffsets[0]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[0], _PatchSize[0], _Image.ImageBase());
memcpy(pbPatch[0], EncryptedPEM0.data(), _PatchSize[0]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[0], _PatchSize[0], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[1]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[1], _PatchSize[1], _Image.ImageBase());
memcpy(pbPatch[1], &ImmValue1, _PatchSize[1]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[1], _PatchSize[1], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[2]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[2], _PatchSize[2], _Image.ImageBase());
memcpy(pbPatch[2], EncryptedPEM2.data(), _PatchSize[2]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[2], _PatchSize[2], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[3]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[3], _PatchSize[3], _Image.ImageBase());
memcpy(pbPatch[3], &ImmValue3, _PatchSize[3]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[3], _PatchSize[3], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[4]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[4], _PatchSize[4], _Image.ImageBase());
memcpy(pbPatch[4], EncryptedPEM4.data(), _PatchSize[4]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[4], _PatchSize[4], _Image.ImageBase());
_putts(TEXT(""));
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution1 has not been ready yet."));
}
printf("[+] PatchSolution1 ...... Ready to apply.\n");
printf(" Keyword offset = +0x%.8x\n", pvt_PatchOffset);
return true;
}
}
bool PatchSolution1::CheckKey(const RSACipher& RsaCipher) const noexcept {
try {
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
PublicKeyPEM.erase(PublicKeyPEM.find("-----BEGIN PUBLIC KEY-----"), 26);
PublicKeyPEM.erase(PublicKeyPEM.find("-----END PUBLIC KEY-----"), 24);
{
std::string::size_type pos = 0;
while ((pos = PublicKeyPEM.find('\n', pos)) != std::string::npos) {
PublicKeyPEM.erase(pos, 1);
}
}
return PublicKeyPEM.length() == sizeof(Keyword);
} catch (...) {
return false;
}
}
void PatchSolution1::MakePatch(const RSACipher& RsaCipher) const {
if (pvt_PatchOffset == X64ImageInterpreter::InvalidOffset) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PatchSolution1 is not ready.");
}
auto pbPatch = pvt_Image.ImageOffset<uint8_t*>(pvt_PatchOffset);
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
PublicKeyPEM.erase(PublicKeyPEM.find("-----BEGIN PUBLIC KEY-----"), 26);
PublicKeyPEM.erase(PublicKeyPEM.find("-----END PUBLIC KEY-----"), 24);
{
std::string::size_type pos = 0;
while ((pos = PublicKeyPEM.find('\n', pos)) != std::string::npos) {
PublicKeyPEM.erase(pos, 1);
}
}
uint8_t key = 8;
for (auto& c : PublicKeyPEM) {
if (key == 0) key = 8;
reinterpret_cast<uint8_t&>(c) ^= 0xbbu - key;
--key;
}
puts("**************************************************************");
puts("* PatchSolution1 *");
puts("**************************************************************");
printf("@+0x%.8x\n", pvt_PatchOffset);
puts("Previous:");
nkg::PrintMemory(pbPatch, pbPatch + sizeof(Keyword), pbPatch);
memcpy(pbPatch, PublicKeyPEM.data(), PublicKeyPEM.length());
puts("After:");
nkg::PrintMemory(pbPatch, pbPatch + sizeof(Keyword), pbPatch);
puts("");
}
-511
View File
@@ -1,511 +0,0 @@
#include "PatchSolutions.hpp"
#include <vector>
#include <algorithm>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution2-amd64.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
/*
Keyword[0x188][5] is generated by the following python script:
-----Begin Python3 Script-----
meta = \
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I" \
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv" \
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF" \
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2" \
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt" \
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ" \
"awIDAQAB"
print('const uint8_t PatchSolution2::Keyword[0x188][5] = {')
for i in range(0, len(meta)):
i1 = '0x83, 0xf0, 0x%.2x' % ord(meta[i]) # asm('xor eax, meta[i]')
i2 = '0x88, 0x05' # asm_prefix('mov byte ptr ds:xxxxxxxxxxxxxxxx, al')
print(' { %s, %s }' % (i1, i2), end = ',\n' if i != len(meta) - 1 else '\n')
print('};')
-----End Python3 Script-----
*/
const uint8_t PatchSolution2::Keyword[0x188][5] = {
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x7a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x56, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x54, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x56, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x75, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x54, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x56, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x37, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x7a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x37, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x75, 0x88, 0x05 },
{ 0x83, 0xf0, 0x75, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 }
};
[[nodiscard]]
bool PatchSolution2::FindPatchOffset() noexcept {
try {
auto SectionHeader_text = _Image.ImageSectionHeaderByName(".text");
auto SectionView_text = _Image.ImageSectionView<const uint8_t*>(SectionHeader_text);
const uint8_t* lpPatch[_countof(_PatchOffset)] = {};
std::vector<size_t> Hints;
DWORD PossibleRangeStart = 0xffffffff;
DWORD PossibleRangeEnd;
for (DWORD i = 0; i < SectionHeader_text->SizeOfRawData; ++i) {
if (memcmp(SectionView_text + i, Keyword[0], sizeof(Keyword[0])) == 0) {
size_t RRip = i + sizeof(Keyword[0]) + sizeof(uint32_t);
size_t RRipOffset = *reinterpret_cast<const uint32_t*>(SectionView_text + i + sizeof(Keyword[0]));
Hints.emplace_back(RRip + RRipOffset);
if (i < PossibleRangeStart) {
PossibleRangeStart = i;
}
}
}
PossibleRangeStart -= 0x1000;
PossibleRangeEnd = PossibleRangeStart + 0x100000;
// Keywords[0] should occur 9 times.
// Because there's only 9 'M' chars in `KeywordMeta`.
if (Hints.size() != 9) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.size() != 9"));
}
std::sort(Hints.begin(), Hints.end());
// assert
// if not satisfied, refuse to patch
if (Hints.back() - Hints.front() != 0x18360F8F8 - 0x18360F7D0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.back() - Hints.front() != 0x18360F8F8 - 0x18360F7D0"));
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
for (DWORD j = PossibleRangeStart; j < PossibleRangeEnd; ++j) {
if (memcmp(SectionView_text + j, Keyword[i], sizeof(Keyword[i])) == 0) {
size_t RRip = j + sizeof(Keyword[i]) + sizeof(uint32_t);
size_t RRipOffset = *reinterpret_cast<const uint32_t*>(SectionView_text + j + sizeof(Keyword[i]));
size_t Index = RRip + RRipOffset - Hints.front();
if (Index == i) {
lpPatch[i] = SectionView_text + j;
}
}
}
// if not found, refuse to patch
if (lpPatch[i] == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("A patch point is missing."));
}
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = _Image.PointerToFileOffset(lpPatch[i]);
}
LOG_SUCCESS(0, "PatchSolution2 ...... Ready to apply");
for (size_t i = 0; i < _countof(_PatchOffset); i += 4) {
static_assert(sizeof(_countof(_PatchOffset)) % 4 == 0);
LOG_HINT(4, "Patch offset[%zu ... %zu] = 0x%.8zx, 0x%.8zx, 0x%.8zx, 0x%.8zx", i, i + 3, _PatchOffset[i], _PatchOffset[i + 1], _PatchOffset[i + 2], _PatchOffset[i + 3]);
}
return true;
} catch (nkg::Exception&) {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
LOG_FAILURE(0, "PatchSolution2 ...... Omitted");
return false;
}
}
}
@@ -1,92 +0,0 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution2-generic.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
const char PatchSolution2::KeywordMeta[0x188 + 1] =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ"
"awIDAQAB";
[[nodiscard]]
bool PatchSolution2::CheckKey(const RSACipher& Cipher) const noexcept {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
return szPublicKey.length() == literal_length(KeywordMeta);
}
void PatchSolution2::MakePatch(const RSACipher& Cipher) const {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
if (_PatchOffset[i] == InvalidOffset) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution2 has not been ready yet."));
}
}
auto pbImage = _Image.ImageBase<uint8_t*>();
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
if (szPublicKey.length() != literal_length(KeywordMeta)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("szPublicKey.length() != literal_length(KeywordMeta)"));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution2 *"));
_putts(TEXT("*******************************************************"));
for (size_t i = 0; i < _countof(_PatchOffset); i += 2) {
static_assert(_countof(_PatchOffset) % 2 == 0);
LOG_HINT(0, "+0x%.8zx: %.2x %.2x %.2x -> %.2x %.2x %.2x | +0x%.8zx: %.2x %.2x %.2x -> %.2x %.2x %.2x",
_PatchOffset[i],
pbImage[_PatchOffset[i]],
pbImage[_PatchOffset[i] + 1],
pbImage[_PatchOffset[i] + 2],
pbImage[_PatchOffset[i]],
pbImage[_PatchOffset[i] + 1],
szPublicKey[i],
_PatchOffset[i + 1],
pbImage[_PatchOffset[i + 1]],
pbImage[_PatchOffset[i + 1] + 1],
pbImage[_PatchOffset[i + 1] + 2],
pbImage[_PatchOffset[i + 1]],
pbImage[_PatchOffset[i + 1] + 1],
szPublicKey[i + 1]
);
pbImage[_PatchOffset[i] + 2] = szPublicKey[i];
pbImage[_PatchOffset[i + 1] + 2] = szPublicKey[i + 1];
}
}
}
-517
View File
@@ -1,517 +0,0 @@
#include "PatchSolutions.hpp"
#include <vector>
#include <algorithm>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution2-i386.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
/*
Keyword[0x188][5] is generated by the following python script:
-----Begin Python3 Script-----
meta = \
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I" \
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv" \
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF" \
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2" \
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt" \
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ" \
"awIDAQAB"
print('const uint8_t PatchSolution2::Keywords[0x188][5] = {')
for i in range(0, len(meta)):
if i % 3 == 0:
i1 = '0x83, 0xf2, 0x%.2x' % ord(meta[i]) # asm('xor edx, meta[i]')
i2 = '0x88, 0x15' # asm_prefix('mov byte ptr ds:xxxxxxxx, dl')
elif i % 3 == 1:
i1 = '0x83, 0xf0, 0x%.2x' % ord(meta[i]) # asm('xor eax, meta[i]')
i2 = '0xa2' # asm_prefix('mov byte ptr ds:xxxxxxxx, al')
else:
i1 = '0x83, 0xf1, 0x%.2x' % ord(meta[i]) # asm('xor ecx, meta[i]')
i2 = '0x88, 0x0d' # asm_prefix('mov byte ptr ds:xxxxxxxx, cl')
print(' { %s, %s }' % (i1, i2), end=',\n' if i != len(meta) - 1 else '\n')
print('};')
-----End Python3 Script-----
*/
const uint8_t PatchSolution2::Keyword[0x188][5] = {
{ 0x83, 0xf2, 0x4d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x42, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4e, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x67, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x71, 0x88, 0x0d },
{ 0x83, 0xf2, 0x68, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x39, 0xa2 },
{ 0x83, 0xf1, 0x77, 0x88, 0x0d },
{ 0x83, 0xf2, 0x30, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 },
{ 0x83, 0xf1, 0x41, 0x88, 0x0d },
{ 0x83, 0xf2, 0x51, 0x88, 0x15 },
{ 0x83, 0xf0, 0x45, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x4f, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x38, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x67, 0xa2 },
{ 0x83, 0xf1, 0x4b, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x45, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x77, 0x88, 0x0d },
{ 0x83, 0xf2, 0x31, 0x88, 0x15 },
{ 0x83, 0xf0, 0x64, 0xa2 },
{ 0x83, 0xf1, 0x71, 0x88, 0x0d },
{ 0x83, 0xf2, 0x46, 0x88, 0x15 },
{ 0x83, 0xf0, 0x33, 0xa2 },
{ 0x83, 0xf1, 0x53, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6b, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x61, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x6d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x7a, 0xa2 },
{ 0x83, 0xf1, 0x73, 0x88, 0x0d },
{ 0x83, 0xf2, 0x38, 0x88, 0x15 },
{ 0x83, 0xf0, 0x38, 0xa2 },
{ 0x83, 0xf1, 0x39, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x71, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x39, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x64, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x64, 0x88, 0x15 },
{ 0x83, 0xf0, 0x68, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x47, 0xa2 },
{ 0x83, 0xf1, 0x39, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x50, 0xa2 },
{ 0x83, 0xf1, 0x63, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4c, 0xa2 },
{ 0x83, 0xf1, 0x6e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4a, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x70, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x46, 0x88, 0x15 },
{ 0x83, 0xf0, 0x34, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x39, 0x88, 0x15 },
{ 0x83, 0xf0, 0x56, 0xa2 },
{ 0x83, 0xf1, 0x48, 0x88, 0x0d },
{ 0x83, 0xf2, 0x53, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4d, 0xa2 },
{ 0x83, 0xf1, 0x47, 0x88, 0x0d },
{ 0x83, 0xf2, 0x65, 0x88, 0x15 },
{ 0x83, 0xf0, 0x38, 0xa2 },
{ 0x83, 0xf1, 0x6f, 0x88, 0x0d },
{ 0x83, 0xf2, 0x50, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x79, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x4a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x44, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x34, 0x88, 0x0d },
{ 0x83, 0xf2, 0x42, 0x88, 0x15 },
{ 0x83, 0xf0, 0x63, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x67, 0xa2 },
{ 0x83, 0xf1, 0x76, 0x88, 0x0d },
{ 0x83, 0xf2, 0x73, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x66, 0x88, 0x15 },
{ 0x83, 0xf0, 0x67, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x76, 0xa2 },
{ 0x83, 0xf1, 0x61, 0x88, 0x0d },
{ 0x83, 0xf2, 0x35, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x35, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x35, 0x88, 0x15 },
{ 0x83, 0xf0, 0x32, 0xa2 },
{ 0x83, 0xf1, 0x55, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6f, 0xa2 },
{ 0x83, 0xf1, 0x44, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x55, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x54, 0x88, 0x0d },
{ 0x83, 0xf2, 0x58, 0x88, 0x15 },
{ 0x83, 0xf0, 0x47, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x68, 0x88, 0x15 },
{ 0x83, 0xf0, 0x70, 0xa2 },
{ 0x83, 0xf1, 0x41, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4d, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x34, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 },
{ 0x83, 0xf1, 0x70, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x33, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x65, 0x88, 0x15 },
{ 0x83, 0xf0, 0x64, 0xa2 },
{ 0x83, 0xf1, 0x47, 0x88, 0x0d },
{ 0x83, 0xf2, 0x36, 0x88, 0x15 },
{ 0x83, 0xf0, 0x32, 0xa2 },
{ 0x83, 0xf1, 0x72, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x71, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 },
{ 0x83, 0xf1, 0x67, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x53, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x79, 0xa2 },
{ 0x83, 0xf1, 0x78, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x53, 0xa2 },
{ 0x83, 0xf1, 0x50, 0x88, 0x0d },
{ 0x83, 0xf2, 0x42, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x4a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4f, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x52, 0x88, 0x15 },
{ 0x83, 0xf0, 0x30, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x67, 0x88, 0x15 },
{ 0x83, 0xf0, 0x5a, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x62, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x6e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x55, 0x88, 0x15 },
{ 0x83, 0xf0, 0x30, 0xa2 },
{ 0x83, 0xf1, 0x66, 0x88, 0x0d },
{ 0x83, 0xf2, 0x72, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6a, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x34, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x56, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x67, 0x88, 0x0d },
{ 0x83, 0xf2, 0x59, 0x88, 0x15 },
{ 0x83, 0xf0, 0x69, 0xa2 },
{ 0x83, 0xf1, 0x4c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x75, 0x88, 0x15 },
{ 0x83, 0xf0, 0x5a, 0xa2 },
{ 0x83, 0xf1, 0x53, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x62, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x38, 0x88, 0x0d },
{ 0x83, 0xf2, 0x5a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x78, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x48, 0x88, 0x15 },
{ 0x83, 0xf0, 0x50, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x70, 0x88, 0x15 },
{ 0x83, 0xf0, 0x31, 0xa2 },
{ 0x83, 0xf1, 0x6f, 0x88, 0x0d },
{ 0x83, 0xf2, 0x44, 0x88, 0x15 },
{ 0x83, 0xf0, 0x34, 0xa2 },
{ 0x83, 0xf1, 0x74, 0x88, 0x0d },
{ 0x83, 0xf2, 0x55, 0x88, 0x15 },
{ 0x83, 0xf0, 0x70, 0xa2 },
{ 0x83, 0xf1, 0x76, 0x88, 0x0d },
{ 0x83, 0xf2, 0x73, 0x88, 0x15 },
{ 0x83, 0xf0, 0x46, 0xa2 },
{ 0x83, 0xf1, 0x63, 0x88, 0x0d },
{ 0x83, 0xf2, 0x69, 0x88, 0x15 },
{ 0x83, 0xf0, 0x34, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x59, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6a, 0xa2 },
{ 0x83, 0xf1, 0x4e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x47, 0xa2 },
{ 0x83, 0xf1, 0x55, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x57, 0xa2 },
{ 0x83, 0xf1, 0x50, 0x88, 0x0d },
{ 0x83, 0xf2, 0x48, 0x88, 0x15 },
{ 0x83, 0xf0, 0x36, 0xa2 },
{ 0x83, 0xf1, 0x72, 0x88, 0x0d },
{ 0x83, 0xf2, 0x76, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x68, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6c, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x4b, 0x88, 0x0d },
{ 0x83, 0xf2, 0x72, 0x88, 0x15 },
{ 0x83, 0xf0, 0x78, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x74, 0x88, 0x15 },
{ 0x83, 0xf0, 0x71, 0xa2 },
{ 0x83, 0xf1, 0x4c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x69, 0x88, 0x15 },
{ 0x83, 0xf0, 0x65, 0xa2 },
{ 0x83, 0xf1, 0x6c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x73, 0x88, 0x15 },
{ 0x83, 0xf0, 0x76, 0xa2 },
{ 0x83, 0xf1, 0x61, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x55, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x72, 0xa2 },
{ 0x83, 0xf1, 0x67, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x36, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x79, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x59, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x76, 0x88, 0x15 },
{ 0x83, 0xf0, 0x5a, 0xa2 },
{ 0x83, 0xf1, 0x4e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x45, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x68, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x45, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x4c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x31, 0x88, 0x15 },
{ 0x83, 0xf0, 0x65, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x62, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x79, 0x88, 0x0d },
{ 0x83, 0xf2, 0x54, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x44, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x59, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x51, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x34, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6c, 0xa2 },
{ 0x83, 0xf1, 0x78, 0x88, 0x0d },
{ 0x83, 0xf2, 0x66, 0x88, 0x15 },
{ 0x83, 0xf0, 0x30, 0xa2 },
{ 0x83, 0xf1, 0x77, 0x88, 0x0d },
{ 0x83, 0xf2, 0x56, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x52, 0x88, 0x0d },
{ 0x83, 0xf2, 0x35, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x63, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4e, 0xa2 },
{ 0x83, 0xf1, 0x37, 0x88, 0x0d },
{ 0x83, 0xf2, 0x58, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x58, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x48, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x46, 0xa2 },
{ 0x83, 0xf1, 0x48, 0x88, 0x0d },
{ 0x83, 0xf2, 0x53, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x67, 0x88, 0x15 },
{ 0x83, 0xf0, 0x7a, 0xa2 },
{ 0x83, 0xf1, 0x58, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x61, 0xa2 },
{ 0x83, 0xf1, 0x62, 0x88, 0x0d },
{ 0x83, 0xf2, 0x52, 0x88, 0x15 },
{ 0x83, 0xf0, 0x53, 0xa2 },
{ 0x83, 0xf1, 0x76, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x72, 0xa2 },
{ 0x83, 0xf1, 0x6c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x37, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x57, 0x88, 0x0d },
{ 0x83, 0xf2, 0x36, 0x88, 0x15 },
{ 0x83, 0xf0, 0x63, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x78, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6c, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x75, 0x88, 0x15 },
{ 0x83, 0xf0, 0x75, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x61, 0x88, 0x15 },
{ 0x83, 0xf0, 0x77, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x44, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 }
};
[[nodiscard]]
bool PatchSolution2::FindPatchOffset() noexcept {
try {
auto SectionHeader_text = _Image.ImageSectionHeaderByName(".text");
auto SectionView_text = _Image.ImageSectionView<const uint8_t*>(SectionHeader_text);
const uint8_t* lpPatch[_countof(_PatchOffset)] = {};
std::vector<size_t> Hints;
DWORD PossibleRangeStart = 0xffffffff;
DWORD PossibleRangeEnd;
for (DWORD i = 0; i < SectionHeader_text->SizeOfRawData; ++i) {
if (memcmp(SectionView_text + i, Keyword[0], sizeof(Keyword[0])) == 0) {
Hints.emplace_back(
*reinterpret_cast<const uint32_t*>(SectionView_text + i + sizeof(Keyword[0]))
);
if (i < PossibleRangeStart) {
PossibleRangeStart = i;
}
}
}
PossibleRangeStart -= 0x1000;
PossibleRangeEnd = PossibleRangeStart + 0x100000;
// Keywords[0] should occur 3 times.
if (Hints.size() != 3) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.size() != 3"));
}
std::sort(Hints.begin(), Hints.end());
if (Hints.back() - Hints.front() != 0x127382BE - 0x12738210) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.back() - Hints.front() != 0x127382BE - 0x12738210"));
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
uint8_t CurrentKeyword[9];
size_t CurrentKeywordSize = i % 3 == 1 ? 4 : 5;
memcpy(CurrentKeyword, Keyword[i], CurrentKeywordSize);
*reinterpret_cast<uint32_t*>(CurrentKeyword + CurrentKeywordSize) = Hints[0] + i;
CurrentKeywordSize += sizeof(uint32_t);
for (DWORD j = PossibleRangeStart; j < PossibleRangeEnd; ++j) {
if (memcmp(SectionView_text + j, CurrentKeyword, CurrentKeywordSize) == 0) {
lpPatch[i] = SectionView_text + j;
break;
}
}
// if not found, refuse to patch
if (lpPatch[i] == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("A patch point is missing."));
}
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = _Image.PointerToFileOffset(lpPatch[i]);
}
LOG_SUCCESS(0, "PatchSolution2 ...... Ready to apply");
for (size_t i = 0; i < _countof(_PatchOffset); i += 4) {
static_assert(sizeof(_countof(_PatchOffset)) % 4 == 0);
LOG_HINT(4, "Patch offset[%zu ... %zu] = 0x%.8zx, 0x%.8zx, 0x%.8zx, 0x%.8zx", i, i + 3, _PatchOffset[i], _PatchOffset[i + 1], _PatchOffset[i + 2], _PatchOffset[i + 3]);
}
return true;
} catch (nkg::Exception&) {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
LOG_FAILURE(0, "PatchSolution2 ...... Omitted");
return false;
}
}
}
+254
View File
@@ -0,0 +1,254 @@
#include "PatchSolutions.hpp"
#include <memory.h>
const char PatchSolution2::Keyword[1114] =
"BIjWyoeRR0NBgkqnDZWxCgKCEAw1dqF3DTvOB91ZHwecJYFrdM1KEh"
"1yVeRoGqSdLLGZGUlngig3OD5mMzs889IqWqqfHSeHMvzyg1p6UPCY"
"nesxa9M2dDUrXHomRHOFHSfsbSXRFwt5GivtnJG9lLJHZ7XWeIQABi"
"dKionYD3O6c9tvUAoDosUJAdQ1RaSXTzyETbHTRtnTPeLpO3EedGMs"
"v3jG9yPcmmdYkddSeJRwn2raPJmnvdHScHUACw0sUNuosAqPaQbTQN"
"PATDzcrnd1Sf8RIbUp4MQJFVJugPLVZbP53Gjtyyniqe5q75kva8Qm"
"Hr1uOuXkVppe3cwECaGamupG43L1XfcpRjCMrxRep3s2VlbL01xmfz"
"5cIhrj34iVmgZSAmIb8ZxiHPdp1oDMFkbNetZyWegqjAHQQ9eoSOTD"
"bERbKEwZ5FLeLsbNAxfqsapB1XBvCavFHualx6bxVxuRQceh4z8kaZ"
"iv2pOKbZQSJ2Dx5HEq0bYZ6y6b7sN9IaeDFNQwjzQn1K7k3XlYAPWC"
"IvDe8Ln0FUe4yMNmuUhu5RTjxE05hUqtz1HjJvYQ9Es1VA6LflKQ87"
"TwIXBNvfrcHaZ72QM4dQtDUyEMrLgMDkJBDM9wqIDps65gSlAz6eHD"
"8tYWUttrWose0cH0yykVnqFzPtdRiZyZRfio6lGyK48mIC9z7T6MN3"
"a7OaLZHZSwzcpQLcGi7M9q1wXLq4Ms1UvlwntB9FLHc63tHPpG8rhn"
"XhZIk4QrSm4GYuEKQVHwku6ulw6wfggVL8FZPhoPCGsrb2rQGurBUL"
"3lkVJ6RO9VGHcczDYomXqAJqlt4y9pkQIj9kgwTrxTzEZgMGdYZqsV"
"4Bd5JjtrL7u3LA0N2Hq9Xvmmis2jDVhSQoUoGukNIoqng3SBsf0E7b"
"4W0S1aZSSOJ90nQHQkQShE9YIMDBbNwIg2ncthwADYqibYUgIvJcK9"
"89XHnYmZsdMWtt53lICsXE1vztR5WrQjSw4WXDiB31LXTrvudCB6vw"
"kCQa4leutETpKLJ2bYaOYBdoiBFOwvf36YaSuRoY4SP2x1pWOwGFTg"
"d90J2uYyCqUa3Q3iX52iigT4EKL2vJKdJ";
const uint8_t PatchSolution2::FunctionHeader[9] = {
0x55, // push rbp
0x48, 0x89, 0xe5, // mov rbp, rsp
0x41, 0x57, // push r15
0x41, 0x56, // push r14
0x53, // push rbx
};
PatchSolution2::PatchSolution2(const X64ImageInterpreter& Image) noexcept :
pvt_Image(Image),
pvt_Disassembler(CapstoneDisassembler::Create(CS_ARCH_X86, CS_MODE_64)),
pvt_Assembler(KeystoneAssembler::Create(KS_ARCH_X86, KS_MODE_64)),
pvt_FunctionOffset(X64ImageInterpreter::InvalidOffset),
pvt_KeywordOffset(X64ImageInterpreter::InvalidOffset),
pvt_StdStringAppendStubRva(X64ImageInterpreter::InvalidAddress)
{
pvt_Disassembler.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
bool PatchSolution2::FindPatchOffset() noexcept {
auto FunctionOffset = X64ImageInterpreter::InvalidOffset;
auto KeywordOffset = X64ImageInterpreter::InvalidOffset;
auto StdStringAppendStubRva = X64ImageInterpreter::InvalidAddress;
try {
auto Sec__text = pvt_Image.ImageSection("__TEXT", "__text");
auto Sec__const = pvt_Image.ImageSection("__TEXT", "__const");
auto Sec__stubs = pvt_Image.ImageSection("__TEXT", "__stubs");
auto SecView__text = pvt_Image.SectionView<uint8_t*>(Sec__text);
auto SecView__const = pvt_Image.SectionView<uint8_t*>(Sec__const);
auto SecView__stubs = pvt_Image.SectionView<uint8_t*>(Sec__stubs);
KeywordOffset = pvt_Image.SearchSectionOffset("__TEXT", "__const", [](const uint8_t* p) {
return memcmp(p, Keyword, sizeof(Keyword)) == 0;
});
auto KeywordRva = pvt_Image.OffsetToRva(KeywordOffset);
auto Hint = pvt_Image.SearchSectionOffset("__TEXT", "__text", [Sec__text, SecView__text, KeywordRva](const uint8_t* p) {
auto rip = (p - SecView__text) + Sec__text->addr + 4;
auto off = *reinterpret_cast<const uint32_t*>(p);
return rip + off == KeywordRva;
}) - 0xc0;
for (uint32_t i = 0; i < 0xc0; ++i) {
if (memcmp(pvt_Image.ImageOffset(Hint + i), FunctionHeader, sizeof(FunctionHeader)) == 0) {
FunctionOffset = Hint + i;
break;
}
}
if (FunctionOffset == X64ImageInterpreter::InvalidOffset) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Not found.");
}
pvt_Disassembler.SetContext(SecView__stubs, Sec__stubs->size, Sec__stubs->addr);
while (pvt_Disassembler.Next()) {
auto insn = pvt_Disassembler.GetInstruction();
//
// As far as I know, all stub functions have a pattern looking like:
// jmp qword ptr [RIP + xxxx]
//
if (strcasecmp(insn->mnemonic, "jmp") == 0 && insn->detail->x86.operands[0].type == X86_OP_MEM && insn->detail->x86.operands[0].mem.base == X86_REG_RIP) {
uint64_t la_symbol_ptr_rva = pvt_Disassembler.GetContext().Address + insn->detail->x86.operands[0].mem.disp;
uint32_t la_symbol_ptr_offset = pvt_Image.RvaToOffset(la_symbol_ptr_rva);
if (la_symbol_ptr_offset == X64ImageInterpreter::InvalidOffset)
continue;
uint64_t stub_helper_rva = *pvt_Image.ImageOffset<const uint64_t*>(la_symbol_ptr_offset);
uint32_t stub_helper_offset = pvt_Image.RvaToOffset(stub_helper_rva);
if (stub_helper_offset == X64ImageInterpreter::InvalidOffset)
continue;
//
// __ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKc
// is the mangled name of "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::append(char const*)",
// which is, as known as, "std::string::append(const char*)"
// You can demangle it by c++flit
// e.g.
// c++filt -_ '__ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKc'
//
if (nkg::IsResolvedTo(pvt_Image, pvt_Image.ImageOffset(stub_helper_offset), "__ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKc")) {
auto StdStringAppendStubOffset = pvt_Disassembler.GetInstructionContext().pbOpcode - pvt_Image.ImageBase<const uint8_t*>();
StdStringAppendStubRva = pvt_Image.OffsetToRva(StdStringAppendStubOffset);
break;
}
}
}
if (StdStringAppendStubRva == X64ImageInterpreter::InvalidAddress) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Not found.");
}
pvt_FunctionOffset = FunctionOffset;
pvt_KeywordOffset = KeywordOffset;
pvt_StdStringAppendStubRva = StdStringAppendStubRva;
printf("[+] PatchSolution2 ...... Ready to apply.\n");
printf(" Function offset = +0x%.8x\n", pvt_FunctionOffset);
printf(" Keyword offset = +0x%.8x\n", pvt_KeywordOffset);
printf(" std::string::append(const char*) RVA = 0x%.16llx\n", pvt_StdStringAppendStubRva);
return true;
} catch (...) {
printf("[-] PatchSolution2 ...... Omitted.\n");
return false;
}
}
[[nodiscard]]
bool PatchSolution2::CheckKey(const RSACipher& RsaCipher) const noexcept {
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
PublicKeyPEM.erase(PublicKeyPEM.find("-----BEGIN PUBLIC KEY-----"), 26);
PublicKeyPEM.erase(PublicKeyPEM.find("-----END PUBLIC KEY-----"), 24);
{
std::string::size_type pos = 0;
while ((pos = PublicKeyPEM.find('\n', pos)) != std::string::npos) {
PublicKeyPEM.erase(pos, 1);
}
}
return PublicKeyPEM.length() == 0x188;
}
void PatchSolution2::MakePatch(const RSACipher& RsaCipher) const {
if (pvt_FunctionOffset == X64ImageInterpreter::InvalidOffset ||
pvt_KeywordOffset == X64ImageInterpreter::InvalidOffset ||
pvt_StdStringAppendStubRva == X64ImageInterpreter::InvalidAddress)
{
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "PatchSolution2 is not ready.");
}
//
// Prepare public key string
//
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
PublicKeyPEM.erase(PublicKeyPEM.find("-----BEGIN PUBLIC KEY-----"), 26);
PublicKeyPEM.erase(PublicKeyPEM.find("-----END PUBLIC KEY-----"), 24);
{
std::string::size_type pos = 0;
while ((pos = PublicKeyPEM.find('\n', pos)) != std::string::npos) {
PublicKeyPEM.erase(pos, 1);
}
}
//
// Prepare new function opcodes
//
uint64_t FunctionRVA = pvt_Image.OffsetToRva(pvt_FunctionOffset);
uint64_t KeywordRVA = pvt_Image.OffsetToRva(pvt_KeywordOffset);
char AssemblyCode[512] = {};
sprintf(AssemblyCode,
"push rbp;"
"mov rbp, rsp;"
"push r15;"
"push r14;"
"push rbx;"
"sub rsp, 0x48;"
"mov rbx, rdi;"
"xor rax, rax;" // initialize std::string with null
"mov qword ptr[rsp], rax;"
"mov qword ptr[rsp + 0x8], rax;"
"mov qword ptr[rsp + 0x10], rax;"
"lea rdi, qword ptr[rsp];"
"lea rsi, qword ptr[0x%.16llx];" // filled with address to Keyword
"call 0x%.16llx;" // filled with address to std::string::append(const char*)
"mov rax, qword ptr[rsp];"
"mov qword ptr[rbx], rax;"
"mov rax, qword ptr[rsp + 0x8];"
"mov qword ptr[rbx + 0x8], rax;"
"mov rax, qword ptr[rsp + 0x10];"
"mov qword ptr[rbx + 0x10], rax;"
"mov rax, rbx;"
"add rsp, 0x48;"
"pop rbx;"
"pop r14;"
"pop r15;"
"pop rbp;"
"ret;",
KeywordRVA,
pvt_StdStringAppendStubRva
);
auto NewFunctionOpcode = pvt_Assembler.GenerateOpcode(AssemblyCode, FunctionRVA);
auto pbFunctionPatch = pvt_Image.ImageOffset<uint8_t*>(pvt_FunctionOffset);
auto pbKeywordPatch = pvt_Image.ImageOffset<uint8_t*>(pvt_KeywordOffset);
puts("**************************************************************");
puts("* PatchSolution2 *");
puts("**************************************************************");
printf("@+0x%.8x\n", pvt_KeywordOffset);
puts("Previous:");
nkg::PrintMemory(pbKeywordPatch, pbKeywordPatch + sizeof(Keyword) - 1, pbKeywordPatch);
memcpy(pbKeywordPatch, PublicKeyPEM.c_str(), PublicKeyPEM.length() + 1); // with a null-terminator
puts("After:");
nkg::PrintMemory(pbKeywordPatch, pbKeywordPatch + sizeof(Keyword) - 1, pbKeywordPatch);
puts("");
printf("@+0x%.8x\n", pvt_FunctionOffset);
puts("Previous:");
nkg::PrintMemory(pbFunctionPatch, pbFunctionPatch + NewFunctionOpcode.size(), pbFunctionPatch);
memcpy(pbFunctionPatch, NewFunctionOpcode.data(), NewFunctionOpcode.size());
puts("After:");
nkg::PrintMemory(pbFunctionPatch, pbFunctionPatch + NewFunctionOpcode.size(), pbFunctionPatch);
puts("");
}
-231
View File
@@ -1,231 +0,0 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution3-amd64.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
PatchSolution3::PatchSolution3(const ImageInterpreter& Image) :
_Image(Image),
_Engine(CS_ARCH_X86, CS_MODE_64),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
PatchSolution3::PatchSolution3(const ImageInterpreter* lpImage) :
_Image(*lpImage),
_Engine(CS_ARCH_X86, CS_MODE_64),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
[[nodiscard]]
bool PatchSolution3::CheckIfMatchPattern(const cs_insn* lpInsn) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for IMM_DATA
// 2. lea REG, PTR [MEM] (MEM must point to a non-empty printable string) // for STRING_DATA
if (_stricmp(lpInsn->mnemonic, "mov") == 0) {
if (lpInsn->detail->x86.operands[1].type != X86_OP_IMM) {
return false;
}
auto pbImmValue = lpInsn->bytes + lpInsn->detail->x86.encoding.imm_offset;
auto cbImmValue = lpInsn->detail->x86.encoding.imm_size;
return IsPrintable(pbImmValue, cbImmValue);
} else if (_stricmp(lpInsn->mnemonic, "lea") == 0) {
// as far as I know, all strings are loaded by "lea REG, QWORD PTR [RIP + disp]"
// so operands[1] must look like "[RIP + disp]"
if (lpInsn->detail->x86.operands[1].mem.base != X86_REG_RIP) {
return false;
}
// scale must 1, otherwise pattern mismatches
if (lpInsn->detail->x86.operands[1].mem.scale != 1) {
return false;
}
auto StringRva = static_cast<uintptr_t>(
lpInsn->address + lpInsn->size + // Next RIP
lpInsn->detail->x86.operands[1].mem.disp
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
auto StringLength = strlen(StringPtr);
// StringPtr must have at least one char
// every char in StringPtr must be printable, otherwise pattern mismatches
return StringLength && IsPrintable(StringPtr, StringLength);
} catch (nkg::Exception&) {
// If not found, pattern mismatches
return false;
}
} else {
return false;
}
}
[[nodiscard]]
bool PatchSolution3::CheckIfFound(const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for IMM_DATA
// 2. lea REG, PTR [MEM] (MEM must point to a non-empty printable string) // for STRING_DATA
auto& op_count = lpInsn->detail->x86.op_count;
auto& operands = lpInsn->detail->x86.operands;
if (op_count != 2) {
return false;
}
if (Keyword[KeywordIdx].Type == IMM_DATA && operands[1].type == X86_OP_IMM) {
static_assert(sizeof(operands[1].imm) == sizeof(Keyword[KeywordIdx].Value));
return
operands[1].imm == *reinterpret_cast<const int64_t*>(Keyword[KeywordIdx].Value) &&
lpInsn->detail->x86.encoding.imm_size == Keyword[KeywordIdx].Size;
} else if (Keyword[KeywordIdx].Type == STRING_DATA && operands[1].type == X86_OP_MEM) {
auto StringRva = static_cast<uintptr_t>(
lpInsn->address + lpInsn->size + // Next RIP
operands[1].mem.disp
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
return
strncmp(StringPtr, reinterpret_cast<const char*>(Keyword[KeywordIdx].Value), Keyword[KeywordIdx].Size) == 0 &&
StringPtr[Keyword[KeywordIdx].Size] == '\x00';
} catch (nkg::Exception&) {
return false;
}
} else {
return false;
}
}
[[nodiscard]]
PatchSolution3::PatchInfo PatchSolution3::CreatePatchPoint(const void* lpOpcode, const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
PatchInfo NewPatch;
NewPatch.OpcodeRva = lpInsn->address;
NewPatch.lpOpcode = const_cast<void*>(lpOpcode);
if (lpInsn->detail->x86.operands[1].type == X86_OP_MEM) {
auto StringRva = static_cast<uintptr_t>(
lpInsn->address + lpInsn->size + // Next RIP
lpInsn->detail->x86.operands[1].mem.disp
);
NewPatch.lpOriginalString = _Image.RvaToPointer<char*>(StringRva);
if (Keyword[KeywordIdx].NotRecommendedToModify) {
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.disp_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.disp_size;
} else {
NewPatch.lpPatch = reinterpret_cast<uint8_t*>(NewPatch.lpOriginalString);
NewPatch.cbPatch = Keyword[KeywordIdx].Size;
}
} else { // X86_OP_IMM
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.imm_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.imm_size;
NewPatch.lpOriginalString = nullptr;
}
NewPatch.lpReplaceString = nullptr;
return NewPatch;
}
[[nodiscard]]
bool PatchSolution3::FindPatchOffset() noexcept {
try {
static const uint8_t HeaderOfTargetFunction[] = {
0x40, 0x55, // push rbp
0x48, 0x8D, 0xAC, 0x24, 0x70, 0xBC, 0xFF, 0xFF, // lea rbp, [rsp-4390h]
0xB8, 0x90, 0x44, 0x00, 0x00 // mov eax, 4490h
};
PatchInfo Patch[_countof(_Patch)] = {};
const uint8_t* lpTargetFunction = nullptr;
auto lptargetFunctionHint = _Image.SearchSection<const uint8_t*>(".text", [&lpTargetFunction](const uint8_t* p) {
__try {
if (*reinterpret_cast<const uint32_t*>(p) == 0x6b67424e) {
auto i = p - 0x250;
for (; i < p; ++i) {
if (memcmp(i, HeaderOfTargetFunction, sizeof(HeaderOfTargetFunction)) == 0) {
lpTargetFunction = i;
return true;
}
}
}
return false;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
size_t KeywordIndex = 0;
CapstoneDisassembler Disassembler = _Engine.CreateDisassembler();
Disassembler.SetContext(CapstoneContext{ lpTargetFunction, 0xcd03, _Image.PointerToRva(lpTargetFunction) });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIndex));
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Reach end of function."));
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
if (CheckIfFound(lpInsn, KeywordIndex) == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Missing a patch."));
}
Patch[KeywordIndex] = CreatePatchPoint(Disassembler.GetInstructionContext().lpMachineCode, lpInsn, KeywordIndex);
++KeywordIndex;
}
if (KeywordIndex == _countof(Patch)) {
break;
}
}
if (KeywordIndex != _countof(Patch)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Some patches are not found."));
}
LOG_SUCCESS(0, "PatchSolution3 ...... Ready to apply");
for (size_t i = 0; i < _countof(Patch); ++i) {
_Patch[i] = Patch[i];
LOG_HINT(4, "[%3zu] Instruction RVA = 0x%.8llx, Patch Offset = +0x%.8zx", i, _Patch[i].OpcodeRva, address_delta(_Patch[i].lpPatch, _Image.ImageBase()));
}
return true;
} catch (nkg::Exception&) {
memset(_Patch, 0, sizeof(_Patch));
LOG_FAILURE(0, "PatchSolution3 ...... Omitted");
return false;
}
}
}
-424
View File
@@ -1,424 +0,0 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution3-generic.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
const PatchSolution3::KeywordInfo PatchSolution3::Keyword[111] = {
{ { 0x4d, 0x49, 0x49 }, 3, STRING_DATA, false },
{ { 0x42, 0x49 }, 2, IMM_DATA, false },
{ { 0x6a }, 1, IMM_DATA, false },
{ { 0x41 }, 1, IMM_DATA, false },
{ { 0x4e, 0x42, 0x67, 0x6b }, 4, IMM_DATA, false },
{ { 0x71 }, 1, IMM_DATA, false },
{ { 0x68, 0x6b, 0x69, 0x47, 0x39, 0x77 }, 6, STRING_DATA, false },
{ { 0x30 }, 1, STRING_DATA, true },
{ { 0x42 }, 1, IMM_DATA, false },
{ { 0x41 }, 1, IMM_DATA, false },
{ { 0x51, 0x45, 0x46, 0x41, 0x41, 0x4f, 0x43 }, 7, STRING_DATA, false },
{ { 0x41, 0x51, 0x38, 0x41, 0x4d, 0x49 }, 6, STRING_DATA, false },
{ { 0x49, 0x42 }, 2, STRING_DATA, false },
{ { 0x43, 0x67, 0x4b, 0x43 }, 4, IMM_DATA, false },
{ { 0x41, 0x51 }, 2, STRING_DATA, false },
{ { 0x45, 0x41, 0x77, 0x31 }, 4, IMM_DATA, false },
{ { 0x64, 0x71, 0x46, 0x33 }, 4, IMM_DATA, false },
{ { 0x53 }, 1, STRING_DATA, true },
{ { 0x6b, 0x43, 0x61, 0x41, 0x41, 0x6d }, 6, STRING_DATA, false },
{ { 0x4d, 0x7a, 0x73, 0x38 }, 4, IMM_DATA, false },
{ { 0x38, 0x39, 0x49, 0x71 }, 4, IMM_DATA, false },
{ { 0x64 }, 1, IMM_DATA, false },
{ { 0x57 }, 1, IMM_DATA, false },
{ { 0x39, 0x4d, 0x32, 0x64 }, 4, IMM_DATA, false },
{ { 0x49, 0x64, 0x68 }, 3, STRING_DATA, false },
{ { 0x33, 0x6a }, 2, IMM_DATA, false },
{ { 0x47, 0x39, 0x79, 0x50 }, 4, IMM_DATA, false },
{ { 0x63, 0x6d }, 2, IMM_DATA, false },
{ { 0x4c }, 1, IMM_DATA, false },
{ { 0x6e, 0x6d, 0x4a }, 3, STRING_DATA, false },
{ { 0x69, 0x47, 0x70, 0x42, 0x46, 0x34, 0x45 }, 7, STRING_DATA, false },
{ { 0x39, 0x56, 0x48, 0x53, 0x4d, 0x47 }, 6, STRING_DATA, false },
{ { 0x65, 0x38, 0x6f, 0x50, 0x41, 0x79, 0x32, 0x6b }, 8, STRING_DATA, false },
{ { 0x4a, 0x44 }, 2, STRING_DATA, false },
{ { 0x6d, 0x64 }, 2, IMM_DATA, false },
{ { 0x4e, 0x74, 0x34 }, 3, STRING_DATA, false },
{ { 0x42, 0x63, 0x45, 0x79, 0x67, 0x76 }, 6, STRING_DATA, false },
{ { 0x73, 0x73, 0x45, 0x66, 0x67, 0x69 }, 6, STRING_DATA, false },
{ { 0x6e, 0x76, 0x61, 0x35, 0x74 }, 5, STRING_DATA, false },
{ { 0x35, 0x6a, 0x6d, 0x33, 0x35, 0x32 }, 6, STRING_DATA, false },
{ { 0x55, 0x41 }, 2, IMM_DATA, false },
{ { 0x6f, 0x44, 0x6f, 0x73 }, 4, IMM_DATA, false },
{ { 0x55, 0x4a }, 2, IMM_DATA, false },
{ { 0x6b, 0x54, 0x58, 0x47, 0x51 }, 5, STRING_DATA, false },
{ { 0x68, 0x70, 0x41, 0x57, 0x4d, 0x46 }, 6, STRING_DATA, false },
{ { 0x34, 0x66, 0x42, 0x6d, 0x42 }, 5, STRING_DATA, false },
{ { 0x70, 0x4f, 0x33, 0x45 }, 4, IMM_DATA, false },
{ { 0x65, 0x64 }, 2, IMM_DATA, false },
{ { 0x47 }, 1, IMM_DATA, false },
{ { 0x36, 0x32, 0x72, 0x4f, 0x73, 0x71 }, 6, STRING_DATA, false },
{ { 0x4d }, 1, IMM_DATA, false },
{ { 0x42, 0x67, 0x6d, 0x53 }, 4, STRING_DATA, false },
{ { 0x64 }, 1, IMM_DATA, false },
{ { 0x41, 0x79, 0x78, 0x43, 0x53 }, 5, STRING_DATA, false },
{ { 0x50 }, 1, IMM_DATA, false },
{ { 0x42, 0x52, 0x4a, 0x49, 0x4f }, 5, STRING_DATA, false },
{ { 0x46, 0x52, 0x30, 0x51, 0x67, 0x5a, 0x46, 0x62 }, 8, STRING_DATA, false },
{ { 0x52 }, 1, IMM_DATA, false },
{ { 0x6e, 0x55, 0x30, 0x66 }, 4, STRING_DATA, false },
{ { 0x72, 0x6a, 0x33, 0x34 }, 4, IMM_DATA, false },
{ { 0x66 }, 1, STRING_DATA, true },
{ { 0x69, 0x56, 0x6d, 0x67 }, 4, IMM_DATA, false },
{ { 0x59, 0x69, 0x4c, 0x75 }, 4, STRING_DATA, false },
{ { 0x5a, 0x53, 0x41, 0x6d }, 4, IMM_DATA, false },
{ { 0x49, 0x62 }, 2, IMM_DATA, false },
{ { 0x73 }, 1, IMM_DATA, false },
{ { 0x38, 0x5a, 0x78, 0x69 }, 4, IMM_DATA, false },
{ { 0x48 }, 1, IMM_DATA, false },
{ { 0x50, 0x64, 0x70, 0x31 }, 4, IMM_DATA, false },
{ { 0x6f, 0x44 }, 2, IMM_DATA, false },
{ { 0x34 }, 1, IMM_DATA, false },
{ { 0x74, 0x55, 0x70, 0x76, 0x73, 0x46 }, 6, STRING_DATA, false },
{ { 0x63, 0x69, 0x34, 0x51, 0x4a, 0x74 }, 6, STRING_DATA, false },
{ { 0x59, 0x4e, 0x6a, 0x4e, 0x6e, 0x47, 0x55 }, 7, STRING_DATA, false },
{ { 0x32, 0x57, 0x50, 0x48 }, 4, STRING_DATA, false },
{ { 0x36, 0x72, 0x76, 0x43, 0x68, 0x47, 0x6c }, 7, STRING_DATA, false },
{ { 0x31, 0x49, 0x52, 0x4b, 0x72, 0x78, 0x4d, 0x74 }, 8, STRING_DATA, false },
{ { 0x71, 0x4c, 0x69, 0x65, 0x6c }, 5, STRING_DATA, false },
{ { 0x73, 0x76, 0x61, 0x6a, 0x55, 0x6a, 0x79, 0x72 }, 8, STRING_DATA, false },
{ { 0x67 }, 1, STRING_DATA, true },
{ { 0x4f, 0x43, 0x36, 0x4e, 0x6d, 0x79, 0x6d, 0x59 }, 8, STRING_DATA, false },
{ { 0x4d }, 1, IMM_DATA, false },
{ { 0x76, 0x5a, 0x4e }, 3, STRING_DATA, false },
{ { 0x45, 0x52, 0x33, 0x68, 0x74 }, 5, STRING_DATA, false },
{ { 0x46 }, 1, IMM_DATA, false },
{ { 0x45, 0x74, 0x4c, 0x31 }, 4, STRING_DATA, false },
{ { 0x65, 0x51, 0x62, 0x43, 0x79 }, 5, STRING_DATA, false },
{ { 0x54, 0x66, 0x44, 0x6d, 0x74, 0x59, 0x79, 0x51 }, 8, STRING_DATA, false },
{ { 0x31, 0x57, 0x74, 0x34 }, 4, STRING_DATA, false },
{ { 0x4f }, 1, IMM_DATA, false },
{ { 0x74, 0x31, 0x32, 0x6c, 0x78, 0x66 }, 6, STRING_DATA, false },
{ { 0x30 }, 1, IMM_DATA, false },
{ { 0x77, 0x56, 0x49, 0x52, 0x35 }, 5, STRING_DATA, false },
{ { 0x6d }, 1, IMM_DATA, false },
{ { 0x63, 0x47, 0x4e, 0x37 }, 4, STRING_DATA, false },
{ { 0x58, 0x43, 0x58, 0x4a }, 4, STRING_DATA, false },
{ { 0x52, 0x48, 0x4f, 0x46 }, 4, IMM_DATA, false },
{ { 0x48, 0x53 }, 2, IMM_DATA, false },
{ { 0x66 }, 1, IMM_DATA, false },
{ { 0x31, 0x67, 0x7a, 0x58, 0x57 }, 5, STRING_DATA, false },
{ { 0x61 }, 1, IMM_DATA, false },
{ { 0x62 }, 1, IMM_DATA, false },
{ { 0x52, 0x53 }, 2, STRING_DATA, false },
{ { 0x76, 0x6d, 0x74, 0x31, 0x6e }, 5, STRING_DATA, false },
{ { 0x72, 0x6c }, 2, STRING_DATA, true },
{ { 0x37, 0x73, 0x57 }, 3, STRING_DATA, false },
{ { 0x36, 0x63, 0x6a }, 3, STRING_DATA, false },
{ { 0x78, 0x6c, 0x6a, 0x75, 0x75, 0x51, 0x61 }, 7, STRING_DATA, false },
{ { 0x77, 0x49, 0x44, 0x41 }, 4, STRING_DATA, false },
{ { 0x51, 0x41 }, 2, IMM_DATA, false },
{ { 0x42 }, 1, IMM_DATA, false }
};
[[nodiscard]]
bool PatchSolution3::IsPrintable(const void* p, size_t s) noexcept {
auto pb = reinterpret_cast<const uint8_t*>(p);
for (size_t i = 0; i < s; ++i) {
if (isprint(pb[i]) == false) {
return false;
}
}
return true;
}
[[nodiscard]]
CapstoneContext PatchSolution3::GetJumpedBranch(const CapstoneContext& NotJumpedBranch, const cs_insn* lpJxxInsn) const {
CapstoneContext JumpedBranch;
JumpedBranch.lpMachineCode = _Image.RvaToPointer<const void*>(
static_cast<uintptr_t>(lpJxxInsn->detail->x86.operands[0].imm)
);
JumpedBranch.cbMachineCode = NotJumpedBranch.cbMachineCode - (
reinterpret_cast<const uint8_t*>(JumpedBranch.lpMachineCode) -
reinterpret_cast<const uint8_t*>(NotJumpedBranch.lpMachineCode)
);
JumpedBranch.Address = lpJxxInsn->detail->x86.operands[0].imm;
return JumpedBranch;
}
[[nodiscard]]
CapstoneContext PatchSolution3::SelectBranch(const CapstoneContext& NotJumpedBranch, const CapstoneContext& JumpedBranch, size_t KeywordIdx) const {
CapstoneContext A = NotJumpedBranch;
CapstoneContext B = JumpedBranch;
int WeightA = 0;
int WeightB = 0;
auto Disassembler = _Engine.CreateDisassembler();
while (true) {
int WeightAPrev = WeightA;
int WeightBPrev = WeightB;
//
// process NotJumpedBranch
//
Disassembler.SetContext(A);
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// For all x86 mnemonics, only 'jcc' or 'jmp' starts with 'j' or 'J'.
// So it should be a new branch if we meet them.
//
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
try {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIdx));
} catch (nkg::Exception&) {
// If exception occurs, give up NotJumpedBranch
break;
}
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
return JumpedBranch;
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
//
// if match pattern, but keyword doesn't match,
// NotJumpedBranch must not be what we want
//
if (CheckIfFound(lpInsn, KeywordIdx) == false) {
return JumpedBranch;
}
//
// If keyword is succeeded to match
// Add WeightA and stop processing NotJumpedBranch
//
++WeightA;
break;
}
}
A = Disassembler.GetContext();
//
// process JumpedBranch
//
Disassembler.SetContext(B);
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// For all x86 mnemonics, only 'jcc' or 'jmp' starts with 'j' or 'J'.
// So it should be a new branch if we meet them.
//
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
try {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIdx));
} catch (nkg::Exception&) {
// If exception occurs, give up JumpedBranch
break;
}
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
return NotJumpedBranch;
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
//
// if match pattern, but keyword doesn't match,
// JumpedBranch must not be what we want
//
if (CheckIfFound(lpInsn, KeywordIdx) == false) {
return NotJumpedBranch;
}
//
// If keyword is succeeded to match
// Add WeightB and stop processing JumpedBranch
//
++WeightB;
break;
}
}
B = Disassembler.GetContext();
//
// If this happens, it means neither of two branch is our target
if (WeightAPrev == WeightA && WeightBPrev == WeightB) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Branch is not selected."));
}
if (WeightA != WeightB)
return WeightA > WeightB ? NotJumpedBranch : JumpedBranch;
else
++KeywordIdx;
}
}
[[nodiscard]]
bool PatchSolution3::CheckKey(const RSACipher& Cipher) const noexcept {
//
// Brute-force search, cchString should be 1 or 2
//
auto SearchString = [](const void* lpRange, size_t cbRange, const char* lpString, size_t cchString) -> const char* {
const char* p = reinterpret_cast<const char*>(lpRange);
for (size_t i = 0; i < cbRange; ++i) {
if (p[i] == lpString[0]) {
bool match = true;
__try {
for (size_t j = 1; j < cchString; ++j) {
if (p[i + j] != lpString[j]) {
match = false;
break;
}
}
} __except (EXCEPTION_EXECUTE_HANDLER) {
match = false;
}
if (match && p[i + cchString] == '\x00')
return address_offset_cast<const char*>(lpRange, i);
}
}
return nullptr;
};
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
if (szPublicKey.length() != 0x188) {
return false;
}
size_t PublicKeyReadCursor = 0;
auto SectionHeader_rdata = _Image.ImageSectionHeaderByName(".rdata");
auto SectionView_rdata = _Image.ImageSectionView(SectionHeader_rdata);
for (size_t i = 0; i < _countof(_Patch); PublicKeyReadCursor += Keyword[i].Size, ++i) {
if (Keyword[i].NotRecommendedToModify) {
_Patch[i].lpReplaceString = nullptr;
const char* lpReplaceString = nullptr;
const void* lpSearchRange = _Patch[i].lpOriginalString;
size_t cbSearchRange = SectionHeader_rdata->SizeOfRawData - address_delta(_Patch[i].lpOriginalString, SectionView_rdata);
for (size_t offset = 0;;) {
lpReplaceString = SearchString(
address_offset(lpSearchRange, offset),
cbSearchRange - offset,
szPublicKey.c_str() + PublicKeyReadCursor,
Keyword[i].Size
);
if (lpReplaceString == nullptr) {
return false;
}
if (_Image.IsRvaRangeInRelocTable(_Image.PointerToRva(lpReplaceString), Keyword[i].Size + 1)) {
//
// Damn it!
// ReplaceString will be modified during relocation
// We have to find another one
//
++offset;
} else {
//
// ReplaceString won't be modified during relocation
// which can be used to act as a part of public key string
//
break;
}
}
_Patch[i].lpReplaceString = const_cast<char*>(lpReplaceString);
}
}
return true;
}
void PatchSolution3::MakePatch(const RSACipher& Cipher) const {
for (size_t i = 0; i < _countof(_Patch); ++i) {
if (_Patch[i].lpPatch == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution3 has not been ready yet."));
}
}
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution3 *"));
_putts(TEXT("*******************************************************"));
size_t readptr = 0;
for (size_t i = 0; i < _countof(_Patch); readptr += Keyword[i].Size, ++i) {
_tprintf_s(TEXT("[*] +%.8zx: "), address_delta(_Patch[i].lpPatch, _Image.ImageBase()));
PrintBytes(_Patch[i].lpPatch, _Patch[i].cbPatch);
_tprintf_s(TEXT(" ---> "));
if (Keyword[i].NotRecommendedToModify) {
auto offset = _Patch[i].lpReplaceString - _Patch[i].lpOriginalString;
uint64_t disp = 0;
memcpy(&disp, _Patch[i].lpPatch, _Patch[i].cbPatch);
disp += offset;
memcpy(_Patch[i].lpPatch, &disp, _Patch[i].cbPatch);
} else {
memcpy(_Patch[i].lpPatch, szPublicKey.c_str() + readptr, Keyword[i].Size);
}
PrintBytes(_Patch[i].lpPatch, _Patch[i].cbPatch);
_tprintf_s(TEXT("\n"));
}
_putts(TEXT(""));
return;
}
}
-247
View File
@@ -1,247 +0,0 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution3-i386.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
PatchSolution3::PatchSolution3(const ImageInterpreter& Image) :
_Image(Image),
_Engine(CS_ARCH_X86, CS_MODE_32),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
PatchSolution3::PatchSolution3(const ImageInterpreter* lpImage) :
_Image(*lpImage),
_Engine(CS_ARCH_X86, CS_MODE_32),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
[[nodiscard]]
bool PatchSolution3::CheckIfMatchPattern(const cs_insn* lpInsn) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// except pattern "mov [ebp - 0x4], IMM"
// 2. push IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// 3. push offset MEM (MEM must point to a non-empty printable string) // for KeywordType::STRING_DATA
//
if (_stricmp(lpInsn->mnemonic, "mov") == 0) {
// filter the case "mov [ebp - 0x4], IMM"
// because IMM may consist of printable chars in that case, which will mislead us.
//
// Here I use "> -0x30" to intensify condition, instead of "== -0x4"
if (lpInsn->detail->x86.operands[0].type == X86_OP_MEM &&
lpInsn->detail->x86.operands[0].mem.base == X86_REG_EBP &&
lpInsn->detail->x86.operands[0].mem.disp > -0x30)
{
return false;
}
if (lpInsn->detail->x86.operands[1].type != X86_OP_IMM) {
return false;
}
auto pbImmValue = lpInsn->bytes + lpInsn->detail->x86.encoding.imm_offset;
auto cbImmValue = lpInsn->detail->x86.encoding.imm_size;
// each bytes of imm must be printable;
return IsPrintable(pbImmValue, cbImmValue);
} else if (_stricmp(lpInsn->mnemonic, "push") == 0) {
if (lpInsn->detail->x86.operands[0].type != X86_OP_IMM) {
return false;
}
// test if match pattern 2
auto pbImmValue = lpInsn->bytes + lpInsn->detail->x86.encoding.imm_offset;
auto cbImmValue = lpInsn->detail->x86.encoding.imm_size;
if (IsPrintable(pbImmValue, cbImmValue)) {
return true;
}
// test if match pattern 3
auto StringRva = static_cast<uintptr_t>(
lpInsn->detail->x86.operands[0].imm - _Image.ImageNtHeaders()->OptionalHeader.ImageBase
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
auto StringLength = strlen(StringPtr);
// StringPtr must have at least one char
// every char in StringPtr must be printable, otherwise pattern mismatches
return StringLength && IsPrintable(StringPtr, StringLength);
} catch (nkg::Exception&) {
// If not found, pattern mismatches
return false;
}
} else {
return false;
}
}
[[nodiscard]]
bool PatchSolution3::CheckIfFound(const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// except pattern "mov [ebp - 0x4], IMM"
// 2. push IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// 3. push offset MEM (MEM must point to a non-empty printable string) // for KeywordType::STRING_DATA
//
auto& op_count = lpInsn->detail->x86.op_count;
auto& operands = lpInsn->detail->x86.operands;
if (op_count < 1 || operands[op_count - 1].type != X86_OP_IMM) {
return false;
}
if (Keyword[KeywordIdx].Type == IMM_DATA) {
static_assert(sizeof(operands[op_count - 1].imm) == sizeof(Keyword[KeywordIdx].Value));
return
operands[op_count - 1].imm == *reinterpret_cast<const int64_t*>(Keyword[KeywordIdx].Value) &&
lpInsn->detail->x86.encoding.imm_size == Keyword[KeywordIdx].Size;
} else if (Keyword[KeywordIdx].Type == STRING_DATA) {
auto StringRva = static_cast<uintptr_t>(
operands[op_count - 1].imm - _Image.ImageNtHeaders()->OptionalHeader.ImageBase
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
return
strncmp(StringPtr, reinterpret_cast<const char*>(Keyword[KeywordIdx].Value), Keyword[KeywordIdx].Size) == 0 &&
StringPtr[Keyword[KeywordIdx].Size] == '\x00';
} catch (nkg::Exception&) {
return false;
}
} else {
return false;
}
}
[[nodiscard]]
PatchSolution3::PatchInfo PatchSolution3::CreatePatchPoint(const void* lpOpcode, const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
PatchInfo NewPatch;
NewPatch.OpcodeRva = lpInsn->address;
NewPatch.lpOpcode = const_cast<void*>(lpOpcode);
if (Keyword[KeywordIdx].Type == IMM_DATA) {
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.imm_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.imm_size;
NewPatch.lpOriginalString = nullptr;
} else {
auto StringRva = static_cast<uintptr_t>(
lpInsn->detail->x86.operands[0].imm - _Image.ImageNtHeaders()->OptionalHeader.ImageBase
);
NewPatch.lpOriginalString = _Image.RvaToPointer<char*>(StringRva);
if (Keyword[KeywordIdx].NotRecommendedToModify) {
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.imm_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.imm_size;
} else {
NewPatch.lpPatch = reinterpret_cast<uint8_t*>(NewPatch.lpOriginalString);
NewPatch.cbPatch = Keyword[KeywordIdx].Size;
}
}
NewPatch.lpReplaceString = nullptr;
return NewPatch;
}
[[nodiscard]]
bool PatchSolution3::FindPatchOffset() noexcept {
try {
static const uint8_t HeaderOfTargetFunction[] = {
0x55, // push ebp
0x8B, 0xEC, // mov ebp, esp
0x6A, 0xFF // push 0xffffffff
};
PatchInfo Patch[_countof(_Patch)] = {};
const uint8_t* lpTargetFunction = nullptr;
auto lptargetFunctionHint = _Image.SearchSection<const uint8_t*>(".text", [&lpTargetFunction](const uint8_t* p) {
__try {
if (*reinterpret_cast<const uint32_t*>(p) == 0x6b67424e) {
auto i = p - 0x1B0;
for (; i < p; ++i) {
if (memcmp(i, HeaderOfTargetFunction, sizeof(HeaderOfTargetFunction)) == 0) {
lpTargetFunction = i;
return true;
}
}
}
return false;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
size_t KeywordIndex = 0;
CapstoneDisassembler Disassembler = _Engine.CreateDisassembler();
Disassembler.SetContext(CapstoneContext{ lpTargetFunction, 0x9014, _Image.PointerToRva(lpTargetFunction) });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIndex));
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
return false;
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
if (CheckIfFound(lpInsn, KeywordIndex) == false) {
return false;
}
Patch[KeywordIndex] = CreatePatchPoint(Disassembler.GetInstructionContext().lpMachineCode, lpInsn, KeywordIndex);
++KeywordIndex;
}
if (KeywordIndex == _countof(Patch)) {
break;
}
}
if (KeywordIndex != _countof(Patch)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Some patches are not found."));
}
LOG_SUCCESS(0, "PatchSolution3 ...... Ready to apply");
for (size_t i = 0; i < _countof(Patch); ++i) {
_Patch[i] = Patch[i];
LOG_HINT(4, "[%3zu] Instruction RVA = 0x%.8llx, Patch Offset = +0x%.8zx", i, _Patch[i].OpcodeRva, address_delta(_Patch[i].lpPatch, _Image.ImageBase()));
}
return true;
} catch (nkg::Exception&) {
memset(_Patch, 0, sizeof(_Patch));
LOG_FAILURE(0, "PatchSolution3 ...... Omitted");
return false;
}
}
}
-150
View File
@@ -1,150 +0,0 @@
#include "PatchSolutions.hpp"
#include <xstring.hpp>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution4-amd64.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
PatchSolution4::PatchSolution4(const ImageInterpreter& Image) :
_Image(Image),
_DisassemblyEngine(CS_ARCH_X86, CS_MODE_64),
_AssemblyEngine(KS_ARCH_X86, KS_MODE_64),
_pbPatchMachineCode(nullptr),
_pbPatchNewPublicKey(nullptr) { _DisassemblyEngine.Option(CS_OPT_DETAIL, CS_OPT_ON); }
PatchSolution4::PatchSolution4(const ImageInterpreter* Image) :
_Image(*Image),
_DisassemblyEngine(CS_ARCH_X86, CS_MODE_64),
_AssemblyEngine(KS_ARCH_X86, KS_MODE_64),
_pbPatchMachineCode(nullptr),
_pbPatchNewPublicKey(nullptr) { _DisassemblyEngine.Option(CS_OPT_DETAIL, CS_OPT_ON); }
bool PatchSolution4::FindPatchOffset() noexcept {
try {
_pbPatchMachineCode = _Image.SearchSection<uint8_t*>(".text", [](const uint8_t* p) {
__try {
return
p[0] == 0x48 && p[1] == 0x8d && // prefix of "lea rcx, [rbp+5Fh+var_38]"
p[4] == 0x48 && p[5] == 0x83 && // prefix of "cmp [rbp+5Fh+var_20], 10h"
p[9] == 0x48 && p[10] == 0x0f && p[11] == 0x43 && // prefix of "cmovnb rcx, [rbp+5Fh+var_38]"
p[14] == 0x48 && p[15] == 0x8d && // prefix of "lea rax, [rbp+5Fh+var_58]"
p[18] == 0x48 && p[19] == 0x83 && // prefix of "cmp [rbp+5Fh+var_40], 10h"
p[23] == 0x48 && p[24] == 0x0f && p[25] == 0x43 && // prefix of "cmovnb rax, [rbp+5Fh+var_58]"
p[28] == 0x44 && p[29] == 0x0f && p[30] == 0xb6 && // prefix of "movzx r8d, byte ptr [rax+rdi]"
p[33] == 0x44 && p[34] == 0x02 && // prefix of "add r8b, [rcx+rdi]"
p[37] == 0xba && // prefix of "mov edx, 1"
p[42] == 0x48 && p[43] == 0x8b && // prefix of "mov rcx, rbx"
p[45] == 0xe8; // prefix of "call sub_1806E65F0"
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
auto RegisterIndex = X86_REG_INVALID;
auto Disassembler = _DisassemblyEngine.CreateDisassembler();
Disassembler.SetContext({ _pbPatchMachineCode, 45, _Image.PointerToVa(_pbPatchMachineCode) });
if (Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (_stricmp(lpInsn->mnemonic, "movzx") == 0 &&
lpInsn->detail->x86.op_count == 2 &&
lpInsn->detail->x86.operands[0].type == X86_OP_REG &&
lpInsn->detail->x86.operands[1].type == X86_OP_MEM &&
lpInsn->detail->x86.operands[1].size == 1 &&
lpInsn->detail->x86.operands[1].mem.scale == 1)
{
RegisterIndex = lpInsn->detail->x86.operands[1].mem.index;
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Unexpected machine code."));
}
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Disassemble failed."));
}
if (Disassembler.Next() && Disassembler.Next() && Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// The previous instruction of "call sub_1806E65F0" should set RCX register.
//
if (_stricmp(lpInsn->mnemonic, "mov") != 0 ||
lpInsn->detail->x86.op_count < 1 ||
lpInsn->detail->x86.operands[0].type != X86_OP_REG ||
lpInsn->detail->x86.operands[0].reg != X86_REG_RCX)
{
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Unexpected machine code."));
}
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Disassemble failed."));
}
for (size_t i = 0; i < _Image.NumberOfSections(); ++i) {
auto lpSectionHeader = _Image.ImageSectionHeader(i);
if (lpSectionHeader->SizeOfRawData > lpSectionHeader->Misc.VirtualSize) {
auto cbReserved =
lpSectionHeader->SizeOfRawData -
lpSectionHeader->Misc.VirtualSize;
if (cbReserved >= 0x188) {
_pbPatchNewPublicKey = _Image.ImageSectionView<uint8_t*>(lpSectionHeader, lpSectionHeader->Misc.VirtualSize);
auto Assembler = _AssemblyEngine.CreateAssembler();
_NewMachineCode = Assembler.GenerateMachineCode(
std::xstring::format(
TEXT(
"lea rax, qword ptr[0x%.16llx];"
"mov r8b, byte ptr[rax + %hs];"
"mov edx, 1;"
),
_Image.PointerToVa(_pbPatchNewPublicKey),
_DisassemblyEngine.GetRegisterName(RegisterIndex)
).explicit_string().c_str(),
_Image.PointerToVa(_pbPatchMachineCode)
);
// >>>>>>>>>>>> .text:00000001819B02C0 48 8D 4D 27 lea rcx, [rbp + 5Fh + var_38]
// .text:00000001819B02C4 48 83 7D 3F 10 cmp[rbp + 5Fh + var_20], 10h
// 42 BYTES .text:00000001819B02C9 48 0F 43 4D 27 cmovnb rcx, [rbp + 5Fh + var_38]
// .text:00000001819B02CE 48 8D 45 07 lea rax, [rbp + 5Fh + var_58]
// THESE CODE .text:00000001819B02D2 48 83 7D 1F 10 cmp[rbp + 5Fh + var_40], 10h
// WILL BE .text:00000001819B02D7 48 0F 43 45 07 cmovnb rax, [rbp + 5Fh + var_58]
// REPLACED .text:00000001819B02DC 44 0F B6 04 38 movzx r8d, byte ptr[rax + rdi]
// .text:00000001819B02E1 44 02 04 39 add r8b, [rcx + rdi]
// <<<<<<<<<<<< .text:00000001819B02E5 BA 01 00 00 00 mov edx, 1
// .text:00000001819B02EA 48 8B CB mov rcx, rbx
// .text:00000001819B02ED E8 FE 62 D3 FE call sub_1806E65F0
while (_NewMachineCode.size() < 42) {
_NewMachineCode.emplace_back(0x90); // padding with "nop"
}
if (_NewMachineCode.size() != 42) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Something unexpected happens."));
}
LOG_SUCCESS(0, "PatchSolution4 ...... Ready to apply");
LOG_HINT(4, "Machine code patch VA = 0x%zx", _Image.PointerToVa(_pbPatchMachineCode));
LOG_HINT(4, "New public key VA = 0x%zx", _Image.PointerToVa(_pbPatchNewPublicKey));
LOG_HINT(4, "New public key offset = 0x%zx", _Image.PointerToFileOffset(_pbPatchNewPublicKey));
return true;
}
}
}
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("No space to store public key."));
} catch (nkg::Exception&) {
_pbPatchMachineCode = nullptr;
_pbPatchNewPublicKey = nullptr;
_NewMachineCode.clear();
LOG_FAILURE(0, "PatchSolution4 ...... Omitted");
return false;
}
}
}
@@ -1,72 +0,0 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution4-generic.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
bool PatchSolution4::CheckKey(const RSACipher& Cipher) const noexcept {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
return szPublicKey.length() == 0x188;
}
void PatchSolution4::MakePatch(const RSACipher& Cipher) const {
if (_pbPatchMachineCode == nullptr || _pbPatchNewPublicKey == nullptr || _NewMachineCode.empty()) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution4 has not been ready yet."));
}
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution4 *"));
_putts(TEXT("*******************************************************"));
LOG_HINT(0, "Previous:");
PrintMemory(_pbPatchMachineCode, _NewMachineCode.size(), _Image.ImageBase());
memcpy(_pbPatchMachineCode, _NewMachineCode.data(), _NewMachineCode.size());
LOG_HINT(0, "After:");
PrintMemory(_pbPatchMachineCode, _NewMachineCode.size(), _Image.ImageBase());
_putts(TEXT(""));
LOG_HINT(0, "Previous:");
PrintMemory(_pbPatchNewPublicKey, szPublicKey.size(), _Image.ImageBase());
memcpy(_pbPatchNewPublicKey, szPublicKey.data(), szPublicKey.size());
LOG_HINT(0, "After:");
PrintMemory(_pbPatchNewPublicKey, szPublicKey.size(), _Image.ImageBase());
_putts(TEXT(""));
}
}
-145
View File
@@ -1,145 +0,0 @@
#include "PatchSolutions.hpp"
#include <xstring.hpp>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution4-i386.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
PatchSolution4::PatchSolution4(const ImageInterpreter& Image) :
_Image(Image),
_DisassemblyEngine(CS_ARCH_X86, CS_MODE_32),
_AssemblyEngine(KS_ARCH_X86, KS_MODE_32),
_pbPatchMachineCode(nullptr),
_pbPatchNewPublicKey(nullptr) { _DisassemblyEngine.Option(CS_OPT_DETAIL, CS_OPT_ON); }
PatchSolution4::PatchSolution4(const ImageInterpreter* Image) :
_Image(*Image),
_DisassemblyEngine(CS_ARCH_X86, CS_MODE_32),
_AssemblyEngine(KS_ARCH_X86, KS_MODE_32),
_pbPatchMachineCode(nullptr),
_pbPatchNewPublicKey(nullptr) { _DisassemblyEngine.Option(CS_OPT_DETAIL, CS_OPT_ON); }
bool PatchSolution4::FindPatchOffset() noexcept {
try {
_pbPatchMachineCode = _Image.SearchSection<uint8_t*>(".text", [](const uint8_t* p) {
__try {
return
p[0] == 0x83 && // prefix of "cmp [ebp+var_30], 10h"
p[4] == 0x8d && // prefix of "lea ecx, [ebp+Dst]"
p[7] == 0x8d && // prefix of "lea eax, [ebp+Memory]"
p[10] == 0x0f && p[11] == 0x43 && // prefix of "cmovnb ecx, [ebp+Dst]"
p[14] == 0x83 && // prefix of "cmp [ebp+var_18], 10h"
p[18] == 0x0f && p[19] == 0x43 && // prefix of "cmovnb eax, [ebp+Memory]"
p[22] == 0x8a && // prefix of "mov dl, [eax+ebx]"
p[25] == 0x02; // prefix of "add dl, [ecx+ebx]"
// p[28]
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
auto RegisterIndex = X86_REG_INVALID;
auto RegisterFinalValue = X86_REG_INVALID;
auto Disassembler = _DisassemblyEngine.CreateDisassembler();
Disassembler.SetContext({ _pbPatchMachineCode, 28, _Image.PointerToVa(_pbPatchMachineCode) });
if (Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next() && Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (_stricmp(lpInsn->mnemonic, "mov") == 0 &&
lpInsn->detail->x86.op_count == 2 &&
lpInsn->detail->x86.operands[0].type == X86_OP_REG &&
lpInsn->detail->x86.operands[1].type == X86_OP_MEM &&
lpInsn->detail->x86.operands[1].size == 1 &&
lpInsn->detail->x86.operands[1].mem.scale == 1)
{
RegisterIndex = lpInsn->detail->x86.operands[1].mem.index;
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Unexpected machine code."));
}
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Disassemble failed."));
}
if (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (_stricmp(lpInsn->mnemonic, "add") == 0 &&
lpInsn->detail->x86.op_count >= 1 &&
lpInsn->detail->x86.operands[0].type == X86_OP_REG &&
lpInsn->detail->x86.operands[0].size == 1)
{
RegisterFinalValue = lpInsn->detail->x86.operands[0].reg;
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Unexpected machine code."));
}
} else {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Disassemble failed."));
}
for (size_t i = 0; i < _Image.NumberOfSections(); ++i) {
auto lpSectionHeader = _Image.ImageSectionHeader(i);
if (lpSectionHeader->SizeOfRawData > lpSectionHeader->Misc.VirtualSize) {
auto cbReserved =
lpSectionHeader->SizeOfRawData -
lpSectionHeader->Misc.VirtualSize;
if (cbReserved >= 0x188) {
_pbPatchNewPublicKey = _Image.ImageSectionView<uint8_t*>(lpSectionHeader, lpSectionHeader->Misc.VirtualSize);
auto Assembler = _AssemblyEngine.CreateAssembler();
_NewMachineCode = Assembler.GenerateMachineCode(
std::xstring::format(
TEXT(
"call +5;"
"pop eax;"
"add eax, 0x%.8x;"
"mov %hs, byte ptr [eax + %hs];"
),
_Image.PointerToVa(_pbPatchNewPublicKey) - (_Image.PointerToVa(_pbPatchMachineCode) + 5),
_DisassemblyEngine.GetRegisterName(RegisterFinalValue),
_DisassemblyEngine.GetRegisterName(RegisterIndex)
).explicit_string().c_str()
);
// >>>>>>>>>>>> .text:113FE4A0 83 7D D0 10 cmp [ebp+var_30], 10h
// 28 BYTES .text:113FE4A4 8D 4D BC lea ecx, [ebp+Dst]
// .text:113FE4A7 8D 45 D4 lea eax, [ebp+Memory]
// THESE CODE .text:113FE4AA 0F 43 4D BC cmovnb ecx, [ebp+Dst]
// WILL BE .text:113FE4AE 83 7D E8 10 cmp [ebp+var_18], 10h
// REPLACED .text:113FE4B2 0F 43 45 D4 cmovnb eax, [ebp+Memory]
// .text:113FE4B6 8A 14 18 mov dl, [eax+ebx]
// <<<<<<<<<<<< .text:113FE4B9 02 14 19 add dl, [ecx+ebx]
while (_NewMachineCode.size() < 28) {
_NewMachineCode.emplace_back(0x90); // padding with "nop"
}
if (_NewMachineCode.size() != 28) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Something unexpected happens."));
}
LOG_SUCCESS(0, "PatchSolution4 ...... Ready to apply");
LOG_HINT(4, "Machine code patch VA = 0x%zx", _Image.PointerToVa(_pbPatchMachineCode));
LOG_HINT(4, "New public key VA = 0x%zx", _Image.PointerToVa(_pbPatchNewPublicKey));
LOG_HINT(4, "New public key offset = 0x%zx", _Image.PointerToFileOffset(_pbPatchNewPublicKey));
return true;
}
}
}
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("No space to store public key."));
} catch (nkg::Exception&) {
_pbPatchMachineCode = nullptr;
_pbPatchNewPublicKey = nullptr;
_NewMachineCode.clear();
LOG_FAILURE(0, "PatchSolution4 ...... Omitted");
return false;
}
}
}
+106 -226
View File
@@ -1,234 +1,114 @@
#pragma once
#include <RSACipher.hpp>
#include "ImageInterpreter.hpp"
#include "../common/Exception.hpp"
#include "../common/ResourceOwned.hpp"
#include "../common/RSACipher.hpp"
#include "ResourceTraitsUnix.hpp"
#include "X64ImageInterpreter.hpp"
#include "CapstoneDisassembler.hpp"
#include "KeystoneAssembler.hpp"
#include "Misc.hpp"
namespace nkg {
class PatchSolution {
protected:
static constexpr size_t InvalidOffset = -1;
public:
[[nodiscard]]
virtual bool FindPatchOffset() noexcept = 0;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept = 0;
virtual void MakePatch(const RSACipher& Cipher) const = 0;
virtual ~PatchSolution() = default;
};
//
// PatchSolution0 will replace the RSA public key stored in navicat.exe
// Print memory data in [from, to) at least
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
class PatchSolution0 final : public PatchSolution {
private:
static const char Keyword[461];
const ImageInterpreter& _Image;
size_t _PatchOffset;
public:
PatchSolution0(const ImageInterpreter& Image) noexcept :
_Image(Image),
_PatchOffset(InvalidOffset) {}
PatchSolution0(const ImageInterpreter* lpImage) noexcept :
_Image(*lpImage),
_PatchOffset(InvalidOffset) {}
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution1 will replace the RSA public key stored in libcc.dll
//
class PatchSolution1 final : public PatchSolution {
private:
static const char Keyword0[160 + 1];
static const char Keyword1[4 + 1];
static const char Keyword2[742 + 1];
static const char Keyword3[4 + 1];
static const char Keyword4[5 + 1];
const ImageInterpreter& _Image;
size_t _PatchOffset[5];
size_t _PatchSize[5];
public:
PatchSolution1(const ImageInterpreter& Image) noexcept :
_Image(Image),
_PatchOffset{ InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset },
_PatchSize{} {}
PatchSolution1(const ImageInterpreter* lpImage) noexcept :
_Image(*lpImage),
_PatchOffset{ InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset },
_PatchSize{} {}
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution2 will replace the RSA public key stored in libcc.dll
//
class PatchSolution2 final : public PatchSolution {
private:
static const char KeywordMeta[0x188 + 1];
static const uint8_t Keyword[0x188][5];
const ImageInterpreter& _Image;
size_t _PatchOffset[0x188];
public:
PatchSolution2(const ImageInterpreter& Image) noexcept :
_Image(Image),
_PatchOffset{}
{
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
}
PatchSolution2(const ImageInterpreter* lpImage) noexcept :
_Image(*lpImage),
_PatchOffset{}
{
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
}
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution3 will replace the RSA public key stored in libcc.dll
//
class PatchSolution3 final : public PatchSolution {
private:
using KeywordValueType = uint8_t[8];
using KeywordSizeType = size_t;
enum KeywordTypeEnum { IMM_DATA, STRING_DATA };
struct KeywordInfo {
KeywordValueType Value;
KeywordSizeType Size;
KeywordTypeEnum Type;
bool NotRecommendedToModify;
};
struct PatchInfo {
uint64_t OpcodeRva;
void* lpOpcode;
void* lpPatch;
size_t cbPatch;
char* lpOriginalString;
char* lpReplaceString;
};
static const KeywordInfo Keyword[111];
const ImageInterpreter& _Image;
CapstoneEngine _Engine;
mutable PatchInfo _Patch[111];
[[nodiscard]]
static bool IsPrintable(const void* p, size_t s) noexcept;
[[nodiscard]]
bool CheckIfMatchPattern(const cs_insn* lpInsn) const noexcept;
[[nodiscard]]
bool CheckIfFound(const cs_insn* lpInsn, size_t KeywordIdx) const noexcept;
[[nodiscard]]
PatchInfo CreatePatchPoint(const void* lpOpcode, const cs_insn* lpInsn, size_t KeywordIdx) const noexcept;
[[nodiscard]]
CapstoneContext GetJumpedBranch(const CapstoneContext& Bifurcation, const cs_insn* lpJxxInsn) const;
[[nodiscard]]
CapstoneContext SelectBranch(const CapstoneContext& NotJumpedBranch, const CapstoneContext& JumpedBranch, size_t KeywordIdx) const;
public:
PatchSolution3(const ImageInterpreter& Image);
PatchSolution3(const ImageInterpreter* lpImage);
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution3 will replace the RSA public key stored in libcc.dll
// For Navicat Data Modeler 3
//
class PatchSolution4 : public PatchSolution {
private:
static const uint8_t KeywordA[0x188];
static const uint8_t KeywordB[0x188];
const ImageInterpreter& _Image;
CapstoneEngine _DisassemblyEngine;
KeystoneEngine _AssemblyEngine;
uint8_t* _pbPatchMachineCode;
uint8_t* _pbPatchNewPublicKey;
std::vector<uint8_t> _NewMachineCode;
public:
PatchSolution4(const ImageInterpreter& Image);
PatchSolution4(const ImageInterpreter* lpImage);
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
void PrintMemory(const void *from, const void *to, const void *base = nullptr);
bool IsResolvedTo(const X64ImageInterpreter& Image, const void* StubHelperProc, const char *Symbol);
}
class PatchSolution {
public:
[[nodiscard]]
virtual bool FindPatchOffset() noexcept = 0;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& RsaCipher) const noexcept = 0;
virtual void MakePatch(const RSACipher& RsaCipher) const = 0;
virtual ~PatchSolution() = default;
};
class PatchSolution0 : public PatchSolution {
private:
static const char Keyword[452];
const X64ImageInterpreter& pvt_Image;
uint32_t pvt_PatchOffset;
public:
explicit
PatchSolution0(const X64ImageInterpreter& Image) noexcept;
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool CheckKey(const RSACipher& RsaCipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& RsaCipher) const override;
};
class PatchSolution1 : public PatchSolution {
private:
static const uint8_t Keyword[0x188];
const X64ImageInterpreter& pvt_Image;
uint32_t pvt_PatchOffset;
public:
explicit
PatchSolution1(const X64ImageInterpreter& Image) noexcept;
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool CheckKey(const RSACipher& RsaCipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& RsaCipher) const override;
};
class PatchSolution2 : public PatchSolution {
private:
static const char Keyword[1114];
static const uint8_t FunctionHeader[9];
const X64ImageInterpreter& pvt_Image;
CapstoneDisassembler pvt_Disassembler;
KeystoneAssembler pvt_Assembler;
uint32_t pvt_FunctionOffset;
uint32_t pvt_KeywordOffset;
uint64_t pvt_StdStringAppendStubRva;
public:
explicit
PatchSolution2(const X64ImageInterpreter& Image) noexcept;
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual bool CheckKey(const RSACipher& RsaCipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& RsaCipher) const override;
};
+8 -3
View File
@@ -1,18 +1,23 @@
#pragma once
#include <capstone/capstone.h>
#include "ExceptionCapstone.hpp"
struct CapstoneHandleTraits {
using HandleType = csh;
static inline const HandleType InvalidValue = NULL;
static inline const HandleType InvalidValue = 0;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(HandleType& Handle) noexcept {
cs_close(&Handle);
static void Releasor(HandleType& Handle) {
auto err = cs_close(&Handle);
if (err != CS_ERR_OK) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::CapstoneError(__FILE__, __LINE__, err, "ks_close failed.");
}
}
};
+7 -2
View File
@@ -1,5 +1,6 @@
#pragma once
#include <keystone/keystone.h>
#include "ExceptionKeystone.hpp"
struct KeystoneHandleTraits {
using HandleType = ks_engine*;
@@ -11,8 +12,12 @@ struct KeystoneHandleTraits {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
ks_close(Handle);
static void Releasor(const HandleType& Handle) {
auto err = ks_close(Handle);
if (err != KS_ERR_OK) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::KeystoneError(__FILE__, __LINE__, err, "ks_close failed.");
}
}
};
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <errno.h> // NOLINT
#include <unistd.h>
#include <sys/mman.h>
#include "../common/ExceptionSystem.hpp"
struct FileHandleTraits {
using HandleType = int;
static inline const HandleType InvalidValue = -1;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) {
if (close(Handle) != 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "close failed.");
}
}
};
struct MapViewTraits {
using HandleType = void*;
static inline const HandleType InvalidValue = MAP_FAILED;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
};
+131
View File
@@ -0,0 +1,131 @@
#include "X64ImageInterpreter.hpp"
[[nodiscard]]
X64ImageInterpreter X64ImageInterpreter::Parse(void* ImageBase) {
X64ImageInterpreter NewImage;
NewImage.pvt_MachHeader = reinterpret_cast<mach_header_64*>(ImageBase);
if (NewImage.pvt_MachHeader->magic != MH_MAGIC_64) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Bad Image");
}
auto cmd_p = reinterpret_cast<load_command*>(NewImage.pvt_MachHeader + 1);
for (uint32_t i = 0; i < NewImage.pvt_MachHeader->ncmds; ++i) {
switch (cmd_p->cmd) {
case LC_SEGMENT_64: {
auto segcmd_p = reinterpret_cast<segment_command_64*>(cmd_p);
auto section_p = reinterpret_cast<section_64*>(segcmd_p + 1);
NewImage.pvt_SegmentCommands.emplace_back(segcmd_p);
for (uint32_t j = 0; j < segcmd_p->nsects; ++j) {
NewImage.pvt_Sections.ByIndex[NewImage.pvt_Sections.ByIndex.size()] = &section_p[j];
NewImage.pvt_Sections.ByMapAddress[section_p[j].addr] = &section_p[j];
NewImage.pvt_Sections.ByFileOffset[section_p[j].offset] = &section_p[j];
}
break;
}
case LC_DYSYMTAB: {
NewImage.pvt_DynamicSymbol.SegmentCommand = reinterpret_cast<dysymtab_command*>(cmd_p);
break;
}
case LC_SYMTAB: {
NewImage.pvt_Symbol.SegmentCommand = reinterpret_cast<symtab_command*>(cmd_p);
NewImage.pvt_Symbol.StringTable = NewImage.ImageOffset<char*>(NewImage.pvt_Symbol.SegmentCommand->stroff);
NewImage.pvt_Symbol.SymbolTable = NewImage.ImageOffset<nlist_64*>(NewImage.pvt_Symbol.SegmentCommand->symoff);
break;
}
case LC_DYLD_INFO_ONLY: { // NOLINT
NewImage.pvt_DynamicLoaderInfoOnly.SegmentCommand = reinterpret_cast<dyld_info_command*>(cmd_p);
}
default:
break;
}
cmd_p = reinterpret_cast<load_command*>(
reinterpret_cast<uint8_t*>(cmd_p) + cmd_p->cmdsize
);
}
return NewImage;
}
[[nodiscard]]
size_t X64ImageInterpreter::NumberOfSections() const noexcept {
return pvt_Sections.ByIndex.size();
}
[[nodiscard]]
section_64* X64ImageInterpreter::ImageSection(size_t Index) const {
auto it = pvt_Sections.ByIndex.find(Index);
if (it != pvt_Sections.ByIndex.cend()) {
return it->second;
} else {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Section is not found.");
}
}
[[nodiscard]]
section_64* X64ImageInterpreter::ImageSection(const char* SegmentName, const char* SectionName) const {
for (auto segcmd_p : pvt_SegmentCommands) {
if (strncmp(SegmentName, segcmd_p->segname, sizeof(segcmd_p->segname)) == 0) {
auto sec_p = reinterpret_cast<section_64*>(segcmd_p + 1);
for (uint32_t i = 0; i < segcmd_p->nsects; ++i) {
if (strncmp(SectionName, sec_p[i].sectname, sizeof(sec_p[i].sectname)) == 0)
return &sec_p[i];
}
break;
}
}
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Section is not found.");
}
[[nodiscard]]
section_64* X64ImageInterpreter::ImageSectionByOffset(uint32_t Offset) const {
for (const auto& it : pvt_Sections.ByFileOffset) {
if (it.first <= Offset && Offset < it.first + it.second->size) {
return it.second;
}
}
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Section is not found.");
}
[[nodiscard]]
section_64* X64ImageInterpreter::ImageSectionByRva(uint64_t Rva) const {
for (const auto& it : pvt_Sections.ByMapAddress) {
if (it.first <= Rva && Rva < it.first + it.second->size) {
return it.second;
}
}
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Section is not found.");
}
[[nodiscard]]
uint64_t X64ImageInterpreter::OffsetToRva(uint32_t Offset) const {
auto section = ImageSectionByOffset(Offset);
return section->addr + (Offset - section->offset);
}
[[nodiscard]]
uint32_t X64ImageInterpreter::RvaToOffset(uint64_t Rva) const {
auto section = ImageSectionByRva(Rva);
return section->offset + (Rva - section->addr);
}
[[nodiscard]]
nlist_64* X64ImageInterpreter::ImageSymbolTable() const noexcept {
return pvt_Symbol.SymbolTable;
}
+199
View File
@@ -0,0 +1,199 @@
#pragma once
#include <string.h> // NOLINT
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <vector>
#include <map>
#include "../common/Exception.hpp"
class X64ImageInterpreter {
public:
static constexpr uint64_t InvalidAddress = static_cast<uint64_t>(-1);
static constexpr uint32_t InvalidOffset = static_cast<uint32_t>(-1);
private:
mach_header_64* pvt_MachHeader;
std::vector<segment_command_64*> pvt_SegmentCommands;
struct {
std::map<size_t, section_64*> ByIndex;
std::map<uint64_t, section_64*> ByMapAddress;
std::map<uint32_t, section_64*> ByFileOffset;
} pvt_Sections;
struct {
dysymtab_command* SegmentCommand;
} pvt_DynamicSymbol;
struct {
symtab_command* SegmentCommand;
char* StringTable;
nlist_64* SymbolTable;
} pvt_Symbol;
struct {
dyld_info_command* SegmentCommand;
} pvt_DynamicLoaderInfoOnly;
X64ImageInterpreter() :
pvt_MachHeader(nullptr),
pvt_DynamicSymbol{},
pvt_Symbol{},
pvt_DynamicLoaderInfoOnly{} {}
public:
[[nodiscard]]
static X64ImageInterpreter Parse(void* ImageBase);
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageBase() const noexcept {
static_assert(std::is_pointer_v<__ReturnType>);
return reinterpret_cast<__ReturnType>(pvt_MachHeader);
}
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageOffset(size_t Offset) const noexcept {
static_assert(std::is_pointer_v<__ReturnType>);
return reinterpret_cast<__ReturnType>(
reinterpret_cast<uint8_t*>(pvt_MachHeader) + Offset
);
}
template<unsigned __CommandMacro>
[[nodiscard]]
auto CommandOf() const noexcept {
if constexpr (__CommandMacro == LC_DYSYMTAB) {
return pvt_DynamicSymbol.SegmentCommand;
} else if constexpr (__CommandMacro == LC_SYMTAB) {
return pvt_Symbol.SegmentCommand;
} else if constexpr (__CommandMacro == LC_DYLD_INFO_ONLY) { // NOLINT
return pvt_DynamicLoaderInfoOnly.SegmentCommand;
} else {
return nullptr;
}
}
[[nodiscard]]
size_t NumberOfSections() const noexcept;
[[nodiscard]]
section_64* ImageSection(size_t Index) const;
[[nodiscard]]
section_64* ImageSection(const char* SegmentName, const char* SectionName) const;
[[nodiscard]]
section_64* ImageSectionByOffset(uint32_t Offset) const;
[[nodiscard]]
section_64* ImageSectionByRva(uint64_t Rva) const;
template<typename __ReturnType>
[[nodiscard]]
__ReturnType SectionView(size_t Index) const {
auto Section = ImageSection(Index);
return ImageOffset<__ReturnType>(Section->offset);
}
template<typename __ReturnType>
[[nodiscard]]
__ReturnType SectionView(const char* SegmentName, const char* SectionName) const {
auto Section = ImageSection(SegmentName, SectionName);
return ImageOffset<__ReturnType>(Section->offset);
}
template<typename __ReturnType>
[[nodiscard]]
__ReturnType SectionView(section_64* Section) const {
return ImageOffset<__ReturnType>(Section->offset);
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(size_t Index, __Hint&& Hint) const {
return SearchSection<__ReturnType>(ImageSection(Index), std::forward<__Hint>(Hint));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(const char* SegmentName, const char* SectionName, __Hint&& Hint) const {
return SearchSection<__ReturnType>(ImageSection(SegmentName, SectionName), std::forward<__Hint>(Hint));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(section_64* Section, __Hint&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto begin = SectionView<const uint8_t*>(Section);
auto end = begin + Section->size;
for (; begin < end; ++begin) {
if (Hint(begin) == true) {
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(begin));
}
}
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Data is not found.");
}
template<typename __Hint>
[[nodiscard]]
uint32_t SearchSectionOffset(size_t Index, __Hint&& Hint) const {
return SearchSection<uint8_t*>(Index, std::forward<__Hint>(Hint)) - ImageBase<uint8_t*>();
}
template<typename __Hint>
[[nodiscard]]
uint32_t SearchSectionOffset(const char* SegmentName, const char* SectionName, __Hint&& Hint) const {
return SearchSection<uint8_t*>(SegmentName, SectionName, std::forward<__Hint>(Hint)) - ImageBase<uint8_t*>();
}
template<typename __Hint>
[[nodiscard]]
uint32_t SearchSectionOffset(section_64* Section, __Hint&& Hint) const {
return SearchSection<uint8_t*>(Section, std::forward<__Hint>(Hint)) - ImageBase<uint8_t*>();
}
template<typename __Hint>
[[nodiscard]]
uint64_t SearchSectionRva(size_t Index, __Hint&& Hint) const {
auto Section = ImageSection(Index);
auto Offset = SearchSection<uint8_t*>(Section, std::forward<__Hint>(Hint)) - SectionView<uint8_t*>(Section);
return Section->addr + Offset;
}
template<typename __Hint>
[[nodiscard]]
uint64_t SearchSectionRva(const char* SegmentName, const char* SectionName, __Hint&& Hint) const {
auto Section = ImageSection(SegmentName, SectionName);
auto Offset = SearchSection<uint8_t*>(Section, std::forward<__Hint>(Hint)) - SectionView<uint8_t*>(Section);
return Section->addr + Offset;
}
template<typename __Hint>
[[nodiscard]]
uint64_t SearchSectionRva(section_64* Section, __Hint&& Hint) const {
auto Offset = SearchSection<uint8_t*>(Section, std::forward<__Hint>(Hint)) - SectionView<uint8_t*>(Section);
return Section->addr + Offset;
}
[[nodiscard]]
uint64_t OffsetToRva(uint32_t Offset) const;
[[nodiscard]]
uint32_t RvaToOffset(uint64_t Address) const;
[[nodiscard]]
nlist_64* ImageSymbolTable() const noexcept;
[[nodiscard]]
char* LookupStringTable(size_t Offset) const noexcept {
return pvt_Symbol.StringTable + Offset;
}
};
-459
View File
@@ -1,459 +0,0 @@
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <Exception.hpp>
#include <ExceptionWin32.hpp>
#include <ResourceOwned.hpp>
#include <ResourceTraitsWin32.hpp>
#include "ImageInterpreter.hpp"
#include "PatchSolutions.hpp"
#include "Misc.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\_tmain.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
static void Welcome() {
_putts(TEXT("***************************************************"));
_putts(TEXT("* Navicat Patcher by @DoubleLabyrinth *"));
_putts(TEXT("* Version: 4.1 *"));
_putts(TEXT("***************************************************"));
_putts(TEXT(""));
_putts(TEXT("Press Enter to continue or Ctrl + C to abort."));
auto c = _gettchar();
while (c != TEXT('\n') && _gettchar() != TEXT('\n')) {}
}
static void Help() {
_putts(TEXT("***************************************************"));
_putts(TEXT("* Navicat Patcher by @DoubleLabyrinth *"));
_putts(TEXT("* Version: 4.1 *"));
_putts(TEXT("***************************************************"));
_putts(TEXT(""));
_putts(TEXT("Usage:"));
_putts(TEXT(" navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]"));
_putts(TEXT(""));
_putts(TEXT(" [-dry-run] Run patcher without applying any patches."));
_putts(TEXT(" This parameter is optional."));
_putts(TEXT(""));
_putts(TEXT(" <Navicat Installation Path> The folder path where Navicat is installed."));
_putts(TEXT(" This parameter must be specified."));
_putts(TEXT(""));
_putts(TEXT(" [RSA-2048 PEM File Path] The path to an RSA-2048 private key file."));
_putts(TEXT(" This parameter is optional."));
_putts(TEXT(" If not specified, an RSA-2048 private key file"));
_putts(TEXT(" named \"RegPrivateKey.pem\" will be generated."));
_putts(TEXT(""));
_putts(TEXT("Example:"));
_putts(TEXT(" navicat-patcher.exe \"C:\\Program Files\\PremiumSoft\\Navicat Premium 12\""));
}
static bool ParseCommandLine(int argc, PTSTR argv[], bool& bDryRun, std::xstring& NavInstallPath, std::xstring& RsaPrivateKeyPath) {
if (argc == 2) {
bDryRun = false;
NavInstallPath = argv[1];
RsaPrivateKeyPath.clear();
return true;
} else if (argc == 3) {
if (_tcsicmp(argv[1], TEXT("-dry-run")) == 0) {
bDryRun = true;
NavInstallPath = argv[2];
RsaPrivateKeyPath.clear();
return true;
} else {
bDryRun = false;
NavInstallPath = argv[1];
RsaPrivateKeyPath = argv[2];
return true;
}
} else if (argc == 4) {
if (_tcsicmp(argv[1], TEXT("-dry-run")) == 0) {
bDryRun = true;
NavInstallPath = argv[2];
RsaPrivateKeyPath = argv[3];
return true;
} else {
return false;
}
} else {
return false;
}
}
static void SelectPatchSolutions(
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution0,
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution1,
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution2,
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution3)
{
// if RSA public is detected in libcc.dll, don't patch main application to keep digital signature valid.
if ((lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) && lpSolution0.IsValid()) {
LOG_HINT(0, "PatchSolution0 is suppressed in order to keep digital signature valid.");
lpSolution0.Release();
}
}
static void NavicatBackupDetect(const std::xstring& FilePath) {
if (std::xstring BackupPath = FilePath + TEXT(".backup"); nkg::IsValidFilePath(BackupPath.c_str()) == true) {
while (true) {
LOG_SELECT(0, "Previous backup %s detected. Delete? (y/n)", BackupPath.c_str());
auto select = _gettchar();
while (select != TEXT('\n') && _gettchar() != TEXT('\n')) {}
if (select == TEXT('Y') || select == TEXT('y')) {
if (!DeleteFile(BackupPath.c_str())) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to delete backup file."));
} else {
break;
}
} else if (select == TEXT('N') || select == TEXT('n')) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Backup file still existed. Patch abort!"));
} else {
continue;
}
}
_putts(TEXT(""));
}
}
static void NavicatBackupMake(const std::xstring& FilePath) {
std::xstring BackupPath = FilePath + TEXT(".backup");
if (CopyFile(FilePath.c_str(), BackupPath.c_str(), TRUE) == FALSE) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CopyFile failed."));
}
}
static void LoadKey(
nkg::RSACipher& Cipher, const std::xstring& KeyFilePath,
nkg::PatchSolution* pSolution0,
nkg::PatchSolution* pSolution1,
nkg::PatchSolution* pSolution2,
nkg::PatchSolution* pSolution3,
nkg::PatchSolution* pSolution4)
{
if (KeyFilePath.empty() == false) {
LOG_HINT(0, "Import RSA-2048 key from %s", KeyFilePath.c_str());
Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(KeyFilePath);
if (pSolution0 && !pSolution0->CheckKey(Cipher) ||
pSolution1 && !pSolution1->CheckKey(Cipher) ||
pSolution2 && !pSolution2->CheckKey(Cipher) ||
pSolution3 && !pSolution3->CheckKey(Cipher) ||
pSolution4 && !pSolution4->CheckKey(Cipher))
{
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("The RSA private key you provide cannot be used."));
}
} else {
LOG_HINT(0, "Generating new RSA private key, it may take a long time...");
do {
Cipher.GenerateKey(2048);
} while (pSolution0 && !pSolution0->CheckKey(Cipher) ||
pSolution1 && !pSolution1->CheckKey(Cipher) ||
pSolution2 && !pSolution2->CheckKey(Cipher) ||
pSolution3 && !pSolution3->CheckKey(Cipher) ||
pSolution4 && !pSolution4->CheckKey(Cipher)); // re-generate RSA key if one of 'CheckKey's return false
}
LOG_HINT(0, "Your RSA public key:\n%hs", Cipher.ExportKeyString<nkg::RSAKeyType::PublicKey, nkg::RSAKeyFormat::PEM>().c_str());
}
int _tmain(int argc, PTSTR argv[]) {
bool bDryRun;
std::xstring NavInstallPath;
std::xstring RsaPrivateKeyPath;
if (ParseCommandLine(argc, argv, bDryRun, NavInstallPath, RsaPrivateKeyPath) == false) {
Help();
return -1;
} else {
Welcome();
try {
if (nkg::IsValidDirectoryPath(NavInstallPath.c_str()) == false) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Navicat installation path doesn't point to a directory."))
.AddHint(TEXT("Are you sure the path you specified is correct?"))
.AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
}
if (RsaPrivateKeyPath.empty() == false && nkg::IsValidFilePath(RsaPrivateKeyPath.c_str()) == false) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA key file path doesn't point to a file."))
.AddHint(TEXT("Are you sure the path you specified is correct?"))
.AddHint(std::xstring::format(TEXT("The path you specified: %s"), RsaPrivateKeyPath.c_str()));
}
while (NavInstallPath.back() == TEXT('\\') || NavInstallPath.back() == TEXT('/')) {
NavInstallPath.pop_back();
}
NavInstallPath.push_back(nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\'));
nkg::RSACipher Cipher;
std::xstring MainExePath;
ResourceOwned hMainExe(FileHandleTraits{});
ResourceOwned hMainExeMapping(GenericHandleTraits{});
ResourceOwned lpMainExeMapping(MapViewHandleTraits{});
ResourceOwned lpMainExeInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
std::xstring LibccDllPath;
ResourceOwned hLibccDll(FileHandleTraits{});
ResourceOwned hLibccDllMapping(GenericHandleTraits{});
ResourceOwned lpLibccDllMapping(MapViewHandleTraits{});
ResourceOwned lpLibccDllInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
ResourceOwned lpSolution0(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution1(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution2(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution3(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution4(CppObjectTraits<nkg::PatchSolution>{});
//
// Open main application
//
do {
MainExePath = NavInstallPath + TEXT("Navicat.exe");
hMainExe.TakeOver(
CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hMainExe.IsValid()) {
LOG_SUCCESS(0, "Try to open Navicat.exe ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open Navicat.exe ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Navicat.exe"));
}
MainExePath = NavInstallPath + TEXT("Modeler.exe");
hMainExe.TakeOver(
CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hMainExe.IsValid()) {
LOG_SUCCESS(0, "Try to open Modeler.exe ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open Modeler.exe ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Modeler.exe"));
}
MainExePath = NavInstallPath + TEXT("Rviewer.exe");
hMainExe.TakeOver(
CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hMainExe.IsValid()) {
LOG_SUCCESS(0, "Try to open Rviewer.exe ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open Rviewer.exe ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Rviewer.exe"));
}
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Main application is not found."))
.AddHint(TEXT("Are you sure you specified a valid Navicat installation path?"))
.AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
} while (false);
//
// Open libcc.dll, if have
//
do {
LibccDllPath = NavInstallPath + TEXT("libcc.dll");
hLibccDll.TakeOver(
CreateFile(LibccDllPath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hLibccDll.IsValid()) {
LOG_SUCCESS(0, "Try to open libcc.dll ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open libcc.dll ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open libcc.dll"));
}
} while (false);
_putts(TEXT(""));
//
// Map main application
//
hMainExeMapping.TakeOver(CreateFileMapping(hMainExe, NULL, PAGE_READWRITE, 0, 0, NULL));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
}
lpMainExeMapping.TakeOver(MapViewOfFile(hMainExeMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
}
lpMainExeInterpreter.TakeOver(
new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpMainExeMapping))
);
lpSolution0.TakeOver(new nkg::PatchSolution0(lpMainExeInterpreter));
//
// Map libcc.dll, if have
//
if (hLibccDll.IsValid()) {
hLibccDllMapping.TakeOver(CreateFileMapping(hLibccDll, NULL, PAGE_READWRITE, 0, 0, NULL));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
}
lpLibccDllMapping.TakeOver(MapViewOfFile(hLibccDllMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
}
lpLibccDllInterpreter.TakeOver(
new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpLibccDllMapping))
);
lpSolution1.TakeOver(new nkg::PatchSolution1(lpLibccDllInterpreter));
lpSolution2.TakeOver(new nkg::PatchSolution2(lpLibccDllInterpreter));
lpSolution3.TakeOver(new nkg::PatchSolution3(lpLibccDllInterpreter));
lpSolution4.TakeOver(new nkg::PatchSolution4(lpLibccDllInterpreter));
}
//
// Finding patch offsets
//
if (lpSolution0->FindPatchOffset() == false) {
lpSolution0.Release();
}
if (lpSolution1.IsValid() && lpSolution1->FindPatchOffset() == false) {
lpSolution1.Release();
}
if (lpSolution2.IsValid() && lpSolution2->FindPatchOffset() == false) {
lpSolution2.Release();
}
if (lpSolution3.IsValid() && lpSolution3->FindPatchOffset() == false) {
lpSolution3.Release();
}
if (lpSolution4.IsValid() && lpSolution4->FindPatchOffset() == false) {
lpSolution4.Release();
}
_putts(TEXT(""));
//
// decide which solutions will be applied
//
SelectPatchSolutions(lpSolution0, lpSolution1, lpSolution2, lpSolution3);
if (lpSolution0.IsValid() == false && lpSolution1.IsValid() == false && lpSolution2.IsValid() == false && lpSolution3.IsValid() == false && lpSolution4.IsValid() == false) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("No patch applied. Patch abort!"))
.AddHint(TEXT("Are you sure your Navicat has not been patched/modified before?"));
}
_putts(TEXT(""));
//
// detecting backups
//
if (lpSolution0.IsValid()) {
NavicatBackupDetect(MainExePath);
}
if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid() || lpSolution4.IsValid()) {
NavicatBackupDetect(LibccDllPath);
}
//
// Loading key
//
LoadKey(Cipher, RsaPrivateKeyPath, lpSolution0, lpSolution1, lpSolution2, lpSolution3, lpSolution4);
if (bDryRun == false) {
//
// Saving private key if not given
//
if (RsaPrivateKeyPath.empty()) {
Cipher.ExportKeyToFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(std::xstring{ std::xstring_extension{}, "RegPrivateKey.pem" });
}
//
// Making backups
//
if (lpSolution0.IsValid()) {
NavicatBackupMake(MainExePath);
}
if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid() || lpSolution4.IsValid()) {
NavicatBackupMake(LibccDllPath);
}
//
// Making patch. No way to go back here :-)
//
if (lpSolution0.IsValid()) {
lpSolution0->MakePatch(Cipher);
}
if (lpSolution1.IsValid()) {
lpSolution1->MakePatch(Cipher);
}
if (lpSolution2.IsValid()) {
lpSolution2->MakePatch(Cipher);
}
if (lpSolution3.IsValid()) {
lpSolution3->MakePatch(Cipher);
}
if (lpSolution4.IsValid()) {
lpSolution4->MakePatch(Cipher);
}
if (RsaPrivateKeyPath.empty()) {
LOG_HINT(
0,
"New RSA-2048 private key has been saved to\n%s%cRegPrivateKey.pem",
nkg::GetCurrentWorkingDirectory().c_str(),
nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\')
);
_putts(TEXT(""));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PATCH HAS BEEN DONE SUCCESSFULLY! *"));
_putts(TEXT("* HAVE FUN AND ENJOY~ *"));
_putts(TEXT("*******************************************************"));
} else {
_putts(TEXT("*******************************************************"));
_putts(TEXT("* DRY-RUN MODE ENABLE! *"));
_putts(TEXT("* NO PATCH WILL BE APPLIED! *"));
_putts(TEXT("*******************************************************"));
}
return 0;
} catch (nkg::Exception& e) {
LOG_FAILURE(0, "%s:%zu ->", e.File(), e.Line());
LOG_FAILURE(4, "%s", e.Message());
if (e.HasErrorCode()) {
LOG_HINT(4, "%s (0x%zx)", e.ErrorString(), e.ErrorCode());
}
for (auto& Hint : e.Hints()) {
LOG_HINT(4, "Hint: %s", Hint.c_str());
}
return -1;
}
}
}
+259
View File
@@ -0,0 +1,259 @@
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <plist/plist++.h>
#include <string>
#include "../common/ExceptionSystem.hpp"
#include "../common/ResourceOwned.hpp"
#include "ResourceTraitsUnix.hpp"
#include "PatchSolutions.hpp"
static void Welcome() {
puts("***************************************************");
puts("* Navicat Patcher by @DoubleLabyrinth *");
puts("* Version: 4.0 *");
puts("***************************************************");
puts("");
puts("Press Enter to continue or Ctrl + C to abort.");
getchar();
}
static void Help() {
puts("***************************************************");
puts("* Navicat Patcher by @DoubleLabyrinth *");
puts("* Version: 4.0 *");
puts("***************************************************");
puts("");
puts("Usage:");
puts(" navicat-patcher <Navicat installation path> [RSA-2048 Private Key File]");
puts("");
puts(" <Navicat installation path> Path to `Navicat Premium.app`.");
puts(" Example:");
puts(" /Applications/Navicat\\ Premium.app/");
puts(" This parameter must be specified.");
puts("");
puts(" [RSA-2048 Private Key File] Path to a PEM-format RSA-2048 private key file.");
puts(" This parameter is optional.");
puts("");
}
static std::string GetNavicatVersion(const char* AppPath) {
ResourceOwned hInfoPlist(FileHandleTraits{});
ResourceOwned InfoPlist(CppObjectTraits<PList::Dictionary>{});
hInfoPlist.TakeOver(open((std::string(AppPath) + "/Contents/Info.plist").c_str(), O_RDONLY));
if (hInfoPlist.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "Failed to open Contents/Info.plist.");
}
struct stat statInfoPlist = {};
if (fstat(hInfoPlist, &statInfoPlist) != 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "Failed to get file size of Contents/Info.plist.");
}
std::string contentInfoPlist(statInfoPlist.st_size, '\x00');
if (read(hInfoPlist, contentInfoPlist.data(), contentInfoPlist.size()) != contentInfoPlist.size()) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "Failed to read Contents/Info.plist.");
}
InfoPlist.TakeOver(dynamic_cast<PList::Dictionary*>(PList::Structure::FromXml(contentInfoPlist)));
if (InfoPlist.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Failed to parse Contents/Info.plist.");
}
auto kv = InfoPlist->Find("CFBundleShortVersionString");
if (kv == InfoPlist->End()) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Cannot find CFBundleShortVersionString in Contents/Info.plist.");
}
if (kv->second->GetType() == PLIST_STRING) {
return dynamic_cast<PList::String*>(kv->second)->GetValue();
} else {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "Failed to get Navicat version.");
}
}
static void LoadKey(RSACipher& RsaCipher, const char* RsaKeyFileName,
PatchSolution* lpSolution0,
PatchSolution* lpSolution1,
PatchSolution* lpSolution2) {
if (RsaKeyFileName) {
RsaCipher.ImportKeyFromFile<RSAKeyType::PrivateKey, RSAKeyFormat::PEM>(RsaKeyFileName);
if ((lpSolution0 && !lpSolution0->CheckKey(RsaCipher)) ||
(lpSolution1 && !lpSolution1->CheckKey(RsaCipher)) ||
(lpSolution2 && !lpSolution2->CheckKey(RsaCipher)))
{
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::Exception(__FILE__, __LINE__, "The RSA private key you provide cannot be used.");
}
} else {
puts("");
puts("[*] Generating new RSA private key, it may take a long time...");
do {
RsaCipher.GenerateKey(2048);
} while ((lpSolution0 && !lpSolution0->CheckKey(RsaCipher)) ||
(lpSolution1 && !lpSolution1->CheckKey(RsaCipher)) ||
(lpSolution2 && !lpSolution2->CheckKey(RsaCipher))); // re-generate RSA key if CheckKey return false
RsaCipher.ExportKeyToFile<RSAKeyType::PrivateKey, RSAKeyFormat::PEM>("RegPrivateKey.pem");
puts("[+] New RSA private key has been saved to RegPrivateKey.pem.");
}
std::string PublicKeyPEM = RsaCipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
puts("");
puts("[*] Your RSA public key:");
puts(PublicKeyPEM.c_str());
}
int main(int argc, char* argv[]) {
if (argc != 2 && argc != 3) {
Help();
return -1;
} else {
Welcome();
try {
RSACipher RsaCipher;
ResourceOwned Solution0(CppObjectTraits<PatchSolution>{});
ResourceOwned Solution1(CppObjectTraits<PatchSolution>{});
ResourceOwned Solution2(CppObjectTraits<PatchSolution>{});
ResourceOwned hMainApp(FileHandleTraits{}, open((std::string(argv[1]) + "/Contents/MacOS/Navicat Premium").c_str(), O_RDWR));
if (hMainApp.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "open failed.");
}
struct stat statMainApp = {};
if (fstat(hMainApp, &statMainApp) != 0) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "fstat failed.");
}
ResourceOwned lpMainApp(MapViewTraits{},
mmap(nullptr, static_cast<size_t>(statMainApp.st_size), PROT_READ | PROT_WRITE, MAP_SHARED, hMainApp, 0),
[&statMainApp](void* p) { munmap(p, statMainApp.st_size); }
);
if (lpMainApp.IsValid() == false) {
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "mmap failed.");
}
int Ver0, Ver1, Ver2;
if (sscanf(GetNavicatVersion(argv[1]).c_str(), "%d.%d.%d", &Ver0, &Ver1, &Ver2) != 3) { // NOLINT
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "Failed to get version of Navicat.");
}
X64ImageInterpreter MainApp = X64ImageInterpreter::Parse(lpMainApp);
printf("[*] Your Navicat version: %d.%d.%d\n", Ver0, Ver1, Ver2);
printf("\n");
Solution0.TakeOver(new PatchSolution0(MainApp));
Solution1.TakeOver(new PatchSolution1(MainApp));
Solution2.TakeOver(new PatchSolution2(MainApp));
if (Solution0->FindPatchOffset() == false) {
Solution0.Release();
}
if (Solution1->FindPatchOffset() == false) {
Solution1.Release();
}
if (Solution2->FindPatchOffset() == false) {
Solution2.Release();
}
//
// Begin strategies by different Navicat versions
//
if (Ver0 < 12) { // ver < 12.0.0
// NOLINTNEXTLINE: allow exceptions that is not derived from std::exception
throw nkg::SystemError(__FILE__, __LINE__, errno, "Unsupported version of Navicat.");
} else if (Ver0 == 12 && Ver1 == 0 && Ver2 < 24) { // ver < 12.0.24
std::string path(argv[1]);
while(path.back() == '/') {
path.pop_back();
}
printf("[*] Your Navicat version is < 12.0.24. So there would be nothing patched.\n");
printf(" Just use `openssl` to generate `RegPrivateKey.pem` and `rpk` file:\n");
printf(" openssl genrsa -out RegPrivateKey.pem 2048\n");
printf(" openssl rsa -in RegPrivateKey.pem -pubout -out rpk\n");
printf(" and replace `%s/Contents/Resources/rpk` with the `rpk` file you just generated.\n", path.c_str());
printf("\n");
return 0;
} else if (Ver0 == 12 && (Ver1 == 0 || (Ver1 == 1 && Ver2 < 14))) { // 12.0.24 <= ver && ver < 12.1.14
// In this case, Solution0 must be applied
if (Solution0.IsValid() == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched before?");
return -1;
}
} else if (Ver0 == 12 && Ver1 == 1 && Ver2 == 14) { // ver == 12.1.14
// In this case, Solution0 and Solution1 must be applied
if ((Solution0.IsValid() && Solution1.IsValid()) == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched before?");
return -1;
}
} else { // ver > 12.1.14
// In this case, Solution0 and Solution2 must be applied
if ((Solution0.IsValid() && Solution2.IsValid()) == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched before?");
return -1;
}
}
//
// End strategies by different Navicat versions
//
LoadKey(RsaCipher, argc == 3 ? argv[2] : nullptr, Solution0, Solution1, Solution2);
if (Solution0.IsValid()) {
Solution0->MakePatch(RsaCipher);
}
if (Solution1.IsValid()) {
Solution1->MakePatch(RsaCipher);
}
if (Solution2.IsValid()) {
Solution2->MakePatch(RsaCipher);
}
if (Solution0.IsValid())
puts("[+] PatchSolution0 has been applied.");
if (Solution1.IsValid())
puts("[+] PatchSolution1 has been applied.");
if (Solution2.IsValid())
puts("[+] PatchSolution2 has been applied.");
puts("");
puts("**************************************************************");
puts("* Patch has been done successfully. Have fun and enjoy~~ *");
puts("* DO NOT FORGET TO SIGN NAVICAT BY YOUR CERTIFICATE!!! *");
puts("**************************************************************");
return 0;
} catch (nkg::Exception& e) {
printf("[-] %s:%zu -> \n", e.File(), e.Line());
printf(" %s\n", e.Message());
if (e.HasErrorCode()) {
printf(" %s\n", e.ErrorString());
}
return -1;
}
}
}
-219
View File
@@ -1,219 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>navicatpatcher</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<VcpkgTriplet Condition="'$(Platform)'=='Win32'">x86-windows-static</VcpkgTriplet>
<VcpkgTriplet Condition="'$(Platform)'=='x64'">x64-windows-static</VcpkgTriplet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
<Import Project="..\common\common.vcxitems" Label="Shared" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CapstoneDisassembler.cpp" />
<ClCompile Include="ImageInterpreter.cpp" />
<ClCompile Include="KeystoneAssembler.cpp" />
<ClCompile Include="Misc.cpp" />
<ClCompile Include="PatchSolution0.cpp" />
<ClCompile Include="PatchSolution1.cpp" />
<ClCompile Include="PatchSolution2-generic.cpp" />
<ClCompile Include="PatchSolution2-i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution2-amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution3-amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution3-generic.cpp" />
<ClCompile Include="PatchSolution3-i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution4-amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution4-generic.cpp" />
<ClCompile Include="PatchSolution4-i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="_tmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="CapstoneDisassembler.hpp" />
<ClInclude Include="ExceptionCapstone.hpp" />
<ClInclude Include="ExceptionKeystone.hpp" />
<ClInclude Include="ImageInterpreter.hpp" />
<ClInclude Include="KeystoneAssembler.hpp" />
<ClInclude Include="Misc.hpp" />
<ClInclude Include="NavicatCrypto.hpp" />
<ClInclude Include="PatchSolutions.hpp" />
<ClInclude Include="ResourceTraitsCapstone.hpp" />
<ClInclude Include="ResourceTraitsKeystone.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
@@ -1,99 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="_tmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ImageInterpreter.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution0.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution1.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution2-i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution2-amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution3-amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution3-i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Misc.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution2-generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution3-generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CapstoneDisassembler.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution4-generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution4-amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="KeystoneAssembler.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution4-i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="NavicatCrypto.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ImageInterpreter.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="CapstoneDisassembler.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ResourceTraitsCapstone.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ExceptionCapstone.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="PatchSolutions.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Misc.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="KeystoneAssembler.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ExceptionKeystone.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ResourceTraitsKeystone.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
</Project>