Compare commits

..

No commits in common. "windows" and "mac" have entirely different histories.
windows ... mac

108 changed files with 5573 additions and 7281 deletions

View File

@ -1,68 +0,0 @@
name: navicat-keygen builds
on: workflow_dispatch
jobs:
navicat-keygen-x86:
runs-on: windows-latest
steps:
- name: Install dependencies
shell: pwsh
run: |
pushd .
cd ${env:VCPKG_INSTALLATION_ROOT}
git pull
vcpkg install openssl:x86-windows-static
vcpkg install unicorn:x86-windows-static
vcpkg install fmt:x86-windows-static
vcpkg install rapidjson:x86-windows-static
vcpkg install keystone:x86-windows-static
popd
- name: Clone source
uses: actions/checkout@v2
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: Build project
run: |
vcpkg integrate install
msbuild navicat-keygen.sln /p:Configuration=Release /p:Platform=x86
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: navicat-keygen-x86.zip
path: bin/x86-Release/*.exe
navicat-keygen-x64:
runs-on: windows-latest
steps:
- name: Install dependencies
run: |
pushd .
cd ${env:VCPKG_INSTALLATION_ROOT}
git pull
vcpkg install openssl:x64-windows-static
vcpkg install unicorn:x64-windows-static
vcpkg install fmt:x64-windows-static
vcpkg install rapidjson:x64-windows-static
vcpkg install keystone:x64-windows-static
popd
- name: Clone source
uses: actions/checkout@v2
- name: Add msbuild to PATH
uses: microsoft/setup-msbuild@v1.1
- name: Build project
run: |
vcpkg integrate install
msbuild navicat-keygen.sln /p:Configuration=Release /p:Platform=x64
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: navicat-keygen-x64.zip
path: bin/x64-Release/*.exe

7
.gitignore vendored
View File

@ -1,4 +1,3 @@
.vs/
.vscode/
bin/
obj/
*.DS_Store
.vscode/*
bin/*

233
HOW_DOES_IT_WORK.md Normal file
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
HOW_DOES_IT_WORK.zh-CN.md Normal file
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软件中填入 __激活码__ 即可完成离线激活。

97
Makefile Normal file
View File

@ -0,0 +1,97 @@
CC = g++
OPENSSL_INCLUDE_PATH = /usr/local/opt/openssl@1.1/include
OPENSSL_LIB_PATH = /usr/local/opt/openssl@1.1/lib
CAPSTONE_INCLUDE_PATH =
CAPSTONE_LIB_PATH =
KEYSTONE_INCLUDE_PATH =
KEYSTONE_LIB_PATH =
RAPIDJSON_INCLUDE_PATH =
LIBPLIST_INCLUDE_PATH =
LIBPLIST_LIB_PATH =
OUTPUT_DIR = ./bin/
COMMON_DIR = ./common/
PATCHER_DIR = ./navicat-patcher/
KEYGEN_DIR = ./navicat-keygen/
COMMON_HEADER = \
$(COMMON_DIR)Exception.hpp \
$(COMMON_DIR)ExceptionGeneric.hpp \
$(COMMON_DIR)ExceptionOpenssl.hpp \
$(COMMON_DIR)ExceptionSystem.hpp \
$(COMMON_DIR)ResourceTraitsOpenssl.hpp \
$(COMMON_DIR)ResourceWrapper.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)MemoryAccess.hpp \
$(PATCHER_DIR)Misc.hpp \
$(PATCHER_DIR)X64ImageInterpreter.hpp \
$(PATCHER_DIR)PatchSolutions.hpp
PATCHER_SOURCE = \
$(PATCHER_DIR)CapstoneDisassembler.cpp \
$(PATCHER_DIR)KeystoneAssembler.cpp \
$(PATCHER_DIR)Misc.cpp \
$(PATCHER_DIR)X64ImageInterpreter.cpp \
$(PATCHER_DIR)PatchSolution0.cpp \
$(PATCHER_DIR)PatchSolution1.cpp \
$(PATCHER_DIR)PatchSolution2.cpp \
$(PATCHER_DIR)PatchSolution3.cpp \
$(PATCHER_DIR)main.cpp
PATCHER_BINARY = $(OUTPUT_DIR)navicat-patcher
KEYGEN_HEADER = \
$(KEYGEN_DIR)Base32.hpp \
$(KEYGEN_DIR)Base64.hpp \
$(KEYGEN_DIR)SerialNumberGenerator.hpp
KEYGEN_SOURCE = \
$(KEYGEN_DIR)CollectInformation.cpp \
$(KEYGEN_DIR)GenerateLicense.cpp \
$(KEYGEN_DIR)main.cpp \
$(KEYGEN_DIR)SerialNumberGenerator.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$(COMMON_DIR) \
-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),) \
$(PATCHER_SOURCE) -o $(PATCHER_BINARY) -lcrypto -lcapstone -lkeystone -lplist++
@echo
keygen: $(KEYGEM_HEADER) $(KEYGEN_SOURCE)
@if [ ! -d $(OUTPUT_DIR) ]; then mkdir -p $(OUTPUT_DIR); fi
$(CC) -std=c++17 -O2 \
-I$(COMMON_DIR) \
-I$(OPENSSL_INCLUDE_PATH) -L$(OPENSSL_LIB_PATH) \
$(if $(RAPIDJSON_INCLUDE_PATH),-I$(RAPIDJSON_INCLUDE_PATH),) \
$(KEYGEN_SOURCE) -o $(KEYGEN_BINARY) -lcrypto
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

228
README.md
View File

@ -1,35 +1,229 @@
# navicat-keygen
# Navicat Keygen
[中文版README](README.zh-CN.md)
This repository will tell you how Navicat offline activation works.
Previous previous code is archived in [`windows-archived`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived) branch for the reason that previous previous code contains 3rd binary libraries and it gets quite big :-(
[How does it work?](HOW_DOES_IT_WORK.md)
Previous code is archived in [`windows-archived2`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived2) branch for the reason that Navicat has come to version 16.x.x which I think should be a milestone and I decide to obsolete previous code and rewrite new one.
__NOTICE: This keygen only supports Navicat Premium.__
When you git-clone this repo, please add `--single-branch` flag so that archived branches won't be cloned to your computer, which saves your time and disk.
## 1. How to build
```console
$ git clone -b windows --single-branch https://notabug.org/doublesine/navicat-keygen.git
```
* Before you build keygen, you should make sure you have following libs:
```
openssl
capstone
keystone
rapidjson
libplist
```
## 1. How does it work?
You can install them by
```shell
$ brew install openssl
$ brew install capstone
$ brew install keystone
$ brew install rapidjson
$ brew install libplist
```
see [here](doc/how-does-it-work.md). (WATING TO BE UPDATED)
* Clone `mac` branch and build keygen and patcher:
## 2. How to build?
```shell
$ git clone -b mac --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
$ cd navicat-keygen
$ make all
```
see [here](doc/how-to-build.md).
You will see two executable files in `bin/` directory:
## 3. How to use?
```shell
$ ls bin/
navicat-keygen navicat-patcher
```
see [here](doc/how-to-use.md).
## 2. How to Use
## 4. Contributor
1. Build keygen and patcher. __And open Navicat Premium AT LEAST ONCE!!!__
* 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`.
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 [--dry-run] <Navicat installation path> [RSA-2048 Private Key File]
[--dry-run] Run patcher without applying any patches.
This parameter is optional.
<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.
```
__Example:__
```console
$ ./navicat-patcher /Applications/Navicat\ Premium.app/
```
It has been tested on __Navicat Premium 15.0.4 English For Mac__ version.
An example of output can be found [here](example/navicat-patcher.txt)
* __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 `libcc-premium.dylib`, if have, and `Navicat Premium.app`.__
* __If you Navicat Premium version >= 15.0.0,__
__you must re-sign `libcc-premium.dylib` before re-sign `Navicat Premium.app`.__
```console
$ codesign -f -s "Your self-signed code-sign certificate name" <path to Navicat Premium.app>/Contents/Frameworks/libcc-premium.dylib
```
```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/Contents/Frameworks/libcc-premium.dylib
$ codesign -f -s "foobar" /Applications/Navicat\ Premium.app/
```
6. Then use `navicat-keygen` to generate __snKey__ and __Activation Code__.
```
Usage:
navicat-keygen [--adv] <RSA-2048 Private Key File>
[--adv] Enable advance mode.
This parameter is optional.
<RSA-2048 Private Key File> A path to an RSA-2048 private key file.
This parameter must be specified.
Example:
./navicat-keygen ./RegPrivateKey.pem
```
__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 (macOS) by @DoubleLabyrinth *
* Version: 5.0 *
**********************************************************
[*] 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)> 0
[*] Input major version number:
(range: 0 ~ 15, default: 15)> 15
[*] Serial number:
NAVD-ZM3Z-BK6L-JUWD
[*] 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: (Double press ENTER 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
[*] Input request code in Base64: (Double press ENTER to end)
IF+tuUn0WcDqJ0tthu/UwOxCZAz5/TqGrSG/9y5DcYJ0/5kfu11Tu314T/pUFK7WPzbnK2MFQ9kb9VytT4T10fXHKoHVYRBtOTYDQqCN2lwnmTty1i1SwUVO+CAqXasqqnss/r4ytbQUpsr2EmBqMQeXERhH72winnhfHkXoWgIHhYXgcvRBagKI1a48c8vJTjTB1eYHmO+DQI6orJoQ65ClqVSkdgKwyhAtSv0yMeKQX45UEX5hQCu9rrgqRN13f7mKWXhGZXkYrk4VZaHdfsr0o50zmU/ZhKLdFqRjrLzt4JY41+AIjAxtHd5g/LAUwBfUdfy9KdHjaeXCxdueXQ==
[*] Request Info:
{"K":"NAVDZM3ZBK6LJUWD", "DI":"78BC84E24E18EFCE1DF7", "P":"MAC"}
[*] Response Info:
{"K":"NAVDZM3ZBK6LJUWD","DI":"78BC84E24E18EFCE1DF7","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1576005483}
[*] Activation Code:
dJldt4pru2xBtqWiYCdT8s8H0vQ8xe8wI/f3/BLzSf7m3gevql9Z9CfkdMpuCJg35YPYTDHBwYYLnU6heO0bmvnVAF1U6ZKtWXpAAi+w6tGjeV64uachGI+/xb5Q5bQzD0V44PGYmL6cYULYjNtndMAgzhWGFzgsjGtaJOSczWC2OI1R1gAGh+l+pFdx37+VMXtfUtwv7V+qypj5CrzIULsUdh9U5JHXkdVSK6y+8bEeplYLwvQR6Cnavra0WUAP0hSg7khjy+mPiCuXSMwH1EphFqXscp1WUGjkms7pSK/aPtCoxWcJeK3SrgAVberBn2+rqaI1PBBh5DTctDy2SQ==
```
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.
* zenuo

View File

@ -1,34 +1,222 @@
# navicat-keygen for windows
# Navicat Keygen
这份repo将会告诉你Navicat是怎么完成离线激活的。
第一次归档的代码位于 [`windows-archived`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived) 分支。归档原因:包含第三方二进制库,项目过大。
[注册机是怎么工作的?](HOW_DOES_IT_WORK.zh-CN.md)
第二次归档的代码位于 [`windows-archived2`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived2) 分支。归档原因Navicat进入16.x.x版本本项目打算进行重构。
__注意仅支持Navicat Premium。__
当你clone该仓库的时候请使用 `--single-branch` 选项以此避免clone到已被归档的分支、以及节省你的时间和磁盘空间。
## 1. 如何编译
```console
$ git clone -b windows --single-branch https://notabug.org/doublesine/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
```
见[这里](doc/how-to-use.zh-CN.md)。
## 2. 如何使用这个Keygen
## 4. 贡献者
1. 编译好keygen和patcher。__并且打开Navicat Premium至少一次。
* Deltafox79
2. 备份好Navicat中所有已保存的数据库连接包括密码
* dragonflylee
3. 移除所有Navicat在 `Keychain Access.app` (即钥匙链)中保存的连接,如果有的话。
* zenuo
你可以通过在 `Keychain Access.app` 中搜索关键词 `navicat` 来找到它们。
4. 使用`navicat-patcher`替换掉公钥:
```
Usage:
navicat-patcher [--dry-run] <Navicat installation path> [RSA-2048 Private Key File]
[--dry-run] Run patcher without applying any patches.
This parameter is optional.
<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.
```
__例如__
```console
$ ./navicat-patcher /Applications/Navicat\ Premium.app/
```
__Navicat Premium For Mac 15.0.4 英文版__ 已通过测试。样例输出见[这里](example/navicat-patcher.txt)。
* __仅对 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``libcc-premium.dylib` (如果有的话) 和 `Navicat Premium.app` 重签名。__
* __如果你的Navicat Premium版本号高于15.0.0__
__你必须先签名 `libcc-premium.dylib`,再签名 `Navicat Premium.app`。__
```console
$ codesign -f -s "Your self-signed code-sign certificate name" <path to Navicat Premium.app>/Contents/Frameworks/libcc-premium.dylib
```
```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/Contents/Frameworks/libcc-premium.dylib
$ codesign -f -s "foobar" /Applications/Navicat\ Premium.app/
```
6. 接下来使用`navicat-keygen`来生成 __序列号____激活码__
```
Usage:
navicat-keygen [--adv] <RSA-2048 Private Key File>
[--adv] Enable advance mode.
This parameter is optional.
<RSA-2048 Private Key File> A path to an RSA-2048 private key file.
This parameter must be specified.
Example:
./navicat-keygen ./RegPrivateKey.pem
```
__例如__
```console
$ ./navicat-keygen ./RegPrivateKey.pem
```
你会被要求选择Navicat的语言以及输入主版本号。之后会随机生成一个 __序列号__
```console
$ ./navicat-keygen ./RegPrivateKey.pem
**********************************************************
* Navicat Keygen (macOS) by @DoubleLabyrinth *
* Version: 5.0 *
**********************************************************
[*] 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)> 0
[*] Input major version number:
(range: 0 ~ 15, default: 15)> 15
[*] Serial number:
NAVD-ZM3Z-BK6L-JUWD
[*] Your name:
```
你可以使用这个 __序列号__ 暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```console
[*] Your name: DoubleLabyrinth
[*] Your organization: DoubleLabyrinth
[*] Input request code in Base64: (Double press ENTER to end)
```
之后你会被要求填入请求码。注意 __不要关闭注册机__
7. __断开网络__ 并打开Navicat。
找到`注册`窗口,填入注册机给你的序列号。然后点击`激活`按钮。
8. 一般来说在线激活肯定会失败这时候Navicat会询问你是否`手动激活`,直接选吧。
9. 在`手动激活`窗口你会得到一个请求码复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```console
[*] Input request code in Base64: (Double press ENTER to end)
IF+tuUn0WcDqJ0tthu/UwOxCZAz5/TqGrSG/9y5DcYJ0/5kfu11Tu314T/pUFK7WPzbnK2MFQ9kb9VytT4T10fXHKoHVYRBtOTYDQqCN2lwnmTty1i1SwUVO+CAqXasqqnss/r4ytbQUpsr2EmBqMQeXERhH72winnhfHkXoWgIHhYXgcvRBagKI1a48c8vJTjTB1eYHmO+DQI6orJoQ65ClqVSkdgKwyhAtSv0yMeKQX45UEX5hQCu9rrgqRN13f7mKWXhGZXkYrk4VZaHdfsr0o50zmU/ZhKLdFqRjrLzt4JY41+AIjAxtHd5g/LAUwBfUdfy9KdHjaeXCxdueXQ==
[*] Request Info:
{"K":"NAVDZM3ZBK6LJUWD", "DI":"78BC84E24E18EFCE1DF7", "P":"MAC"}
[*] Response Info:
{"K":"NAVDZM3ZBK6LJUWD","DI":"78BC84E24E18EFCE1DF7","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1576005483}
[*] Activation Code:
dJldt4pru2xBtqWiYCdT8s8H0vQ8xe8wI/f3/BLzSf7m3gevql9Z9CfkdMpuCJg35YPYTDHBwYYLnU6heO0bmvnVAF1U6ZKtWXpAAi+w6tGjeV64uachGI+/xb5Q5bQzD0V44PGYmL6cYULYjNtndMAgzhWGFzgsjGtaJOSczWC2OI1R1gAGh+l+pFdx37+VMXtfUtwv7V+qypj5CrzIULsUdh9U5JHXkdVSK6y+8bEeplYLwvQR6Cnavra0WUAP0hSg7khjy+mPiCuXSMwH1EphFqXscp1WUGjkms7pSK/aPtCoxWcJeK3SrgAVberBn2+rqaI1PBBh5DTctDy2SQ==
```
10. 如果不出意外你会得到一个看似用Base64编码的激活码。
直接复制它并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。
如果没什么意外的话应该能成功激活。

124
common/Exception.hpp Normal file
View File

@ -0,0 +1,124 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <exception>
#include <string>
#include <vector>
#include <utility>
namespace ARL {
class Exception : public std::exception {
private:
const char* m_SourceFile;
const size_t m_SourceLine;
std::string m_Message;
std::vector<std::string> m_Hints;
public:
template<typename... __ArgTypes>
Exception(const char* SourceFile, size_t SourceLine, const char* Format, __ArgTypes&&... Args) noexcept :
m_SourceFile(SourceFile),
m_SourceLine(SourceLine)
{
if constexpr (sizeof...(Args) == 0) {
m_Message.assign(Format);
} else {
int l;
l = snprintf(nullptr, 0, Format, std::forward<__ArgTypes>(Args)...);
if (l < 0) {
std::terminate();
}
m_Message.resize(l + 1);
l = snprintf(m_Message.data(), m_Message.length(), Format, std::forward<__ArgTypes>(Args)...);
if (l < 0) {
std::terminate();
}
while (m_Message.back() == '\x00') {
m_Message.pop_back();
}
}
}
[[nodiscard]]
auto ExceptionFile() const noexcept {
return m_SourceFile;
}
[[nodiscard]]
auto ExceptionLine() const noexcept {
return m_SourceLine;
}
[[nodiscard]]
auto ExceptionMessage() const noexcept {
return m_Message.c_str();
}
template<typename __HintType>
auto& PushHint(__HintType&& Hint) noexcept { // if an exception is thrown, just suppress and terminate.
m_Hints.emplace_back(std::forward<__HintType>(Hint));
return *this;
}
template<typename... __ArgTypes>
auto& PushFormatHint(const char* Format, __ArgTypes&&... Args) noexcept { // if an exception is thrown, just suppress and terminate.
int l;
std::string s;
l = snprintf(nullptr, 0, Format, std::forward<__ArgTypes>(Args)...);
if (l < 0) {
std::terminate();
}
s.resize(l + 1);
l = snprintf(s.data(), s.length(), Format, std::forward<__ArgTypes>(Args)...);
if (l < 0) {
std::terminate();
}
while (s.back() == '\x00') {
s.pop_back();
}
m_Hints.emplace_back(std::move(s));
return *this;
}
[[nodiscard]]
const auto& Hints() const noexcept {
return m_Hints;
}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept {
return false;
}
[[nodiscard]]
virtual intptr_t ErrorCode() const noexcept {
return 0;
}
[[nodiscard]]
virtual const char* ErrorString() const noexcept {
return nullptr;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* what() const noexcept override {
return ExceptionMessage();
}
};
}

View File

@ -0,0 +1,28 @@
#pragma once
#include "Exception.hpp"
namespace ARL {
#pragma push_macro("DECLARE_NEW_EXCEPTION")
#undef DECLARE_NEW_EXCEPTION
#define DECLARE_NEW_EXCEPTION(name) \
class name final : public Exception { \
public: \
template<typename... __ArgTypes> \
name(const char* SourceFile, size_t SourceLine, const char* Format, __ArgTypes&&... Args) noexcept : \
Exception(SourceFile, SourceLine, Format, std::forward<__ArgTypes>(Args)...) {} \
}
DECLARE_NEW_EXCEPTION(AssertionError);
DECLARE_NEW_EXCEPTION(EOFError);
DECLARE_NEW_EXCEPTION(IndexError);
DECLARE_NEW_EXCEPTION(KeyError);
DECLARE_NEW_EXCEPTION(NotImplementedError);
DECLARE_NEW_EXCEPTION(OverflowError);
DECLARE_NEW_EXCEPTION(ValueError);
#undef DECLARE_NEW_EXCEPTION
#pragma pop_macro("DECLARE_NEW_EXCEPTION")
}

View File

@ -0,0 +1,45 @@
#pragma once
#include "Exception.hpp"
#include <openssl/err.h>
namespace ARL {
class OpensslError final : public Exception {
private:
unsigned long m_ErrorCode;
public:
template<typename... __ArgTypes>
OpensslError(const char* SourceFile, size_t SourceLine, unsigned long ErrorCode, const char* Format, __ArgTypes&&... Args) noexcept :
Exception(SourceFile, SourceLine, Format, std::forward<__ArgTypes>(Args)...),
m_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 m_ErrorCode;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
static bool loaded = false;
if (loaded == false) {
ERR_load_crypto_strings();
loaded = true;
}
return ERR_reason_error_string(m_ErrorCode);
}
};
}

View File

@ -0,0 +1,39 @@
#pragma once
#include "Exception.hpp"
#include <string.h>
namespace ARL {
class SystemError final : public Exception {
private:
int m_ErrorCode;
public:
template<typename... __ArgTypes>
SystemError(const char* SourceFile, size_t SourceLine, int ErrorCode, const char* Format, __ArgTypes&&... Args) noexcept :
Exception(SourceFile, SourceLine, Format, std::forward<__ArgTypes>(Args)...),
m_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 m_ErrorCode;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
return strerror(m_ErrorCode);
}
};
}

274
common/RSACipher.hpp Normal file
View File

@ -0,0 +1,274 @@
#pragma once
#include <openssl/opensslv.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <string>
#include "Exception.hpp"
#include "ExceptionOpenssl.hpp"
#include "ResourceWrapper.hpp"
#include "ResourceTraitsOpenssl.hpp"
namespace nkg {
enum class RSAKeyType {
PrivateKey,
PublicKey
};
enum class RSAKeyFormat {
PEM,
PKCS1
};
class RSACipher final : private ARL::ResourceWrapper<ARL::ResourceTraits::OpensslRSA> {
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 ARL::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 ARL::Exception(__FILE__, __LINE__, "PEM_write_bio_RSA_PUBKEY failed.");
}
}
if constexpr (__Format == RSAKeyFormat::PKCS1) {
if (PEM_write_bio_RSAPublicKey(lpBIO, lpRSA) == 0) {
throw ARL::Exception(__FILE__, __LINE__, "PEM_write_bio_RSAPublicKey failed.");
}
}
static_assert(__Format == RSAKeyFormat::PEM || __Format == RSAKeyFormat::PKCS1);
}
static_assert(__Type == RSAKeyType::PrivateKey || __Type == RSAKeyType::PublicKey);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
[[nodiscard]]
static RSA* _ReadRSAFromBIO(BIO* lpBIO) {
RSA* lpRSA;
if constexpr (__Type == RSAKeyType::PrivateKey) {
lpRSA = PEM_read_bio_RSAPrivateKey(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw ARL::Exception(__FILE__, __LINE__, "PEM_read_bio_RSAPrivateKey failed.")
.PushHint("Are you sure that you DO provide a valid RSA private key file?");
}
}
if constexpr (__Type == RSAKeyType::PublicKey) {
if constexpr (__Format == RSAKeyFormat::PEM) {
lpRSA = PEM_read_bio_RSA_PUBKEY(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw ARL::Exception(__FILE__, __LINE__, "PEM_read_bio_RSA_PUBKEY failed.")
.PushHint("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 ARL::Exception(__FILE__, __LINE__, "PEM_read_bio_RSAPublicKey failed.")
.PushHint("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() : ARL::ResourceWrapper<ARL::ResourceTraits::OpensslRSA>(RSA_new()) {
if (IsValid() == false) {
throw ARL::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 (Get()->n == nullptr) {
throw ARL::Exception(__FILE__, __LINE__, "RSA modulus has not been set.");
} else {
return BN_num_bits(Get()->n);
}
#elif (OPENSSL_VERSION_NUMBER & 0xffff0000) == 0x10100000 // openssl 1.1.x
return RSA_bits(Get());
#else
#error "RSACipher.hpp: unexpected OpenSSL version."
#endif
}
void GenerateKey(int bits, unsigned int e = RSA_F4) {
ARL::ResourceWrapper bn_e{ ARL::ResourceTraits::OpensslBIGNUM{} };
bn_e.TakeOver(BN_new());
if (bn_e.IsValid() == false) {
throw ARL::OpensslError(__FILE__, __LINE__, ERR_get_error(), "BN_new failed.");
}
if (!BN_set_word(bn_e, e)) {
throw ARL::Exception(__FILE__, __LINE__, "BN_set_word failed.");
}
if (!RSA_generate_key_ex(Get(), bits, bn_e, nullptr)) {
throw ARL::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_generate_key_ex failed.");
}
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ExportKeyToFile(std::string_view FileName) const {
ARL::ResourceWrapper KeyFile{ ARL::ResourceTraits::OpensslBIO{} };
KeyFile.TakeOver(BIO_new_file(FileName.data(), "w"));
if (KeyFile.IsValid() == false) {
throw ARL::Exception(__FILE__, __LINE__, "BIO_new_file failed.");
}
_WriteRSAToBIO<__Type, __Format>(Get(), KeyFile);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
[[nodiscard]]
std::string ExportKeyString() const {
ARL::ResourceWrapper TempMemory{ ARL::ResourceTraits::OpensslBIO{} };
const char* lpsz = nullptr;
TempMemory.TakeOver(BIO_new(BIO_s_mem()));
if (TempMemory.IsValid() == false) {
throw ARL::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
_WriteRSAToBIO<__Type, __Format>(Get(), TempMemory);
auto l = BIO_get_mem_data(TempMemory.Get(), &lpsz);
std::string KeyString(lpsz, l);
while (KeyString.back() == '\n' || KeyString.back() == '\r') {
KeyString.pop_back();
}
return KeyString;
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyFromFile(std::string_view FileName) {
ARL::ResourceWrapper KeyFile{ ARL::ResourceTraits::OpensslBIO{} };
KeyFile.TakeOver(BIO_new_file(FileName.data(), "r"));
if (KeyFile.IsValid() == false) {
throw ARL::Exception(__FILE__, __LINE__, "BIO_new_file failed.");
}
ReleaseAndTakeOver(_ReadRSAFromBIO<__Type, __Format>(KeyFile));
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyString(std::string_view KeyString) {
ARL::ResourceWrapper TempMemory{ ARL::ResourceTraits::OpensslBIO{} };
TempMemory.TakeOver(BIO_new(BIO_s_mem()));
if (TempMemory.IsValid() == false) {
throw ARL::Exception(__FILE__, __LINE__, "BIO_new failed.");
}
if (BIO_puts(TempMemory.Get(), KeyString.data()) <= 0) {
throw ARL::Exception(__FILE__, __LINE__, "BIO_puts failed.");
}
TakeOver(_ReadRSAFromBIO<__Type, __Format>(TempMemory));
}
template<RSAKeyType __Type = RSAKeyType::PublicKey>
size_t Encrypt(const void* lpFrom, size_t cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
if (cbFrom > static_cast<size_t>(INT_MAX)) {
throw ARL::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),
Get(),
Padding
);
if (BytesWritten == -1) {
throw ARL::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),
Get(),
Padding
);
if (BytesWritten == -1) {
throw ARL::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_public_encrypt failed.");
}
}
return BytesWritten;
}
template<RSAKeyType __Type = RSAKeyType::PrivateKey>
size_t Decrypt(const void* lpFrom, size_t cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
if (cbFrom > static_cast<size_t>(INT_MAX)) {
throw ARL::Exception(__FILE__, __LINE__, "Length overflowed.");
}
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 ARL::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_private_decrypt failed.")
.PushHint("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 ARL::OpensslError(__FILE__, __LINE__, ERR_get_error(), "RSA_public_decrypt failed.")
.PushHint("Are your sure you DO provide a correct public key?");
}
}
return BytesWritten;
}
};
}

View File

@ -0,0 +1,68 @@
#pragma once
#include <openssl/bio.h>
#include <openssl/rsa.h>
namespace ARL::ResourceTraits {
struct OpensslBIO {
using HandleType = BIO*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) noexcept {
BIO_free(Handle);
}
};
struct OpensslBIOChain {
using HandleType = BIO*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) noexcept {
BIO_free_all(Handle);
}
};
struct OpensslBIGNUM {
using HandleType = BIGNUM*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) noexcept {
BN_free(Handle);
}
};
struct OpensslRSA {
using HandleType = RSA*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) noexcept {
RSA_free(Handle);
}
};
}

375
common/ResourceWrapper.hpp Normal file
View File

@ -0,0 +1,375 @@
#pragma once
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace ARL {
template<typename __ResourceTraits>
class ResourceWrapper {
public:
using HandleType = typename __ResourceTraits::HandleType;
static_assert(
std::is_trivial_v<HandleType> && std::is_standard_layout_v<HandleType>,
"HandleType must be a POD type."
);
private:
HandleType m_Handle;
public:
ResourceWrapper() noexcept :
m_Handle(__ResourceTraits::InvalidValue) {}
ResourceWrapper(const HandleType& Handle) noexcept :
m_Handle(Handle) {}
ResourceWrapper(__ResourceTraits) noexcept :
m_Handle(__ResourceTraits::InvalidValue) {}
ResourceWrapper(__ResourceTraits, const HandleType& Handle) noexcept :
m_Handle(Handle) {}
ResourceWrapper(const ResourceWrapper& Other) = delete;
ResourceWrapper(ResourceWrapper&& Other) noexcept :
m_Handle(std::move(Other.m_Handle))
{
Other.m_Handle = __ResourceTraits::InvalidValue;
}
ResourceWrapper& operator=(const ResourceWrapper& Other) = delete;
ResourceWrapper& operator=(ResourceWrapper&& Other) noexcept {
if (this != std::addressof(Other)) {
if (IsValid()) {
__ResourceTraits::Release(m_Handle);
}
m_Handle = std::move(Other.m_Handle);
Other.m_Handle = __ResourceTraits::InvalidValue;
}
return *this;
}
[[nodiscard]]
operator HandleType() const noexcept { // NOLINT: Allow implicit conversion.
return m_Handle;
}
template<typename __AsType>
[[nodiscard]]
__AsType As() const noexcept {
return reinterpret_cast<__AsType>(m_Handle);
}
template<bool __Enable = std::is_pointer_v<HandleType>>
[[nodiscard]]
std::enable_if_t<__Enable, HandleType> operator->() const noexcept {
return m_Handle;
}
[[nodiscard]]
bool IsValid() const noexcept {
return __ResourceTraits::IsValid(m_Handle);
}
[[nodiscard]]
HandleType Get() const noexcept {
return m_Handle;
}
[[nodiscard]]
HandleType* GetAddressOf() noexcept {
return &m_Handle;
}
template<typename __ReturnType>
[[nodiscard]]
__ReturnType GetAddressOfAs() noexcept {
return reinterpret_cast<__ReturnType>(&m_Handle);
}
void TakeOver(const HandleType& Handle) {
if (IsValid() == false) {
m_Handle = Handle;
} else {
throw std::runtime_error("ResourceWrapper is already in use.");
}
}
void Discard() noexcept {
m_Handle = __ResourceTraits::InvalidValue;
}
[[nodiscard]]
HandleType Transfer() noexcept {
auto t = m_Handle;
m_Handle = __ResourceTraits::InvalidValue;
return t;
}
template<typename __ReturnType>
[[nodiscard]]
__ReturnType TransferAs() noexcept {
static_assert(
std::is_trivial_v<__ReturnType> && std::is_standard_layout_v<__ReturnType>,
"__ReturnType should also be a POD type, just like HandleType."
);
auto t = reinterpret_cast<__ReturnType>(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
return t;
}
void Release() {
if (IsValid()) {
__ResourceTraits::Release(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
}
}
void ReleaseAndTakeOver(const HandleType& Handle) {
if (IsValid()) {
__ResourceTraits::Release(m_Handle);
}
m_Handle = Handle;
}
[[nodiscard]]
HandleType* ReleaseAndGetAddressOf() {
if (IsValid()) {
__ResourceTraits::Release(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
}
return GetAddressOf();
}
template<typename __ReturnType>
__ReturnType ReleaseAndGetAddressOfAs() {
if (IsValid()) {
__ResourceTraits::Release(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
}
return GetAddressOfAs<__ReturnType>();
}
~ResourceWrapper() {
Release();
}
};
template<typename __ResourceTraits, typename __DeleterType>
class ResourceWrapperEx {
public:
using HandleType = typename __ResourceTraits::HandleType;
using DeleterType = __DeleterType;
static_assert(
std::is_trivial_v<HandleType> && std::is_standard_layout_v<HandleType>,
"HandleType must be a POD type."
);
private:
HandleType m_Handle;
DeleterType m_Deleter;
public:
template<typename __DeleterArgType>
ResourceWrapperEx(__ResourceTraits, __DeleterArgType&& Deleter) noexcept :
m_Handle(__ResourceTraits::InvalidValue),
m_Deleter(std::forward<__DeleterArgType>(Deleter)) {}
template<typename __DeleterArgType>
ResourceWrapperEx(__ResourceTraits, const HandleType& Handle, __DeleterArgType&& Deleter) noexcept :
m_Handle(Handle),
m_Deleter(std::forward<__DeleterArgType>(Deleter)) {}
ResourceWrapperEx(const ResourceWrapperEx& Other) = delete;
ResourceWrapperEx(ResourceWrapperEx&& Other) noexcept :
m_Handle(std::move(Other.m_Handle)),
m_Deleter(std::move(Other.m_Deleter))
{
Other.m_Handle = __ResourceTraits::InvalidValue;
}
ResourceWrapperEx& operator=(const ResourceWrapperEx& Other) = delete;
ResourceWrapperEx& operator=(ResourceWrapperEx&& Other) noexcept {
if (this != std::addressof(Other)) {
if (IsValid()) {
m_Deleter(m_Handle);
}
m_Handle = std::move(Other.m_Handle);
m_Deleter = std::move(Other.m_Deleter);
Other.m_Handle = __ResourceTraits::InvalidValue;
}
return *this;
}
[[nodiscard]]
operator HandleType() const noexcept { // NOLINT: Allow implicit conversion.
return m_Handle;
}
template<typename __AsType>
[[nodiscard]]
__AsType As() const noexcept {
return reinterpret_cast<__AsType>(m_Handle);
}
template<bool __Enable = std::is_pointer_v<HandleType>>
[[nodiscard]]
std::enable_if_t<__Enable, HandleType> operator->() const noexcept {
return m_Handle;
}
[[nodiscard]]
bool IsValid() const noexcept {
return __ResourceTraits::IsValid(m_Handle);
}
[[nodiscard]]
HandleType Get() const noexcept {
return m_Handle;
}
[[nodiscard]]
HandleType* GetAddressOf() noexcept {
return &m_Handle;
}
template<typename __ReturnType>
[[nodiscard]]
__ReturnType GetAddressOfAs() noexcept {
return reinterpret_cast<__ReturnType>(&m_Handle);
}
void TakeOver(const HandleType& Handle) {
if (IsValid() == false) {
m_Handle = Handle;
} else {
throw std::runtime_error("ResourceWrapperEx is already in use.");
}
}
void Discard() noexcept {
m_Handle = __ResourceTraits::InvalidValue;
}
[[nodiscard]]
HandleType Transfer() noexcept {
auto t = m_Handle;
m_Handle = __ResourceTraits::InvalidValue;
return t;
}
template<typename __ReturnType>
[[nodiscard]]
__ReturnType TransferAs() noexcept {
static_assert(std::is_trivial_v<__ReturnType> && std::is_standard_layout_v<__ReturnType>);
auto t = reinterpret_cast<__ReturnType>(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
return t;
}
void Release() {
if (IsValid()) {
m_Deleter(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
}
}
void ReleaseAndTakeOver(const HandleType& Handle) {
if (IsValid()) {
__ResourceTraits::Release(m_Handle);
}
m_Handle = Handle;
}
[[nodiscard]]
HandleType* ReleaseAndGetAddressOf() {
if (IsValid()) {
m_Deleter(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
}
return GetAddressOf();
}
template<typename __ReturnType>
__ReturnType ReleaseAndGetAddressOfAs() {
if (IsValid()) {
m_Deleter(m_Handle);
m_Handle = __ResourceTraits::InvalidValue;
}
return GetAddressOfAs<__ReturnType>();
}
~ResourceWrapperEx() {
Release();
}
};
template<typename __ResourceTraits, typename __DeleterArgType>
ResourceWrapperEx(__ResourceTraits, __DeleterArgType&& Deleter) ->
ResourceWrapperEx<__ResourceTraits, std::remove_reference_t<__DeleterArgType>>;
template<typename __ResourceTraits, typename __DeleterArgType>
ResourceWrapperEx(__ResourceTraits, const typename __ResourceTraits::HandleType& Handle, __DeleterArgType&& Deleter) ->
ResourceWrapperEx<__ResourceTraits, std::remove_reference_t<__DeleterArgType>>;
namespace ResourceTraits {
template<typename __ClassType>
struct CppObject {
using HandleType = __ClassType*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) {
delete Handle;
}
};
template<typename __ElementType>
struct CppArray {
using HandleType = __ElementType*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) {
delete[] Handle;
}
};
}
}

View File

@ -1,49 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' &lt; '16.0'">$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<ItemsProjectGuid>{6d81a756-475a-4093-919e-3e9217f662ca}</ItemsProjectGuid>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectCapability Include="SourceItemsFromImports" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="$(MSBuildThisFileDirectory)cp_converter.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exceptions\index_exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exceptions\key_exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exceptions\win32_exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exceptions\not_implemented_exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exceptions\operation_canceled_exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)exceptions\overflow_exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\keystone\keystone_handle.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\bignum.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\bio.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\bio_chain.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\decoder_ctx.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\encoder_ctx.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\evp_cipher_ctx.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\evp_pkey.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\evp_pkey_ctx.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\openssl\rsa.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\unicorn\unicorn_handle.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\win32\map_view_ptr.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\cxx_dynamic_array_traits.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\cxx_object_traits.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\win32\file_handle.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\win32\generic_handle.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_traits\win32\local_alloc.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)resource_wrapper.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)rsa_cipher.hpp" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(MSBuildThisFileDirectory)exceptions\win32_exception.cpp" />
<ClCompile Include="$(MSBuildThisFileDirectory)rsa_cipher.cpp" />
</ItemGroup>
</Project>

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>

View File

@ -1,79 +0,0 @@
#pragma once
#include <string>
#include <windows.h>
#include "exceptions/win32_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\common\\cp_converter.hpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
template<int from_cp, int to_cp>
struct cp_converter {
static std::string convert(std::string_view from_string) {
if constexpr (from_cp == to_cp) {
return from_string;
} else {
if (from_cp == CP_ACP && GetACP() == to_cp) {
return from_string;
} else {
return cp_converter<-1, to_cp>::convert(cp_converter<from_cp, -1>::convert(from_string));
}
}
}
};
template<int from_cp>
struct cp_converter<from_cp, -1> {
static std::wstring convert(std::string_view from_string) {
int len;
len = MultiByteToWideChar(from_cp, 0, from_string.data(), -1, NULL, 0);
if (len <= 0) {
throw ::nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"MultiByteToWideChar failed.");
}
std::wstring to_string(len, 0);
len = MultiByteToWideChar(from_cp, 0, from_string.data(), -1, to_string.data(), len);
if (len <= 0) {
throw ::nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"MultiByteToWideChar failed.");
}
while (to_string.length() > 0 && to_string.back() == 0) {
to_string.pop_back();
}
return to_string;
}
};
template<int to_cp>
struct cp_converter<-1, to_cp> {
static std::string convert(std::wstring_view from_string) {
int len;
len = WideCharToMultiByte(to_cp, 0, from_string.data(), -1, NULL, 0, NULL, NULL);
if (len <= 0) {
throw ::nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"WideCharToMultiByte failed.");
}
std::string to_string(len, 0);
len = WideCharToMultiByte(to_cp, 0, from_string.data(), -1, to_string.data(), len, NULL, NULL);
if (len <= 0) {
throw ::nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"WideCharToMultiByte failed.");
}
while (to_string.length() > 0 && to_string.back() == 0) {
to_string.pop_back();
}
return to_string;
}
};
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,86 +0,0 @@
#pragma once
#include <exception>
#include <string>
#include <vector>
namespace nkg {
class exception : public std::exception {
private:
int m_source_line;
std::string m_source_file;
std::string m_custom_message;
std::vector<std::string> m_hints;
public:
[[noreturn]]
static void trap_then_terminate() {
#if _MSC_VER
__debugbreak();
#elif defined(__GNUC__) || defined(__GNUG__) || defined(__clang__)
__builtin_trap();
#else
#error "exception.hpp: unknown compiler is detected."
#endif
std::terminate();
}
exception(std::string_view file, int line, std::string_view message) noexcept :
std::exception(), // don't pass `char*` to `std::exception`, because it is not documented in c++ standard.
m_source_line(line),
m_source_file(file),
m_custom_message(message) {}
[[nodiscard]]
int source_line() const noexcept {
return m_source_line;
}
[[nodiscard]]
const std::string& source_file() const noexcept {
return m_source_file;
}
[[nodiscard]]
const std::string& custom_message() const noexcept {
return m_custom_message;
}
exception& push_hint(std::string_view hint) noexcept {
m_hints.emplace_back(hint);
return *this;
}
exception& pop_hint() noexcept {
m_hints.pop_back();
return *this;
}
const std::vector<std::string>& hints() const noexcept {
return m_hints;
}
virtual const char* what() const noexcept override {
return m_custom_message.c_str();
}
[[nodiscard]]
virtual bool error_code_exists() const noexcept {
return false;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept {
trap_then_terminate();
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept {
trap_then_terminate();
}
virtual ~exception() = default;
};
}

View File

@ -1,10 +0,0 @@
#pragma once
#include "../exception.hpp"
namespace nkg::exceptions {
class index_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

@ -1,10 +0,0 @@
#pragma once
#include "../exception.hpp"
namespace nkg::exceptions {
class key_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

@ -1,10 +0,0 @@
#pragma once
#include "../exception.hpp"
namespace nkg::exceptions {
class not_implemented_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

@ -1,10 +0,0 @@
#pragma once
#include "../exception.hpp"
namespace nkg::exceptions {
class operation_canceled_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

@ -1,10 +0,0 @@
#pragma once
#include "../exception.hpp"
namespace nkg::exceptions {
class overflow_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

@ -1,30 +0,0 @@
#include "win32_exception.hpp"
#include "../resource_wrapper.hpp"
#include "../resource_traits/win32/local_alloc.hpp"
#include "../cp_converter.hpp"
namespace nkg::exceptions {
win32_exception::win32_exception(std::string_view file, int line, error_code_t win32_error_code, std::string_view message) noexcept :
::nkg::exception(file, line, message)
{
m_error_code = win32_error_code;
::nkg::resource_wrapper error_string{ ::nkg::resource_traits::win32::local_alloc{} };
FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL,
win32_error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
error_string.template unsafe_addressof<wchar_t>(),
0,
NULL
);
if (error_string.is_valid()) {
m_error_string = ::nkg::cp_converter<-1, CP_UTF8>::convert(error_string.template as<wchar_t*>());
} else {
std::terminate();
}
}
}

View File

@ -1,35 +0,0 @@
#pragma once
#include "../exception.hpp"
#include <windows.h>
namespace nkg::exceptions {
class win32_exception final : public ::nkg::exception {
public:
using error_code_t = decltype(GetLastError());
private:
error_code_t m_error_code;
std::string m_error_string;
public:
win32_exception(std::string_view file, int line, error_code_t win32_error_code, std::string_view message) noexcept;
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return true;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
return m_error_code;
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
return m_error_string;
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
namespace nkg::resource_traits {
template<typename element_t>
struct cxx_dynamic_array_traits {
using handle_t = element_t*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
delete[] handle;
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
namespace nkg::resource_traits {
template<typename object_t>
struct cxx_object_traits {
using handle_t = object_t*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
delete handle;
}
};
}

View File

@ -1,35 +0,0 @@
#pragma once
#include <keystone/keystone.h>
namespace nkg::resource_traits::keystone {
struct keystone_handle {
using handle_t = ks_engine*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
ks_close(handle);
}
};
struct keystone_alloc {
using handle_t = unsigned char*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
ks_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/bn.h>
namespace nkg::resource_traits::openssl {
struct bignum {
using handle_t = BIGNUM*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
BN_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/bio.h>
namespace nkg::resource_traits::openssl {
struct bio {
using handle_t = BIO*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
BIO_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/bio.h>
namespace nkg::resource_traits::openssl {
struct bio_chain {
using handle_t = BIO*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
BIO_free_all(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/decoder.h>
namespace nkg::resource_traits::openssl {
struct decoder_ctx {
using handle_t = OSSL_DECODER_CTX*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
OSSL_DECODER_CTX_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/encoder.h>
namespace nkg::resource_traits::openssl {
struct encoder_ctx {
using handle_t = OSSL_ENCODER_CTX*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
OSSL_ENCODER_CTX_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/evp.h>
namespace nkg::resource_traits::openssl {
struct evp_cipher_ctx {
using handle_t = EVP_CIPHER_CTX*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
EVP_CIPHER_CTX_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/evp.h>
namespace nkg::resource_traits::openssl {
struct evp_pkey {
using handle_t = EVP_PKEY*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
EVP_PKEY_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/evp.h>
namespace nkg::resource_traits::openssl {
struct evp_pkey_ctx {
using handle_t = EVP_PKEY_CTX*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
EVP_PKEY_CTX_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <openssl/rsa.h>
namespace nkg::resource_traits::openssl {
struct rsa {
using handle_t = RSA*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
RSA_free(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <unicorn/unicorn.h>
namespace nkg::resource_traits::unicorn {
struct unicorn_handle {
using handle_t = uc_engine*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
uc_close(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <windows.h>
namespace nkg::resource_traits::win32 {
struct file_handle {
using handle_t = HANDLE;
static inline const handle_t invalid_value = INVALID_HANDLE_VALUE;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
CloseHandle(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <windows.h>
namespace nkg::resource_traits::win32 {
struct generic_handle {
using handle_t = HANDLE;
static constexpr handle_t invalid_value = NULL;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
CloseHandle(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <windows.h>
namespace nkg::resource_traits::win32 {
struct local_alloc {
using handle_t = HLOCAL;
static constexpr handle_t invalid_value = NULL;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t handle) {
LocalFree(handle);
}
};
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <windows.h>
namespace nkg::resource_traits::win32 {
struct map_view_ptr {
using handle_t = PVOID;
static constexpr handle_t invalid_value = NULL;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) {
UnmapViewOfFile(handle);
}
};
}

View File

@ -1,245 +0,0 @@
#pragma once
#include <type_traits>
#include <utility>
namespace nkg {
template<typename resource_traits_t, typename releaser_t = void>
class resource_wrapper {
public:
using handle_t = typename resource_traits_t::handle_t;
static_assert(std::is_trivial_v<handle_t> && std::is_standard_layout_v<handle_t>, "`resource_wrapper` requires a handle with POD type.");
private:
handle_t m_handle;
releaser_t m_releaser;
public:
template<typename releaser_arg_t>
resource_wrapper(releaser_arg_t&& releaser) noexcept :
m_handle(resource_traits_t::invalid_value),
m_releaser(std::forward<releaser_arg_t>(releaser)) {}
template<typename releaser_arg_t>
resource_wrapper(const handle_t& handle, releaser_arg_t&& releaser) noexcept :
m_handle(handle),
m_releaser(std::forward<releaser_arg_t>(releaser)) {}
template<typename releaser_arg_t>
resource_wrapper(resource_traits_t, releaser_arg_t&& releaser) noexcept :
m_handle(resource_traits_t::invalid_value),
m_releaser(std::forward<releaser_arg_t>(releaser)) {}
template<typename releaser_arg_t>
resource_wrapper(resource_traits_t, const handle_t& handle, releaser_arg_t&& releaser) noexcept :
m_handle(handle),
m_releaser(std::forward<releaser_t>(releaser)) {}
//
// `resource_wrapper` does not allow copy-construct
//
resource_wrapper(const resource_wrapper& other) = delete;
//
// `resource_wrapper` allows move-construct.
//
resource_wrapper(resource_wrapper&& other) noexcept :
m_handle(other.m_handle),
m_releaser(std::move(other.m_releaser))
{
other.m_handle = resource_traits_t::invalid_value;
}
//
// `resource_wrapper` does not allow to copy.
//
resource_wrapper& operator=(const resource_wrapper& other) = delete;
//
// `resource_wrapper` allows to move.
//
resource_wrapper& operator=(resource_wrapper&& other) noexcept {
if (this != std::addressof(other)) {
m_handle = other.m_handle;
m_releaser = std::move(other.m_releaser);
other.m_handle = resource_traits_t::invalid_value;
}
return *this;
}
template<typename ptr_t = handle_t, std::enable_if_t<std::is_pointer_v<handle_t>, ptr_t> = nullptr>
[[nodiscard]]
ptr_t operator->() const noexcept {
return m_handle;
}
template<typename as_t>
[[nodiscard]]
as_t as() const noexcept {
return reinterpret_cast<as_t>(m_handle);
}
[[nodiscard]]
bool is_valid() const noexcept {
return resource_traits_t::is_valid(m_handle);
}
[[nodiscard]]
const handle_t& get() const noexcept {
return m_handle;
}
template<typename as_t = handle_t>
[[nodiscard]]
as_t* unsafe_addressof() noexcept {
return reinterpret_cast<as_t*>(std::addressof(m_handle));
}
void set(const handle_t& handle) {
if (is_valid()) {
m_releaser(m_handle);
}
m_handle = handle;
}
void discard() noexcept {
m_handle = resource_traits_t::invalid_value;
}
[[nodiscard]]
handle_t transfer() noexcept {
handle_t t = m_handle;
m_handle = resource_traits_t::invalid_value;
return t;
}
void release() {
if (is_valid()) {
m_releaser(m_handle);
m_handle = resource_traits_t::invalid_value;
}
}
~resource_wrapper() {
release();
}
};
template<typename resource_traits_t>
class resource_wrapper<resource_traits_t, void> {
public:
using handle_t = typename resource_traits_t::handle_t;
static_assert(std::is_trivial_v<handle_t>&& std::is_standard_layout_v<handle_t>, "`resource_wrapper` requires a handle with POD type.");
private:
handle_t m_handle;
public:
resource_wrapper() noexcept :
m_handle(resource_traits_t::invalid_value) {}
resource_wrapper(const handle_t& handle) noexcept :
m_handle(handle) {}
resource_wrapper(resource_traits_t) noexcept :
m_handle(resource_traits_t::invalid_value) {}
resource_wrapper(resource_traits_t, const handle_t& handle) noexcept :
m_handle(handle) {}
resource_wrapper(const resource_wrapper& other) = delete;
resource_wrapper(resource_wrapper&& other) noexcept :
m_handle(other.m_handle)
{
other.m_handle = resource_traits_t::invalid_value;
}
resource_wrapper& operator=(const resource_wrapper& other) = delete;
resource_wrapper& operator=(resource_wrapper&& other) noexcept {
if (this != std::addressof(other)) {
m_handle = other.m_handle;
other.m_handle = resource_traits_t::invalid_value;
}
return *this;
}
template<typename ptr_t = handle_t, std::enable_if_t<std::is_pointer_v<handle_t>, ptr_t> = nullptr>
[[nodiscard]]
ptr_t operator->() const noexcept {
return m_handle;
}
template<typename as_t>
[[nodiscard]]
as_t as() const noexcept {
return reinterpret_cast<as_t>(m_handle);
}
[[nodiscard]]
bool is_valid() const noexcept {
return resource_traits_t::is_valid(m_handle);
}
[[nodiscard]]
const handle_t& get() const noexcept {
return m_handle;
}
template<typename as_t = handle_t>
[[nodiscard]]
as_t* unsafe_addressof() noexcept {
return reinterpret_cast<as_t*>(std::addressof(m_handle));
}
void set(const handle_t& handle) {
if (is_valid()) {
resource_traits_t::release(m_handle);
}
m_handle = handle;
}
void discard() noexcept {
m_handle = resource_traits_t::invalid_value;
}
[[nodiscard]]
handle_t transfer() noexcept {
handle_t t = m_handle;
m_handle = resource_traits_t::invalid_value;
return t;
}
void release() {
if (is_valid()) {
resource_traits_t::release(m_handle);
m_handle = resource_traits_t::invalid_value;
}
}
~resource_wrapper() {
release();
}
};
template<typename resource_traits_t>
resource_wrapper(resource_traits_t) ->
resource_wrapper<resource_traits_t, void>;
template<typename resource_traits_t, typename arg_t>
resource_wrapper(resource_traits_t, arg_t&&) ->
resource_wrapper<
resource_traits_t,
std::conditional_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<arg_t>>, typename resource_traits_t::handle_t> == false,
std::remove_reference_t<arg_t>,
void
>
>;
template<typename resource_traits_t, typename releaser_t, typename handle_t = typename resource_traits_t::handle_t>
resource_wrapper(resource_traits_t, const handle_t&, releaser_t&&) ->
resource_wrapper<resource_traits_t, std::remove_reference_t<releaser_t>>;
}

View File

@ -1,625 +0,0 @@
#include "rsa_cipher.hpp"
#include <mutex>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include "resource_traits/openssl/bio.hpp"
#include "resource_traits/openssl/bignum.hpp"
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
#include <openssl/encoder.h>
#include <openssl/decoder.h>
#include "resource_traits/openssl/encoder_ctx.hpp"
#include "resource_traits/openssl/decoder_ctx.hpp"
#endif
#include "cp_converter.hpp"
#include "exceptions/overflow_exception.hpp"
#pragma comment(lib, "libcrypto")
#pragma comment(lib, "crypt32") // required by libcrypto.lib
#pragma comment(lib, "ws2_32") // required by libcrypto.lib
#define NKG_CURRENT_SOURCE_FILE() u8".\\common\\rsa_cipher.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
RSA* rsa_cipher::_read_private_key_from_bio(BIO* p_bio) {
resource_wrapper new_rsa
{ resource_traits::openssl::rsa{}, PEM_read_bio_RSAPrivateKey(p_bio, nullptr, nullptr, nullptr) };
if (new_rsa.is_valid()) {
return new_rsa.transfer();
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_read_bio_RSAPrivateKey failed.")
.push_hint(u8"Are you sure that you DO provide a valid RSA private key file?");
}
}
RSA* rsa_cipher::_read_public_key_pem_from_bio(BIO* p_bio) {
resource_wrapper new_rsa
{ resource_traits::openssl::rsa{}, PEM_read_bio_RSA_PUBKEY(p_bio, nullptr, nullptr, nullptr) };
if (new_rsa.is_valid()) {
return new_rsa.transfer();
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_read_bio_RSA_PUBKEY failed.")
.push_hint(u8"Are you sure that you DO provide a valid RSA public key file with PEM format?");
}
}
RSA* rsa_cipher::_read_public_key_pkcs1_from_bio(BIO* p_bio) {
resource_wrapper new_rsa
{ resource_traits::openssl::rsa{}, PEM_read_bio_RSAPublicKey(p_bio, nullptr, nullptr, nullptr) };
if (new_rsa.is_valid()) {
return new_rsa.transfer();
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_read_bio_RSAPublicKey failed.")
.push_hint(u8"Are you sure that you DO provide a valid RSA public key file with PKCS1 format?");
}
}
void rsa_cipher::_write_private_key_to_bio(RSA* p_rsa, BIO* p_bio) {
auto r = PEM_write_bio_RSAPrivateKey(p_bio, p_rsa, nullptr, nullptr, 0, nullptr, nullptr);
if (r == 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_write_bio_RSAPrivateKey failed.");
};
}
void rsa_cipher::_write_public_key_pem_to_bio(RSA* p_rsa, BIO* p_bio) {
auto r = PEM_write_bio_RSA_PUBKEY(p_bio, p_rsa);
if (r == 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_write_bio_RSA_PUBKEY failed.");
}
}
void rsa_cipher::_write_public_key_pkcs1_to_bio(RSA* p_rsa, BIO* p_bio) {
auto r = PEM_write_bio_RSAPublicKey(p_bio, p_rsa);
if (r == 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_write_bio_RSAPublicKey failed.");
}
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
[[nodiscard]]
EVP_PKEY* rsa_cipher::_read_private_key_from_bio(BIO* p_bio) {
resource_wrapper new_rsa{ resource_traits::openssl::evp_pkey{} };
resource_wrapper decoder_context
{ resource_traits::openssl::decoder_ctx{}, OSSL_DECODER_CTX_new_for_pkey(new_rsa.unsafe_addressof(), "PEM", "pkcs1", "RSA", OSSL_KEYMGMT_SELECT_PRIVATE_KEY, nullptr, nullptr) };
if (!decoder_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_DECODER_CTX_new_for_pkey failed.");
}
if (!OSSL_DECODER_from_bio(decoder_context.get(), p_bio)) { // 1 on success, 0 on failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_DECODER_from_bio failed.");
}
return new_rsa.transfer();
}
[[nodiscard]]
EVP_PKEY* rsa_cipher::_read_public_key_pem_from_bio(BIO* p_bio) {
resource_wrapper new_rsa{ resource_traits::openssl::evp_pkey{} };
resource_wrapper decoder_context
{ resource_traits::openssl::decoder_ctx{}, OSSL_DECODER_CTX_new_for_pkey(new_rsa.unsafe_addressof(), "PEM", "SubjectPublicKeyInfo", "RSA", OSSL_KEYMGMT_SELECT_PUBLIC_KEY, nullptr, nullptr) };
if (!decoder_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_DECODER_CTX_new_for_pkey failed.");
}
if (!OSSL_DECODER_from_bio(decoder_context.get(), p_bio)) { // 1 on success, 0 on failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_DECODER_from_bio failed.");
}
return new_rsa.transfer();
}
[[nodiscard]]
EVP_PKEY* rsa_cipher::_read_public_key_pkcs1_from_bio(BIO* p_bio) {
resource_wrapper new_rsa{ resource_traits::openssl::evp_pkey{} };
resource_wrapper decoder_context
{ resource_traits::openssl::decoder_ctx{}, OSSL_DECODER_CTX_new_for_pkey(new_rsa.unsafe_addressof(), "PEM", "pkcs1", "RSA", OSSL_KEYMGMT_SELECT_PUBLIC_KEY, nullptr, nullptr) };
if (!decoder_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_DECODER_CTX_new_for_pkey failed.");
}
if (!OSSL_DECODER_from_bio(decoder_context.get(), p_bio)) { // 1 on success, 0 on failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_DECODER_from_bio failed.");
}
return new_rsa.transfer();
}
void rsa_cipher::_write_private_key_to_bio(EVP_PKEY* p_rsa, BIO* p_bio) {
resource_wrapper encoder_context
{ resource_traits::openssl::encoder_ctx{}, OSSL_ENCODER_CTX_new_for_pkey(p_rsa, OSSL_KEYMGMT_SELECT_PRIVATE_KEY, "PEM", "pkcs1", nullptr) };
if (!encoder_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_CTX_new_for_pkey failed.");
}
if (!OSSL_ENCODER_to_bio(encoder_context.get(), p_bio)) { // 1 on success, 0 on failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_to_bio failed.");
}
}
void rsa_cipher::_write_public_key_pem_to_bio(EVP_PKEY* p_rsa, BIO* p_bio) {
resource_wrapper encoder_context
{ resource_traits::openssl::encoder_ctx{}, OSSL_ENCODER_CTX_new_for_pkey(p_rsa, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, "PEM", "SubjectPublicKeyInfo", nullptr) };
if (!encoder_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_CTX_new_for_pkey failed.");
}
if (!OSSL_ENCODER_to_bio(encoder_context.get(), p_bio)) { // 1 on success, 0 on failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_to_bio failed.");
}
}
void rsa_cipher::_write_public_key_pkcs1_to_bio(EVP_PKEY* p_rsa, BIO* p_bio) {
resource_wrapper encoder_context
{ resource_traits::openssl::encoder_ctx{}, OSSL_ENCODER_CTX_new_for_pkey(p_rsa, OSSL_KEYMGMT_SELECT_PUBLIC_KEY, "PEM", "pkcs1", nullptr) };
if (!encoder_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_CTX_new_for_pkey failed.");
}
if (!OSSL_ENCODER_to_bio(encoder_context.get(), p_bio)) { // 1 on success, 0 on failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_to_bio failed.");
}
}
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
rsa_cipher::rsa_cipher() = default;
[[nodiscard]]
size_t rsa_cipher::bits() const {
if (m_rsa.get()) {
#if (OPENSSL_VERSION_NUMBER & 0xfff00000) == 0x10000000 // openssl 1.0.x
return BN_num_bits(m_rsa->n);
#elif (OPENSSL_VERSION_NUMBER & 0xfff00000) == 0x10100000 // openssl 1.1.x
return RSA_bits(m_rsa.get());
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // openssl 3.x.x
return EVP_PKEY_get_bits(m_rsa.get());
#else
#error "rsa_cipher.cpp: uexpected OpenSSL version"
#endif
} else {
throw no_key_assigned_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"RSA key has not been assigned yet.");
}
}
void rsa_cipher::generate_key(int bits, unsigned int e) {
resource_wrapper bn_e{ resource_traits::openssl::bignum{}, BN_new() };
if (bn_e.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"BN_new failed.");
}
if (BN_set_word(bn_e.get(), e) == 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BN_set_word failed.");
}
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
resource_wrapper new_rsa{ resource_traits::openssl::rsa{}, RSA_new() };
if (!new_rsa.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_new failed.");
}
if (RSA_generate_key_ex(new_rsa.get(), bits, bn_e.get(), nullptr) == 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_generate_key_ex failed.");
}
m_rsa = std::move(new_rsa);
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr) };
if (!evp_pkey_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_new_id failed.");
}
if (EVP_PKEY_keygen_init(evp_pkey_context.get()) <= 0) { // 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_keygen_init failed.");
}
if (EVP_PKEY_CTX_set_rsa_keygen_bits(evp_pkey_context.get(), bits) <= 0) { // return a positive value for success and 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_set_rsa_keygen_bits failed.");
}
if (EVP_PKEY_CTX_set1_rsa_keygen_pubexp(evp_pkey_context.get(), bn_e.get()) <= 0) { // return a positive value for success and 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_set1_rsa_keygen_pubexp failed.");
}
resource_wrapper new_rsa{ resource_traits::openssl::evp_pkey{} };
if (EVP_PKEY_keygen(evp_pkey_context.get(), new_rsa.unsafe_addressof()) <= 0) { // 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_keygen failed.");
}
m_rsa = std::move(new_rsa);
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
}
void rsa_cipher::export_private_key_file(std::wstring_view file_path) const {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "w")};
if (bio_file.is_valid()) {
_write_private_key_to_bio(m_rsa.get(), bio_file.get());
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new_file failed.");
}
}
void rsa_cipher::export_private_key_file(const std::filesystem::path& file_path) const {
export_private_key_file(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::export_public_key_file_pem(std::wstring_view file_path) const {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "w")};
if (bio_file.is_valid()) {
_write_public_key_pem_to_bio(m_rsa.get(), bio_file.get());
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new_file failed.");
}
}
void rsa_cipher::export_public_key_file_pem(const std::filesystem::path& file_path) const {
export_public_key_file_pem(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::export_public_key_file_pkcs1(std::wstring_view file_path) const {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "w")};
if (bio_file.is_valid()) {
_write_public_key_pkcs1_to_bio(m_rsa.get(), bio_file.get());
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new_file failed.");
}
}
void rsa_cipher::export_public_key_file_pkcs1(const std::filesystem::path& file_path) const {
export_public_key_file_pkcs1(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::import_private_key_file(std::wstring_view file_path) {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "r") };
if (bio_file.is_valid()) {
m_rsa.set(_read_private_key_from_bio(bio_file.get()));
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new_file failed.");
}
}
void rsa_cipher::import_private_key_file(const std::filesystem::path& file_path) {
import_private_key_file(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::import_public_key_file_pem(std::wstring_view file_path) {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "r") };
if (bio_file.is_valid()) {
m_rsa.set(_read_public_key_pem_from_bio(bio_file.get()));
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new_file failed.");
}
}
void rsa_cipher::import_public_key_file_pem(const std::filesystem::path& file_path) {
import_public_key_file_pem(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::import_public_key_file_pkcs1(std::wstring_view file_path) {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "r") };
if (bio_file.is_valid()) {
m_rsa.set(_read_public_key_pkcs1_from_bio(bio_file.get()));
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new_file failed.");
}
}
void rsa_cipher::import_public_key_file_pkcs1(const std::filesystem::path& file_path) {
import_public_key_file_pkcs1(static_cast<std::wstring_view>(file_path.native()));
}
[[nodiscard]]
std::string rsa_cipher::export_private_key_string() const {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid()) {
_write_private_key_to_bio(m_rsa.get(), bio_memory.get());
const char* pch = nullptr;
long lch = BIO_get_mem_data(bio_memory.get(), &pch);
return std::string(pch, lch);
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
}
[[nodiscard]]
std::string rsa_cipher::export_public_key_string_pem() const {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid()) {
_write_public_key_pem_to_bio(m_rsa.get(), bio_memory.get());
const char* pch = nullptr;
long lch = BIO_get_mem_data(bio_memory.get(), &pch);
return std::string(pch, lch);
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
}
[[nodiscard]]
std::string rsa_cipher::export_public_key_string_pkcs1() const {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid()) {
_write_public_key_pkcs1_to_bio(m_rsa.get(), bio_memory.get());
const char* pch = nullptr;
long lch = BIO_get_mem_data(bio_memory.get(), &pch);
return std::string(pch, lch);
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
}
void rsa_cipher::import_private_key_string(std::string_view key_string) {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
if (BIO_puts(bio_memory.get(), key_string.data()) <= 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_puts failed.");
}
m_rsa.set(_read_private_key_from_bio(bio_memory.get()));
}
void rsa_cipher::import_public_key_string_pem(std::string_view key_string) {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
if (BIO_puts(bio_memory.get(), key_string.data()) <= 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_puts failed.");
}
m_rsa.set(_read_public_key_pem_from_bio(bio_memory.get()));
}
void rsa_cipher::import_public_key_string_pkcs1(std::string_view key_string) {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
if (BIO_puts(bio_memory.get(), key_string.data()) <= 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_puts failed.");
}
m_rsa.set(_read_public_key_pkcs1_from_bio(bio_memory.get()));
}
size_t rsa_cipher::public_encrypt(const void* plaintext, size_t plaintext_size, void* ciphertext, int padding) const {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (plaintext_size <= INT_MAX) {
int bytes_written =
RSA_public_encrypt(static_cast<int>(plaintext_size), reinterpret_cast<const unsigned char*>(plaintext), reinterpret_cast<unsigned char*>(ciphertext), m_rsa.get(), padding);
if (bytes_written != -1) {
return bytes_written;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_public_encrypt failed.");
}
} else {
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"plaintext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
if (!evp_pkey_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_new failed.");
}
if (EVP_PKEY_encrypt_init(evp_pkey_context.get()) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_encrypt_init failed.");
}
if (EVP_PKEY_CTX_set_rsa_padding(evp_pkey_context.get(), padding) <= 0) { // return a positive value for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_set_rsa_padding failed.");
}
size_t ciphertext_size = 0;
if (EVP_PKEY_encrypt(evp_pkey_context.get(), nullptr, &ciphertext_size, reinterpret_cast<const unsigned char*>(plaintext), plaintext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_encrypt failed.");
}
if (EVP_PKEY_encrypt(evp_pkey_context.get(), reinterpret_cast<unsigned char*>(ciphertext), &ciphertext_size, reinterpret_cast<const unsigned char*>(plaintext), plaintext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_encrypt failed.");
}
return ciphertext_size;
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
}
size_t rsa_cipher::private_encrypt(const void* plaintext, size_t plaintext_size, void* ciphertext, int padding) const {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (plaintext_size <= INT_MAX) {
int bytes_written =
RSA_private_encrypt(static_cast<int>(plaintext_size), reinterpret_cast<const unsigned char*>(plaintext), reinterpret_cast<unsigned char*>(ciphertext), m_rsa.get(), padding);
if (bytes_written != -1) {
return bytes_written;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_public_encrypt failed.");
}
} else {
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"plaintext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
if (!evp_pkey_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_new failed.");
}
if (EVP_PKEY_sign_init(evp_pkey_context.get()) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_sign_init failed.");
}
if (EVP_PKEY_CTX_set_rsa_padding(evp_pkey_context.get(), padding) <= 0) { // return a positive value for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_set_rsa_padding failed.");
}
size_t ciphertext_size = 0;
if (EVP_PKEY_sign(evp_pkey_context.get(), nullptr, &ciphertext_size, reinterpret_cast<const unsigned char*>(plaintext), plaintext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_sign failed.");
}
if (EVP_PKEY_sign(evp_pkey_context.get(), reinterpret_cast<unsigned char*>(ciphertext), &ciphertext_size, reinterpret_cast<const unsigned char*>(plaintext), plaintext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_sign failed.");
}
return ciphertext_size;
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
}
size_t rsa_cipher::public_decrypt(const void* ciphertext, size_t ciphertext_size, void* plaintext, int padding) const {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (ciphertext_size <= INT_MAX) {
int bytes_written =
RSA_public_decrypt(static_cast<int>(ciphertext_size), reinterpret_cast<const unsigned char*>(ciphertext), reinterpret_cast<unsigned char*>(plaintext), m_rsa.get(), padding);
if (bytes_written != -1) {
return bytes_written;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_public_decrypt failed.")
.push_hint(u8"Are your sure you DO provide a correct public key?");
}
} else {
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"ciphertext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
if (!evp_pkey_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_new failed.");
}
if (EVP_PKEY_verify_recover_init(evp_pkey_context.get())) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_verify_recover_init failed.");
}
if (EVP_PKEY_CTX_set_rsa_padding(evp_pkey_context.get(), padding) <= 0) { // return a positive value for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_set_rsa_padding failed.");
}
size_t plaintext_size = 0;
if (EVP_PKEY_verify_recover(evp_pkey_context.get(), nullptr, &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_verify_recover failed.")
.push_hint(u8"Are your sure you DO provide a correct public key?");
}
if (EVP_PKEY_verify_recover(evp_pkey_context.get(), reinterpret_cast<unsigned char*>(plaintext), &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_verify_recover failed.");
}
return plaintext_size;
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
}
size_t rsa_cipher::private_decrypt(const void* ciphertext, size_t ciphertext_size, void* plaintext, int padding) const {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (ciphertext_size <= INT_MAX) {
int bytes_written =
RSA_private_decrypt(static_cast<int>(ciphertext_size), reinterpret_cast<const unsigned char*>(ciphertext), reinterpret_cast<unsigned char*>(plaintext), m_rsa.get(), padding);
if (bytes_written != -1) {
return bytes_written;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_public_decrypt failed.")
.push_hint(u8"Are your sure you DO provide a correct private key?");
}
} else {
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"ciphertext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
if (!evp_pkey_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_new failed.");
}
if (EVP_PKEY_decrypt_init(evp_pkey_context.get()) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_decrypt_init failed.");
}
if (EVP_PKEY_CTX_set_rsa_padding(evp_pkey_context.get(), padding) <= 0) { // return a positive value for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_CTX_set_rsa_padding failed.");
}
size_t plaintext_size = 0;
if (EVP_PKEY_decrypt(evp_pkey_context.get(), nullptr, &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_decrypt failed.")
.push_hint(u8"Are your sure you DO provide a correct private key?");
}
if (EVP_PKEY_decrypt(evp_pkey_context.get(), reinterpret_cast<unsigned char*>(plaintext), &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_decrypt failed.");
}
return plaintext_size;
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
}
rsa_cipher::backend_error::backend_error(std::string_view file, int line, std::string_view message) noexcept:
::nkg::exception::exception(file, line, message), m_error_code(0) {}
rsa_cipher::backend_error::backend_error(std::string_view file, int line, error_code_t openssl_errno, std::string_view message) noexcept:
::nkg::exception::exception(file, line, message), m_error_code(openssl_errno)
{
static std::once_flag onceflag_load_crypto_strings;
std::call_once(onceflag_load_crypto_strings, []() { ERR_load_crypto_strings(); });
m_error_string = ERR_reason_error_string(m_error_code);
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -1,161 +0,0 @@
#pragma once
#include <string>
#include <filesystem>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include "resource_wrapper.hpp"
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
#include "resource_traits/openssl/rsa.hpp"
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
#include "resource_traits/openssl/evp_pkey_ctx.hpp"
#include "resource_traits/openssl/evp_pkey.hpp"
#else
#error "rsa_cipher.hpp: Unexpected OpenSSL version."
#endif
#include "exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\common\\rsa_cipher.hpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
class rsa_cipher {
public:
class backend_error;
class no_key_assigned_error;
private:
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
resource_wrapper<resource_traits::openssl::rsa> m_rsa;
[[nodiscard]]
static RSA* _read_private_key_from_bio(BIO* p_bio);
[[nodiscard]]
static RSA* _read_public_key_pem_from_bio(BIO* p_bio);
[[nodiscard]]
static RSA* _read_public_key_pkcs1_from_bio(BIO* p_bio);
static void _write_private_key_to_bio(RSA* p_rsa, BIO* p_bio);
static void _write_public_key_pem_to_bio(RSA* p_rsa, BIO* p_bio);
static void _write_public_key_pkcs1_to_bio(RSA* p_rsa, BIO* p_bio);
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper<resource_traits::openssl::evp_pkey> m_rsa;
[[nodiscard]]
static EVP_PKEY* _read_private_key_from_bio(BIO* p_bio);
[[nodiscard]]
static EVP_PKEY* _read_public_key_pem_from_bio(BIO* p_bio);
[[nodiscard]]
static EVP_PKEY* _read_public_key_pkcs1_from_bio(BIO* p_bio);
static void _write_private_key_to_bio(EVP_PKEY* p_rsa, BIO* p_bio);
static void _write_public_key_pem_to_bio(EVP_PKEY* p_rsa, BIO* p_bio);
static void _write_public_key_pkcs1_to_bio(EVP_PKEY* p_rsa, BIO* p_bio);
#else
#error "rsa_cipher.hpp: Unexpected OpenSSL version."
#endif
public:
rsa_cipher();
[[nodiscard]]
size_t bits() const;
void generate_key(int bits, unsigned int e = RSA_F4);
void export_private_key_file(std::wstring_view file_path) const;
void export_private_key_file(const std::filesystem::path& file_path) const;
void export_public_key_file_pem(std::wstring_view file_path) const;
void export_public_key_file_pem(const std::filesystem::path& file_path) const;
void export_public_key_file_pkcs1(std::wstring_view file_path) const;
void export_public_key_file_pkcs1(const std::filesystem::path& file_path) const;
void import_private_key_file(std::wstring_view file_path);
void import_private_key_file(const std::filesystem::path& file_path);
void import_public_key_file_pem(std::wstring_view file_path);
void import_public_key_file_pem(const std::filesystem::path& file_path);
void import_public_key_file_pkcs1(std::wstring_view file_path);
void import_public_key_file_pkcs1(const std::filesystem::path& file_path);
[[nodiscard]]
std::string export_private_key_string() const;
[[nodiscard]]
std::string export_public_key_string_pem() const;
[[nodiscard]]
std::string export_public_key_string_pkcs1() const;
void import_private_key_string(std::string_view key_string);
void import_public_key_string_pem(std::string_view key_string);
void import_public_key_string_pkcs1(std::string_view key_string);
size_t public_encrypt(const void* plaintext, size_t plaintext_size, void* ciphertext, int padding) const;
size_t private_encrypt(const void* plaintext, size_t plaintext_size, void* ciphertext, int padding) const;
size_t public_decrypt(const void* ciphertext, size_t ciphertext_size, void* plaintext, int padding) const;
size_t private_decrypt(const void* ciphertext, size_t ciphertext_size, void* plaintext, int padding) const;
};
class rsa_cipher::backend_error : public ::nkg::exception {
public:
using error_code_t = decltype(ERR_get_error());
private:
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, std::string_view message) noexcept;
backend_error(std::string_view file, int line, error_code_t openssl_errno, std::string_view message) noexcept;
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return m_error_code != 0;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
if (error_code_exists()) { return m_error_code; } else { trap_then_terminate(); }
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
if (error_code_exists()) { return m_error_string; } else { trap_then_terminate(); }
}
};
class rsa_cipher::no_key_assigned_error : public ::nkg::exception {
using ::nkg::exception::exception;
};
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

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.

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软件中填入 __激活码__ 即可完成离线激活。

View File

@ -1,60 +0,0 @@
# navicat-keygen for windows - How to build?
[中文版](how-to-build.zh-CN.md)
## 1. Prerequisites
1. Please make sure that you have __Visual Studio 2022__ or the higher. Because this is a VS2022 project.
2. Please make sure you have installed `vcpkg` and the following libraries:
* `fmt:x64-windows-static`
* `fmt:x86-windows-static`
* `openssl:x64-windows-static`
* `openssl:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `unicorn:x64-windows-static`
* `unicorn:x86-windows-static`
is installed.
You can install them by:
```console
$ vcpkg install fmt:x64-windows-static
$ vcpkg install fmt:x86-windows-static
$ vcpkg install openssl:x64-windows-static
$ vcpkg install openssl:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install unicorn:x64-windows-static
$ vcpkg install unicorn: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.

View File

@ -1,54 +0,0 @@
# navicat-keygen for windows - 如何编译?
## 1. 前提条件
1. 请确保你有 __Visual Studio 2022__ 或者更高版本。因为这是一个VS2022项目。
2. 请确保你安装了 `vcpkg` 以及下面几个库:
* `fmt:x64-windows-static`
* `fmt:x86-windows-static`
* `openssl:x64-windows-static`
* `openssl:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `unicorn:x64-windows-static`
* `unicorn:x86-windows-static`
你可以通过下面的命令来安装它们:
```console
$ vcpkg install fmt:x64-windows-static
$ vcpkg install fmt:x86-windows-static
$ vcpkg install openssl:x64-windows-static
$ vcpkg install openssl:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install unicorn:x64-windows-static
$ vcpkg install unicorn: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。

View File

@ -1,196 +0,0 @@
# navicat-keygen for windows - How to use?
[中文版](how-to-use.windows.zh-CN.md)
1. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `libcc.dll`.
```
navicat-patcher.exe [-dry-run] <Navicat Install Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]` Run patcher without applying any patches.
__This parameter is optional.__
* `<Navicat Install 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 16"
```
It has been tested on __Navicat Premium 16.0.7 English version__. The following is an example of output.
```
***************************************************
* navicat-patcher by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[+] Try to open libcc.dll ... OK!
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x00000001837759f0
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x0000000181fa52d0
[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x0000000183439bd0
[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAvxaFFjTE6hi80nhjgfFMM3yPer122OIWIbbumFIuAOcCF6D3
PnRHBdP9IqB99K6Nv6vKK3Jf0Y+dc5ETrg0l0AHYq+dTFTiWusHuRMx6xFjWzO96
7mFmJq6P28dUucKnr6yG1TQeZaq+mHh2DNEnNEYgV7cLVT1unUmMOL/PBh/eCcaJ
8hQNTQafQQknzCnAKC89v33y+rKInJNy9B+zSB0BGCz+eS8MKf6zc78JMSOnF2uj
NK+QEwaYw8lAbJve1F+rCQS0mbm0QvHhZYZrblVHI5l/8LkX5qBtKw7duUhXHxmO
fQieF23bBk9HDp5uQUGsdbKX6ZWitn/h926xyQIDAQABAoIBAQCHXxDRdni5zuSV
xivYdnUhVHDg5zA23ZQINmw5BJ8KjJzy2FnPqNhXzKJb0Y7ptG8/BhinRtOSxkcp
A/IJL89F2MkCn1JAimJd091UZ/fg+X7SmCVikyWm6auIa2IeZ0QcNAEhMVcHdzqn
EU+wLMu1QKjQ+x/QN0ERtHTeDyQ+lUNB+bvAjx3LHN9Zh8weVBHHtwDoyyZDdJPw
NWgpgcW+uYzlT66uh7LPPaRsEZgAkPIkhzZnwmugXdhlWxtYHKTEfe5gCqubQICc
I/x1yBP1EZFm6qBQD4/49775ZbXwxgaWvBXG+Aah9x8JYtVUS4MgrAiC4a8NQqFp
nwKVjUIBAoGBAOWsj9GGb2KYbfLzJNRrSxhs4TUBfpHteKSm2pL92NAbIOjssNhL
hLY3gBFX2RnYmoGD6YT84JNykuAictgAd5GwvLIbaVF9l7MQn8APRbe2CzQ+/494
9hpn33MZOBNd3I+a5+2qoFbXI04loyYDJkkeOqbwZzJjs7k9HmZMNwY5AoGBANT9
tRFWFDvA0pPgGoHhzlsAUAmrbSfCPkhrRXpE9fgl3VnV+NRtjCf9NhJt0uaIokZ5
oSf+jClcwU8N4EvGxMBaCHTqBzgc4dLPWpMAhPoMjjv1Oyug2iBcuTasHVP+Jdgq
CaNzpXOuq4upaaNrq+QMsI6O9wA/zWhWPmnYQYgRAoGAUk56471noU+65zvXUQB6
UvCB7Hrynt0ZRPg+kDrEPh/atV5NKdY2Yw6UqKJwvOBwzkU1pGDzIiQHGqd9vIa+
Usmhdbp5DakSeitU9IEEnQdyEHEbKJFSsLfUzeyVuesDJbt/rh5dg4Fpt5GpW+/5
Am8A2d6BPP+Z4qJSiJp7hZECgYEAy64TCZEXqEytE1yr/KjDfaK+54BX0j2e8gIj
XtmznqoXE2Hboslfzp4Gp3j+xhbDmEGYK3bw8l0RP1g1tkFOxeNTUvq6DJ8SFVbV
dt54S+bV3eCVxRL9hRUmyXGuWjQgXKdWsEhXYFkZE2Xe77h3mI3KCYoOCt74v146
MV3szQECgYEAozTO7Wuum+VMKIY35hmHMjUiYmLl3EXWwMBT2VSsk8Siu0XoH0yd
KoxsLDUBMS8sWKCZhFwU+Fx8UZjfo+xE3H4UTyVsw5EDpB9gSud928gNADwxTKor
3s4jnUzb4XRQ0qN2jXzdNuqXNV1ozeqajbM2oSZqbSnWSs5g6DpIs1Q=
-----END RSA PRIVATE KEY-----
[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\source\repos\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
2. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key 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 Private Key File>`: The full path or relative path to an RSA-2048 private key file. The private key must be in PEM format.
__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.
```
***************************************************
* navicat-keygen by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[*] 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)> 0
[*] Input major version number:
(range: 11 ~ 16, default: 16)> 16
[*] Serial number:
NAVL-GFKA-T5SR-ZFTK
[*] 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: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] 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__.
3. __Disconnect your network__ and open Navicat. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
4. Generally online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
5. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
CpgnfbIJGmAcxCuo/pAb8EeoS0audZn2NNemg6c3NPK/dWgb343IZQrFwoBZY6lpxE4Fq1BoNmCM75P03XpiXQ+hErcvFWk6iQPDCk/d4msf/AoprIqAMpXFoFLkeP0G93UIIEeBsUej8SrxdDgQDM585iPok5fUW+fTDCD1VICr7DBdL3c/69IxeIgiOQSuImdIQiM3/EOfDiFbAJL9vHW5LxFT8jj+8RPXehwPTBphpInmGdzxVZUZJwAGlXt7orrRbzafdeBjz6MnTajTcJP3SS2dBCiR33UScnyxYGEXdzv7+QLScTmCvI7gqg3Z8DMhroKMoHmy1AvC16FKVw==
[*] Request Info:
{"K":"NAVLGFKAT5SRZFTK", "DI":"7D48FCBD093C778879A1", "P":"WIN"}
[*] Response Info:
{"K":"NAVLGFKAT5SRZFTK","DI":"7D48FCBD093C778879A1","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644387294}
[*] Activation Code:
vwLGmQIWg/DtzHMcaKCDHAjTcBNbTo2VmNllphUSUMgGjgvL6v82ue+GqXB6M/qn48Rj4D4Joqqisr6UwMSclNmQxOQz4RftEpLtG6KBjDo4LM71qn9R/jWoZV5EoHPQkX5gzhO/D7GammrRGn2MV+zI6dJ4c4SBFNnNyjAeEqNzinrQwjB7lUVTlpHEe/SMrdCsGliPZQ/X+5ASbEsq3D8PZsjysJv98MIJrZvdTdznrRe8JzYP+8sbIPQMIX1UDmdyDpbpSl45N92OhO4htz1kFjUEfnrwY0GMOhdYHv/PfMI7RiQzkRyY7pLvX7muJ4dkA+CmMmwew3gy3MWjig==
```
6. 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.

View File

@ -1,194 +0,0 @@
# navicat-keygen for windows - 如何使用这个注册机?
1. 使用`navicat-patcher.exe`替换掉`navicat.exe`和`libcc.dll`里的Navicat激活公钥。
```
navicat-patcher.exe [-dry-run] <Navicat Install Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]`: 运行patcher但不对Navicat程序做任何修改。
__这个参数是可选的。__
* `<Navicat Install 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 16"
```
__Navicat Premium 16.0.7 英文版__ 已通过测试。下面将是一份样例输出:
```
***************************************************
* navicat-patcher by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[+] Try to open libcc.dll ... OK!
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x00000001837759f0
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x0000000181fa52d0
[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x0000000183439bd0
[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAvxaFFjTE6hi80nhjgfFMM3yPer122OIWIbbumFIuAOcCF6D3
PnRHBdP9IqB99K6Nv6vKK3Jf0Y+dc5ETrg0l0AHYq+dTFTiWusHuRMx6xFjWzO96
7mFmJq6P28dUucKnr6yG1TQeZaq+mHh2DNEnNEYgV7cLVT1unUmMOL/PBh/eCcaJ
8hQNTQafQQknzCnAKC89v33y+rKInJNy9B+zSB0BGCz+eS8MKf6zc78JMSOnF2uj
NK+QEwaYw8lAbJve1F+rCQS0mbm0QvHhZYZrblVHI5l/8LkX5qBtKw7duUhXHxmO
fQieF23bBk9HDp5uQUGsdbKX6ZWitn/h926xyQIDAQABAoIBAQCHXxDRdni5zuSV
xivYdnUhVHDg5zA23ZQINmw5BJ8KjJzy2FnPqNhXzKJb0Y7ptG8/BhinRtOSxkcp
A/IJL89F2MkCn1JAimJd091UZ/fg+X7SmCVikyWm6auIa2IeZ0QcNAEhMVcHdzqn
EU+wLMu1QKjQ+x/QN0ERtHTeDyQ+lUNB+bvAjx3LHN9Zh8weVBHHtwDoyyZDdJPw
NWgpgcW+uYzlT66uh7LPPaRsEZgAkPIkhzZnwmugXdhlWxtYHKTEfe5gCqubQICc
I/x1yBP1EZFm6qBQD4/49775ZbXwxgaWvBXG+Aah9x8JYtVUS4MgrAiC4a8NQqFp
nwKVjUIBAoGBAOWsj9GGb2KYbfLzJNRrSxhs4TUBfpHteKSm2pL92NAbIOjssNhL
hLY3gBFX2RnYmoGD6YT84JNykuAictgAd5GwvLIbaVF9l7MQn8APRbe2CzQ+/494
9hpn33MZOBNd3I+a5+2qoFbXI04loyYDJkkeOqbwZzJjs7k9HmZMNwY5AoGBANT9
tRFWFDvA0pPgGoHhzlsAUAmrbSfCPkhrRXpE9fgl3VnV+NRtjCf9NhJt0uaIokZ5
oSf+jClcwU8N4EvGxMBaCHTqBzgc4dLPWpMAhPoMjjv1Oyug2iBcuTasHVP+Jdgq
CaNzpXOuq4upaaNrq+QMsI6O9wA/zWhWPmnYQYgRAoGAUk56471noU+65zvXUQB6
UvCB7Hrynt0ZRPg+kDrEPh/atV5NKdY2Yw6UqKJwvOBwzkU1pGDzIiQHGqd9vIa+
Usmhdbp5DakSeitU9IEEnQdyEHEbKJFSsLfUzeyVuesDJbt/rh5dg4Fpt5GpW+/5
Am8A2d6BPP+Z4qJSiJp7hZECgYEAy64TCZEXqEytE1yr/KjDfaK+54BX0j2e8gIj
XtmznqoXE2Hboslfzp4Gp3j+xhbDmEGYK3bw8l0RP1g1tkFOxeNTUvq6DJ8SFVbV
dt54S+bV3eCVxRL9hRUmyXGuWjQgXKdWsEhXYFkZE2Xe77h3mI3KCYoOCt74v146
MV3szQECgYEAozTO7Wuum+VMKIY35hmHMjUiYmLl3EXWwMBT2VSsk8Siu0XoH0yd
KoxsLDUBMS8sWKCZhFwU+Fx8UZjfo+xE3H4UTyVsw5EDpB9gSud928gNADwxTKor
3s4jnUzb4XRQ0qN2jXzdNuqXNV1ozeqajbM2oSZqbSnWSs5g6DpIs1Q=
-----END RSA PRIVATE KEY-----
[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\source\repos\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
2. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key 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 Private Key File>`: RSA-2048私钥文件的完整路径或相对路径。私钥必须是PEM格式的。
__这个参数必须指定。__
__例如(在cmd.exe中)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号。
```
***************************************************
* navicat-keygen by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[*] 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)> 0
[*] Input major version number:
(range: 11 ~ 16, default: 16)> 16
[*] Serial number:
NAVL-GFKA-T5SR-ZFTK
[*] Your name:
```
你可以使用这个序列号暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
3. __断开网络__ 并打开Navicat。找到`注册`窗口并填入keygen给你的序列号。然后点击`激活`按钮。
4. 一般来说在线激活肯定会失败这时候Navicat会询问你是否`手动激活`,直接选吧。
5. 在`手动激活`窗口你会得到一个请求码复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
CpgnfbIJGmAcxCuo/pAb8EeoS0audZn2NNemg6c3NPK/dWgb343IZQrFwoBZY6lpxE4Fq1BoNmCM75P03XpiXQ+hErcvFWk6iQPDCk/d4msf/AoprIqAMpXFoFLkeP0G93UIIEeBsUej8SrxdDgQDM585iPok5fUW+fTDCD1VICr7DBdL3c/69IxeIgiOQSuImdIQiM3/EOfDiFbAJL9vHW5LxFT8jj+8RPXehwPTBphpInmGdzxVZUZJwAGlXt7orrRbzafdeBjz6MnTajTcJP3SS2dBCiR33UScnyxYGEXdzv7+QLScTmCvI7gqg3Z8DMhroKMoHmy1AvC16FKVw==
[*] Request Info:
{"K":"NAVLGFKAT5SRZFTK", "DI":"7D48FCBD093C778879A1", "P":"WIN"}
[*] Response Info:
{"K":"NAVLGFKAT5SRZFTK","DI":"7D48FCBD093C778879A1","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644387294}
[*] Activation Code:
vwLGmQIWg/DtzHMcaKCDHAjTcBNbTo2VmNllphUSUMgGjgvL6v82ue+GqXB6M/qn48Rj4D4Joqqisr6UwMSclNmQxOQz4RftEpLtG6KBjDo4LM71qn9R/jWoZV5EoHPQkX5gzhO/D7GammrRGn2MV+zI6dJ4c4SBFNnNyjAeEqNzinrQwjB7lUVTlpHEe/SMrdCsGliPZQ/X+5ASbEsq3D8PZsjysJv98MIJrZvdTdznrRe8JzYP+8sbIPQMIX1UDmdyDpbpSl45N92OhO4htz1kFjUEfnrwY0GMOhdYHv/PfMI7RiQzkRyY7pLvX7muJ4dkA+CmMmwew3gy3MWjig==
```
6. 如果不出意外你会得到一个看似用Base64编码的激活码。直接复制它并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。

188
example/navicat-patcher.txt Normal file
View File

@ -0,0 +1,188 @@
**********************************************************
* Navicat Patcher (macOS) by @DoubleLabyrinth *
* Version: 5.0 *
**********************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open "Contents/MacOS/Navicat Premium" ... Ok!
[+] Try to open "Contents/Frameworks/libcc-premium.dylib" ... Ok!
[-] PatchSolution0 ...... Omitted.
[-] PatchSolution1 ...... Omitted.
[-] PatchSolution2 ...... Omitted.
[+] PatchSolution3 ...... Ready to apply.
fnGenerateKeyA RVA = 0x000000000116c3b8
fnGenerateKeyB RVA = 0x00000000011788d2
std::string::append(const char*, size_t) RVA = 0x0000000001848974
[*] Your Navicat version: 15.0.4
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA4CF6I7Tcrll2LPW7XwH0WRq0I8uIonHa81zUaFXCGMzsfy79
R9zrG5JdvLv0Q2LXqIESZBaoBaJI2rS9wcG9BklAcuSL6OA8g9iDbr9QRJeqvtZg
pYnmp85qfZNoTp+rKQOKMZ/i4JaYQKcc9ZcZEXaUysn8CFIUAoKqqMOtyiggpuD5
tTvWni+HrHNoBQFm+ro2h8m6wexe0GLh9M81ljkGOyCuaOKkCq4TPUnH3umk15WI
N2XhDGYYwFlPQIPGKzHFJrTegC9PsBTAoYjzqJ9PQK6GIA3DhgdS3WR/pun3AKmn
WOwvUgRG27qZtNY5Fa4JzB/TqiFGbsaKwKjWlQIDAQABAoIBABY0muJAwAByEpg/
vFGcYvYVBDXrq1zUxOmJj+3KWVGVs/Sh1iwxggWYSbsyL/AhMdaa+xR5fioYuvkY
IRi6Nh0SUtVPOWFYHga+A7+MKsqw8BS6LpcYA4cqlzhby2DGxvFoTV+/RH4VzX3S
ULcwQiaNxg4VVugIIb1h7sCLqoM1qQI6Ct2uzfkE4pwwWR2XO8m3mMTRe9tTfv2H
hnhc7QNuQEnz4fDYPF+/7P48eJoB/w+JPcN4JH9y/n47D2paGRYh1XdxlvHl8Bqu
9NuhfLhcWqZ306RIUJejudoYkPuW01ncgbUqI/Vs3wklZZRcM9ISzgLiBgT1jBmd
aQyAO/0CgYEA/jFsZIWOE8hddMXvGlBOtl0xVLYujVknqs6QDStG+JM6p9Q/+6/x
Mh5fTz9DauAJZEySw0Og2wO0yJvfHVigRlomAsEgCrAhNVT+bYokWeyECxmU/IFL
ndObUqxBxRS9ch/rxpVnShq4kPZQ/5G/0UibSBEnpPsoX1EMApSRnKsCgYEA4blY
yHPIRQfHwjC4X+xvIuqZdjS3QyQcpwjcVUjTm6l71jZ0W1LH10BQoPmDCb8FHR3T
SY6QY8SpWd9C0FjTtg8lj3xKBNc8RZ9LLMjXM4GiGzwESDTRzgNQTbZsD19cJjnQ
JlN5LkCHRERByqRWi9OX8CX5IejoYWmbCv6o2b8CgYEA9eeKHJS3JZwoDNeOv74A
55qwJms4DbW6EhtSb+r19XM4wzMp0qoag4muWlOxPKsPauBI+m1qJ3YmZgukhBdA
tc5wByodfTl2ZsmaeQ2yrOuJsdNFtiC+rigPkqLh3W569vS6epn+GkpPUq13HkY5
cpTy43z1BT2TiOI25Cgl1ZECgYB9SJmdkJ3sqpfWEaKUIy/AKoQI1tOM4YNBtqpM
b8J7mINSbyD/+x9OOrVF05dGlo5pDb/TCNzdcy8n4cI8z8CaQSfwzuRqcWhToEli
Twsa3G20PgiGZ0K33KD6sTCjC6Oi193PF++fm1M4scXuim4657NiKEFx78rjHnFe
ld/0EwKBgHSZp9mLN1qifNUygw/TOWZ4Ihwhqeh/4agTbSSLuElT3M0d2dXighSn
efP6t0EAInY78FtWPNFgZxO4Y/II+SSI74vyIYmgyvM31uxaiifPSkw6eoeL5JAP
rWYcPk4BfJn30HN0xwHG/ddbp6TOPZkoFZu5rwzBCFtp2L2YjJdI
-----END RSA PRIVATE KEY-----
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4CF6I7Tcrll2LPW7XwH0
WRq0I8uIonHa81zUaFXCGMzsfy79R9zrG5JdvLv0Q2LXqIESZBaoBaJI2rS9wcG9
BklAcuSL6OA8g9iDbr9QRJeqvtZgpYnmp85qfZNoTp+rKQOKMZ/i4JaYQKcc9ZcZ
EXaUysn8CFIUAoKqqMOtyiggpuD5tTvWni+HrHNoBQFm+ro2h8m6wexe0GLh9M81
ljkGOyCuaOKkCq4TPUnH3umk15WIN2XhDGYYwFlPQIPGKzHFJrTegC9PsBTAoYjz
qJ9PQK6GIA3DhgdS3WR/pun3AKmnWOwvUgRG27qZtNY5Fa4JzB/TqiFGbsaKwKjW
lQIDAQAB
-----END PUBLIC KEY-----
**************************************************************
* PatchSolution3 *
**************************************************************
[*] Previous:
+0x000000000116c3b0 55 48 89 e5 41 57 41 56 UH..AWAV
+0x000000000116c3c0 41 55 41 54 53 48 83 ec 48 48 89 7d 98 b0 01 88 AUATSH..HH.}....
+0x000000000116c3d0 45 d5 88 45 d6 c6 45 d7 00 48 8d 35 30 7b 2a 01 E..E..E..H.50{*.
+0x000000000116c3e0 48 8d 5d a0 48 89 df e8 e0 52 01 00 48 89 df be H.].H....R..H...
+0x000000000116c3f0 6b 00 00 00 e8 c9 c5 6d 00 e8 62 53 01 00 88 45 k......m..bS...E
+0x000000000116c400 d6 e8 d4 53 01 00 88 45 d7 e8 46 54 01 00 88 45 ...S...E..FT...E
+0x000000000116c410 d5 f6 45 d7 01 75 3f f6 45 d5 01 0f 85 12 01 00 ..E..u?.E.......
+0x000000000116c420 00 f6 45 d6 01 0f 84 a7 70 00 00 48 8d 35 ad 82 ..E.....p..H.5..
+0x000000000116c430 2f 01 48 8d 7d b8 e8 91 52 01 00 0f b6 55 b8 89 /.H.}...R....U..
+0x000000000116c440 d0 24 01 0f 84 5f 02 00 00 48 8b 75 c8 48 8b 55 .$..._...H.u.H.U
+0x000000000116c450 c0 e9 59 02 00 00 48 8d 35 70 82 2f 01 48 8d 7d ..Y...H.5p./.H.}
+0x000000000116c460 a0 e8 08 c5 6d 00 48 8d 7d a0 be 61 00 00 00 e8 ....m.H.}..a....
+0x000000000116c470 4e c5 6d 00 48 8d 35 4e 87 2f 01 48 8d 7d a0 e8 N.m.H.5N./.H.}..
+0x000000000116c480 ea c4 6d 00 48 8d 35 47 87 2f 01 48 8d 7d a0 e8 ..m.H.5G./.H.}..
+0x000000000116c490 da c4 6d 00 e8 d5 5b 01 00 88 45 d5 e8 e5 59 01 ..m...[...E...Y.
+0x000000000116c4a0 00 88 45 d7 e8 d1 5a 01 00 88 45 d6 f6 45 d7 01 ..E...Z...E..E..
+0x000000000116c4b0 0f 85 13 4f 00 00 f6 45 d5 01 0f 85 ac 00 00 00 ...O...E........
+0x000000000116c4c0 f6 45 d6 01 0f 84 08 70 00 00 48 8d 7d a0 be 58 .E.....p..H.}..X
+0x000000000116c4d0 00 00 00 e8 ea c4 6d 00 48 8d 35 a8 2a 30 01 48 ......m.H.5.*0.H
+0x000000000116c4e0 8d 7d a0 e8 86 c4 6d 00 48 8d 35 ad ca 2e 01 48 .}....m.H.5....H
+0x000000000116c4f0 8d 7d a0 e8 76 c4 6d 00 e8 03 5a 01 00 88 45 d6 .}..v.m...Z...E.
+0x000000000116c500 e8 d5 52 01 00 88 45 d5 e8 ff 58 01 00 88 45 d7 ..R...E...X...E.
+0x000000000116c510 f6 45 d5 01 0f 85 53 01 00 00 f6 45 d6 01 0f 85 .E....S....E....
+0x000000000116c520 53 02 00 00 f6 45 d7 01 0f 85 57 7b 00 00 e9 9f S....E....W{....
+0x000000000116c530 6f 00 00 48 8d 35 c5 8c 94 00 48 8d 7d a0 ba 01 o..H.5....H.}...
+0x000000000116c540 00 00 00 e8 2c c4 6d 00 48 8d 35 84 81 2f 01 48 ....,.m.H.5../.H
+0x000000000116c550 8d 7d b8 e8 74 51 01 00 0f b6 55 b8 89 d0 24 01 .}..tQ....U...$.
+0x000000000116c560 74 2e 48 8b 75 t.H.u
[*] After:
+0x000000000116c3b0 55 48 89 e5 48 31 c0 48 UH..H1.H
+0x000000000116c3c0 89 07 48 89 47 08 48 89 47 10 ba 88 01 00 00 48 ..H.G.H.G......H
+0x000000000116c3d0 8d 35 07 00 00 00 e8 99 c5 6d 00 c9 c3 4d 49 49 .5.......m...MII
+0x000000000116c3e0 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 BIjANBgkqhkiG9w0
+0x000000000116c3f0 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 BAQEFAAOCAQ8AMII
+0x000000000116c400 42 43 67 4b 43 41 51 45 41 34 43 46 36 49 37 54 BCgKCAQEA4CF6I7T
+0x000000000116c410 63 72 6c 6c 32 4c 50 57 37 58 77 48 30 57 52 71 crll2LPW7XwH0WRq
+0x000000000116c420 30 49 38 75 49 6f 6e 48 61 38 31 7a 55 61 46 58 0I8uIonHa81zUaFX
+0x000000000116c430 43 47 4d 7a 73 66 79 37 39 52 39 7a 72 47 35 4a CGMzsfy79R9zrG5J
+0x000000000116c440 64 76 4c 76 30 51 32 4c 58 71 49 45 53 5a 42 61 dvLv0Q2LXqIESZBa
+0x000000000116c450 6f 42 61 4a 49 32 72 53 39 77 63 47 39 42 6b 6c oBaJI2rS9wcG9Bkl
+0x000000000116c460 41 63 75 53 4c 36 4f 41 38 67 39 69 44 62 72 39 AcuSL6OA8g9iDbr9
+0x000000000116c470 51 52 4a 65 71 76 74 5a 67 70 59 6e 6d 70 38 35 QRJeqvtZgpYnmp85
+0x000000000116c480 71 66 5a 4e 6f 54 70 2b 72 4b 51 4f 4b 4d 5a 2f qfZNoTp+rKQOKMZ/
+0x000000000116c490 69 34 4a 61 59 51 4b 63 63 39 5a 63 5a 45 58 61 i4JaYQKcc9ZcZEXa
+0x000000000116c4a0 55 79 73 6e 38 43 46 49 55 41 6f 4b 71 71 4d 4f Uysn8CFIUAoKqqMO
+0x000000000116c4b0 74 79 69 67 67 70 75 44 35 74 54 76 57 6e 69 2b tyiggpuD5tTvWni+
+0x000000000116c4c0 48 72 48 4e 6f 42 51 46 6d 2b 72 6f 32 68 38 6d HrHNoBQFm+ro2h8m
+0x000000000116c4d0 36 77 65 78 65 30 47 4c 68 39 4d 38 31 6c 6a 6b 6wexe0GLh9M81ljk
+0x000000000116c4e0 47 4f 79 43 75 61 4f 4b 6b 43 71 34 54 50 55 6e GOyCuaOKkCq4TPUn
+0x000000000116c4f0 48 33 75 6d 6b 31 35 57 49 4e 32 58 68 44 47 59 H3umk15WIN2XhDGY
+0x000000000116c500 59 77 46 6c 50 51 49 50 47 4b 7a 48 46 4a 72 54 YwFlPQIPGKzHFJrT
+0x000000000116c510 65 67 43 39 50 73 42 54 41 6f 59 6a 7a 71 4a 39 egC9PsBTAoYjzqJ9
+0x000000000116c520 50 51 4b 36 47 49 41 33 44 68 67 64 53 33 57 52 PQK6GIA3DhgdS3WR
+0x000000000116c530 2f 70 75 6e 33 41 4b 6d 6e 57 4f 77 76 55 67 52 /pun3AKmnWOwvUgR
+0x000000000116c540 47 32 37 71 5a 74 4e 59 35 46 61 34 4a 7a 42 2f G27qZtNY5Fa4JzB/
+0x000000000116c550 54 71 69 46 47 62 73 61 4b 77 4b 6a 57 6c 51 49 TqiFGbsaKwKjWlQI
+0x000000000116c560 44 41 51 41 42 DAQAB
[*] Previous:
+0x00000000011788d0 55 48 89 e5 41 56 53 48 83 ec 40 49 89 fe UH..AVSH..@I..
+0x00000000011788e0 c6 45 ed 01 31 c0 88 45 ee 88 45 ef 48 8d 35 1d .E..1..E..E.H.5.
+0x00000000011788f0 b6 29 01 48 8d 5d b0 48 89 df e8 cd 8d 00 00 48 .).H.].H.......H
+0x0000000001178900 8d 35 67 ce 93 00 ba 06 00 00 00 48 89 df e8 61 .5g........H...a
+0x0000000001178910 00 6d 00 e8 e4 97 00 00 88 45 ee e8 56 98 00 00 .m.......E..V...
+0x0000000001178920 88 45 ed e8 c8 98 00 00 88 45 ef f6 45 ee 01 75 .E.......E..E..u
+0x0000000001178930 33 f6 45 ed 01 75 51 f6 45 ef 01 0f 84 b8 8a 00 3.E..uQ.E.......
+0x0000000001178940 00 48 8d 7d b0 be 58 00 00 00 e8 73 00 6d 00 48 .H.}..X....s.m.H
+0x0000000001178950 8d 35 1b d4 2e 01 48 8d 7d b0 e8 0f 00 6d 00 e9 .5....H.}....m..
+0x0000000001178960 6b 19 00 00 48 8d 35 60 cb 2e 01 48 8d 7d d0 e8 k...H.5`...H.}..
+0x0000000001178970 58 8d 00 00 0f b6 55 d0 89 d0 24 01 74 40 48 8b X.....U...$.t@H.
+0x0000000001178980 75 e0 48 8b 55 d8 eb 3d 48 8d 7d b0 be 75 00 00 u.H.U..=H.}..u..
+0x0000000001178990 00 e8 2c 00 6d 00 48 8d 7d b0 be 44 00 00 00 e8 ..,.m.H.}..D....
+0x00000000011789a0 1e 00 6d 00 48 8d 35 bc d1 93 00 48 8d 7d b0 ba ..m.H.5....H.}..
+0x00000000011789b0 07 00 00 00 e8 bb ff 6c 00 e9 66 7a 00 00 48 d1 .......l..fz..H.
+0x00000000011789c0 ea 48 8d 75 d1 48 8d 7d b0 e8 a6 ff 6c 00 f6 45 .H.u.H.}....l..E
+0x00000000011789d0 d0 01 74 09 48 8b 7d e0 e8 49 02 6d 00 48 8d 35 ..t.H.}..I.m.H.5
+0x00000000011789e0 ed ca 2e 01 48 8d 7d b0 e8 81 ff 6c 00 48 8d 35 ....H.}....l.H.5
+0x00000000011789f0 59 c1 2e 01 48 8d 7d b0 e8 71 ff 6c 00 e8 68 98 Y...H.}..q.l..h.
+0x0000000001178a00 00 00 88 45 ed e8 da 98 00 00 88 45 ef e8 4c 99 ...E.......E..L.
+0x0000000001178a10 00 00 88 45 ee f6 45 ee 01 0f 85 61 27 00 00 f6 ...E..E....a'...
+0x0000000001178a20 45 ed 01 75 0f f6 45 ef 01 0f 85 8c 7d 00 00 e9 E..u..E.....}...
+0x0000000001178a30 c5 89 00 00 48 8d 35 fb cf 2e 01 48 8d 7d b0 e8 ....H.5....H.}..
+0x0000000001178a40 2a ff 6c 00 48 8d 35 f1 cf 2e 01 48 8d 7d d0 e8 *.l.H.5....H.}..
+0x0000000001178a50 78 8c 00 00 0f b6 55 d0 89 d0 24 01 74 0a 48 8b x.....U...$.t.H.
+0x0000000001178a60 75 e0 48 8b 55 d8 eb 07 48 d1 ea 48 8d 75 d1 48 u.H.U...H..H.u.H
+0x0000000001178a70 8d 7d b0 e8 fc fe 6c 00 f6 45 d0 01 74 09 48 .}....l..E..t.H
[*] After:
+0x00000000011788d0 55 48 89 e5 48 31 c0 48 89 07 48 89 47 08 UH..H1.H..H.G.
+0x00000000011788e0 48 89 47 10 ba 88 01 00 00 48 8d 35 07 00 00 00 H.G......H.5....
+0x00000000011788f0 e8 7f 00 6d 00 c9 c3 00 00 00 00 00 00 00 00 00 ...m............
+0x0000000001178900 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178910 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178920 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178930 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178940 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178950 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178960 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178970 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178980 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178990 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x00000000011789a0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x00000000011789b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x00000000011789c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x00000000011789d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x00000000011789e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x00000000011789f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a60 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
+0x0000000001178a70 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ...............
[+] PatchSolution3 has been applied.
[*] New RSA-2048 private key has been saved to
/Users/doublesine/github.com/navicat-keygen/bin/RegPrivateKey.pem
**************************************************************
* Patch has been done successfully. Have fun and enjoy~~ *
* DO NOT FORGET TO SIGN NAVICAT BY YOUR CERTIFICATE!!! *
**************************************************************

View File

@ -1,48 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32112.339
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-keygen", "navicat-keygen\navicat-keygen.vcxproj", "{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-patcher", "navicat-patcher\navicat-patcher.vcxproj", "{1B6920EB-E6ED-465F-9600-B5F816752375}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "common", "common\common.vcxitems", "{6D81A756-475A-4093-919E-3E9217F662CA}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
common\common.vcxitems*{1b6920eb-e6ed-465f-9600-b5f816752375}*SharedItemsImports = 4
common\common.vcxitems*{6d262af4-5dac-4f0c-b3d6-23c9cbea9756}*SharedItemsImports = 4
common\common.vcxitems*{6d81a756-475a-4093-919e-3e9217f662ca}*SharedItemsImports = 9
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Debug|x64.ActiveCfg = Debug|x64
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Debug|x64.Build.0 = Debug|x64
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Debug|x86.ActiveCfg = Debug|Win32
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Debug|x86.Build.0 = Debug|Win32
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Release|x64.ActiveCfg = Release|x64
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Release|x64.Build.0 = Release|x64
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Release|x86.ActiveCfg = Release|Win32
{6D262AF4-5DAC-4F0C-B3D6-23C9CBEA9756}.Release|x86.Build.0 = Release|Win32
{1B6920EB-E6ED-465F-9600-B5F816752375}.Debug|x64.ActiveCfg = Debug|x64
{1B6920EB-E6ED-465F-9600-B5F816752375}.Debug|x64.Build.0 = Debug|x64
{1B6920EB-E6ED-465F-9600-B5F816752375}.Debug|x86.ActiveCfg = Debug|Win32
{1B6920EB-E6ED-465F-9600-B5F816752375}.Debug|x86.Build.0 = Debug|Win32
{1B6920EB-E6ED-465F-9600-B5F816752375}.Release|x64.ActiveCfg = Release|x64
{1B6920EB-E6ED-465F-9600-B5F816752375}.Release|x64.Build.0 = Release|x64
{1B6920EB-E6ED-465F-9600-B5F816752375}.Release|x86.ActiveCfg = Release|Win32
{1B6920EB-E6ED-465F-9600-B5F816752375}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9382E280-F6E3-48E2-B3EF-1DB5BFF83DAE}
EndGlobalSection
EndGlobal

134
navicat-keygen/Base32.hpp Normal file
View File

@ -0,0 +1,134 @@
#pragma once
#include <stdint.h>
#include <string>
#include <vector>
[[nodiscard]]
inline std::string base32_encode(const void* lpBinary, size_t cbBinary) {
static const std::string::value_type Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static constexpr std::string::value_type PaddingChar = '=';
std::string szBase32;
if (auto pbBinary = reinterpret_cast<const uint8_t*>(lpBinary); cbBinary) {
szBase32.reserve((cbBinary * 8 + 4) / 5);
uint8_t Idx = 0;
uint8_t BitsLeft = 8;
for (size_t i = 0; i < cbBinary;) {
if (BitsLeft < 5) {
Idx = pbBinary[i] << (5 - BitsLeft);
++i;
if (i != cbBinary) {
Idx |= pbBinary[i] >> (3 + BitsLeft);
}
Idx &= 0x1F;
BitsLeft += 3;
} else {
Idx = pbBinary[i] >> (BitsLeft - 5);
Idx &= 0x1F;
BitsLeft -= 5;
}
szBase32.append(1, Alphabet[Idx]);
if (BitsLeft == 0) {
BitsLeft = 8;
++i;
}
}
if (szBase32.length() % 8) {
size_t Padding = 8 - szBase32.length() % 8;
szBase32.append(Padding, PaddingChar);
}
}
return szBase32;
}
[[nodiscard]]
inline std::string base32_encode(const std::vector<uint8_t>& Binary) {
return base32_encode(Binary.data(), Binary.size());
}
[[nodiscard]]
inline std::string base32_encode(const std::initializer_list<uint8_t>& Binary) {
return base32_encode(Binary.begin(), Binary.size());
}
[[nodiscard]]
inline std::vector<uint8_t> base32_decode(std::string_view szBase32) {
static constexpr std::string::value_type PaddingChar = '=';
std::vector<uint8_t> Binary;
if (szBase32.length()) {
Binary.reserve((szBase32.length() * 5 + 7) / 8);
uint8_t Byte = 0;
uint8_t BitsNeed = 8;
for (size_t i = 0; i < szBase32.length(); ++i) {
uint8_t Idx;
if ('A' <= szBase32[i] && szBase32[i] <= 'Z') {
Idx = szBase32[i] - 'A';
} else if ('a' <= szBase32[i] && szBase32[i] <= 'z') {
Idx = szBase32[i] - 'a';
} else if ('2' <= szBase32[i] && szBase32[i] <= '7') {
Idx = szBase32[i] - '2' + 26;
} else if (szBase32[i] == PaddingChar) {
for (size_t j = i + 1; j < szBase32.length(); ++j) {
if (szBase32[j] != PaddingChar) {
throw std::invalid_argument("base32_decode: invalid padding schema.");
}
}
break;
} else {
throw std::invalid_argument("base32_decode: non-Base32 character is detected.");
}
if (BitsNeed >= 5) {
Byte |= Idx;
BitsNeed -= 5;
Byte <<= BitsNeed;
} else {
Byte |= Idx >> (5 - BitsNeed);
Binary.push_back(Byte);
BitsNeed += 3;
Byte = Idx << BitsNeed;
if (BitsNeed > 5) {
Byte >>= BitsNeed - 5;
}
}
}
switch (BitsNeed) {
case 1:
case 2:
case 3:
throw std::invalid_argument("base32_decode: base32 string is corrupted.");
case 4:
case 5:
case 6:
case 7:
if (Byte != 0) {
throw std::invalid_argument("base32_decode: base32 string is corrupted.");
}
break;
case 0:
case 8:
break;
default:
__builtin_unreachable();
}
}
return Binary;
}

134
navicat-keygen/Base64.hpp Normal file
View File

@ -0,0 +1,134 @@
#pragma once
#include <stdint.h>
#include <vector>
#include <string>
[[nodiscard]]
inline std::string base64_encode(const void* lpBinary, size_t cbBinary) {
static const std::string::value_type Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr std::string::value_type PaddingChar = '=';
std::string szBase64;
if (auto pbBinary = reinterpret_cast<const uint8_t*>(lpBinary); cbBinary) {
szBase64.reserve((cbBinary * 8 + 5) / 6);
uint8_t Idx = 0;
uint8_t BitsLeft = 8;
for (size_t i = 0; i < cbBinary;) {
if (BitsLeft < 6) {
Idx = pbBinary[i] << (6 - BitsLeft);
++i;
if (i != cbBinary) {
Idx |= pbBinary[i] >> (2 + BitsLeft);
}
Idx &= 0x3F;
BitsLeft += 2;
} else {
Idx = pbBinary[i] >> (BitsLeft - 6);
Idx &= 0x3F;
BitsLeft -= 6;
}
szBase64.append(1, Alphabet[Idx]);
if (BitsLeft == 0) {
BitsLeft = 8;
++i;
}
}
if (szBase64.length() % 4) {
size_t Padding = 4 - szBase64.length() % 4;
szBase64.append(Padding, PaddingChar);
}
}
return szBase64;
}
[[nodiscard]]
inline std::string base64_encode(const std::vector<uint8_t>& Binary) {
return base64_encode(Binary.data(), Binary.size());
}
[[nodiscard]]
inline std::string base64_encode(const std::initializer_list<uint8_t>& Binary) {
return base64_encode(Binary.begin(), Binary.size());
}
[[nodiscard]]
inline std::vector<uint8_t> base64_decode(std::string_view szBase64) {
static constexpr std::string::value_type PaddingChar = '=';
std::vector<uint8_t> Binary;
if (szBase64.length()) {
Binary.reserve((szBase64.length() * 6 + 7) / 8);
uint8_t Byte = 0;
uint8_t BitsNeed = 8;
for (size_t i = 0; i < szBase64.length(); ++i) {
uint8_t Idx;
if ('A' <= szBase64[i] && szBase64[i] <= 'Z') {
Idx = szBase64[i] - 'A';
} else if ('a' <= szBase64[i] && szBase64[i] <= 'z') {
Idx = szBase64[i] - 'a' + 26;
} else if ('0' <= szBase64[i] && szBase64[i] <= '9') {
Idx = szBase64[i] - '0' + 26 + 26;
} else if (szBase64[i] == '+') {
Idx = 26 + 26 + 10;
} else if (szBase64[i] == '/') {
Idx = 26 + 26 + 10 + 1;
} else if (szBase64[i] == PaddingChar) {
for (size_t j = i + 1; j < szBase64.length(); ++j) {
if (szBase64[j] != PaddingChar) {
throw std::invalid_argument("base64_decode: invalid padding schema.");
}
}
break;
} else {
throw std::invalid_argument("base64_decode: non-Base64 character is detected.");
}
if (BitsNeed >= 6) {
Byte |= Idx;
BitsNeed -= 6;
Byte <<= BitsNeed;
} else {
Byte |= Idx >> (6 - BitsNeed);
Binary.push_back(Byte);
BitsNeed += 2;
Byte = Idx << BitsNeed;
if (BitsNeed > 6) {
Byte >>= BitsNeed - 6;
}
}
}
switch (BitsNeed) {
case 2:
throw std::invalid_argument("base64_decode: base64 string is corrupted.");
case 4:
case 6:
if (Byte != 0) {
throw std::invalid_argument("base64_decode: base64 string is corrupted.");
}
break;
case 0:
case 8:
break;
default:
__builtin_unreachable();
}
}
return Binary;
}

View File

@ -1,20 +1,17 @@
#include "navicat_serial_generator.hpp"
#include "SerialNumberGenerator.hpp"
#include "ExceptionGeneric.hpp"
#include <iostream>
#include "exceptions/operation_canceled_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\CollectInformation.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
[[nodiscard]]
static int read_int(int min_val, int max_val, std::wstring_view prompt, std::wstring_view error_msg) {
static int ReadInt(int MinVal, int MaxVal, const char* lpszPrompt, const char* lpszErrorMessage) {
int val;
for (std::wstring s;;) {
std::wcout << prompt;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
std::string s;
while (true) {
std::cout << lpszPrompt;
if (!std::getline(std::cin, s)) {
throw ARL::EOFError(__FILE__, __LINE__, "Abort.");
}
if (s.empty())
@ -22,112 +19,103 @@ namespace nkg {
try {
val = std::stoi(s, nullptr, 0);
if (min_val <= val && val <= max_val) {
if (MinVal <= val && val <= MaxVal) {
return val;
} else {
throw std::invalid_argument(u8"");
throw std::invalid_argument("Out of range.");
}
} catch (std::invalid_argument&) {
std::wcout << error_msg << std::endl;
std::cout << lpszErrorMessage << std::endl;
}
}
}
[[nodiscard]]
static int read_int(int min_val, int max_val, int default_val, std::wstring_view prompt, std::wstring_view error_msg) {
static int ReadInt(int MinVal, int MaxVal, int DefaultVal, const char* lpszPrompt, const char* lpszErrorMessage) {
int val;
for (std::wstring s;;) {
std::wcout << prompt;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
std::string s;
while (true) {
std::cout << lpszPrompt;
if (!std::getline(std::cin, s)) {
throw ARL::EOFError(__FILE__, __LINE__, "Abort.");
}
if (s.empty()) {
return default_val;
return DefaultVal;
}
try {
val = std::stoi(s, nullptr, 0);
if (min_val <= val && val <= max_val) {
if (MinVal <= val && val <= MaxVal) {
return val;
} else {
throw std::invalid_argument(u8"");
throw std::invalid_argument("Out of range.");
}
} catch (std::invalid_argument&) {
std::wcout << error_msg << std::endl;
std::cout << lpszErrorMessage << std::endl;
}
}
}
[[nodiscard]]
navicat_serial_generator CollectInformationNormal() {
navicat_serial_generator sn_generator;
SerialNumberGenerator CollectInformationNormal() {
SerialNumberGenerator Generator;
std::wcout << L"[*] Select Navicat product:" << std::endl;
std::wcout << L" 0. DataModeler" << std::endl;
std::wcout << L" 1. Premium" << std::endl;
std::wcout << L" 2. MySQL" << std::endl;
std::wcout << L" 3. PostgreSQL" << std::endl;
std::wcout << L" 4. Oracle" << std::endl;
std::wcout << L" 5. SQLServer" << std::endl;
std::wcout << L" 6. SQLite" << std::endl;
std::wcout << L" 7. MariaDB" << std::endl;
std::wcout << L" 8. MongoDB" << std::endl;
std::wcout << L" 9. ReportViewer" << std::endl;
std::wcout << L" 10. ChartsCreator" << std::endl;
std::wcout << L" 11. ChartsViewer" << std::endl;
std::wcout << std::endl;
sn_generator.set_software_type(static_cast<navicat_software_type>(read_int(0, 11, L"(Input index)> ", L"Invalid index.")));
std::wcout << std::endl;
Generator.SetProductSignature(NavicatProductType::Premium);
std::cout << "[*] Select product language:" << std::endl;
std::cout << " 0. English" << std::endl;
std::cout << " 1. Simplified Chinese" << std::endl;
std::cout << " 2. Traditional Chinese" << std::endl;
std::cout << " 3. Japanese" << std::endl;
std::cout << " 4. Polish" << std::endl;
std::cout << " 5. Spanish" << std::endl;
std::cout << " 6. French" << std::endl;
std::cout << " 7. German" << std::endl;
std::cout << " 8. Korean" << std::endl;
std::cout << " 9. Russian" << std::endl;
std::cout << " 10. Portuguese" << std::endl;
std::cout << std::endl;
Generator.SetLanguageSignature(
static_cast<NavicatLanguage>(ReadInt(0, 10, "(Input index)> ", "Invalid index."))
);
std::wcout << L"[*] Select product language:" << std::endl;
std::wcout << L" 0. English" << std::endl;
std::wcout << L" 1. Simplified Chinese" << std::endl;
std::wcout << L" 2. Traditional Chinese" << std::endl;
std::wcout << L" 3. Japanese" << std::endl;
std::wcout << L" 4. Polish" << std::endl;
std::wcout << L" 5. Spanish" << std::endl;
std::wcout << L" 6. French" << std::endl;
std::wcout << L" 7. German" << std::endl;
std::wcout << L" 8. Korean" << std::endl;
std::wcout << L" 9. Russian" << std::endl;
std::wcout << L" 10. Portuguese" << std::endl;
std::wcout << std::endl;
sn_generator.set_software_language(static_cast<navicat_software_language>(read_int(0, 10, L"(Input index)> ", L"Invalid index.")));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Input major version number:" << std::endl;
Generator.SetVersion(
static_cast<uint8_t>(ReadInt(0, 15, 15, "(range: 0 ~ 15, default: 15)> ", "Invalid number."))
);
std::wcout << L"[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(1, 16, 16, L"(range: 1 ~ 16, default: 16)> ", L"Invalid number."));
std::wcout << std::endl;
return sn_generator;
std::cout << std::endl;
return Generator;
}
[[nodiscard]]
navicat_serial_generator CollectInformationAdvanced() {
navicat_serial_generator sn_generator;
SerialNumberGenerator CollectInformationAdvanced() {
SerialNumberGenerator Generator;
std::wcout << L"[*] Navicat Product Signature:" << std::endl;
sn_generator.set_software_type(static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number.")));
std::wcout << std::endl;
std::cout << "[*] Navicat Product Signature:" << std::endl;
Generator.SetProductSignature(
static_cast<uint8_t>(ReadInt(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number."))
);
std::wcout << L"[*] Navicat Language Signature 0:" << std::endl;
auto s1 = static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number."));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Navicat Language Signature 0:" << std::endl;
auto s1 = static_cast<uint8_t>(ReadInt(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number."));
std::wcout << L"[*] Navicat Language Signature 1:" << std::endl;
auto s2 = static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number."));
sn_generator.set_software_language(s1, s2);
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Navicat Language Signature 1:" << std::endl;
auto s2 = static_cast<uint8_t>(ReadInt(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number."));
Generator.SetLanguageSignature(s1, s2);
std::wcout << L"[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(1, 16, 16, L"(range: 1 ~ 16, default: 16)> ", L"Invalid number."));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Input major version number:" << std::endl;
Generator.SetVersion(
static_cast<uint8_t>(ReadInt(0, 15, 12, "(range: 0 ~ 15, default: 12)> ", "Invalid number."))
);
return sn_generator;
std::cout << std::endl;
return Generator;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -1,84 +1,70 @@
#include "exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#include "exceptions/win32_exception.hpp"
#include "resource_wrapper.hpp"
#include "resource_traits/win32/file_handle.hpp"
#include "cp_converter.hpp"
#include "base64_rfc4648.hpp"
#include "navicat_serial_generator.hpp"
#include "rsa_cipher.hpp"
#include "Exception.hpp"
#include "ExceptionGeneric.hpp"
#include "ResourceWrapper.hpp"
#include "ResourceTraitsOpenssl.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>
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\GenerateLicense.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
void GenerateLicenseText(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator) {
std::string utf8username;
std::string utf8organization;
std::wstring b64_request_code;
std::vector<std::uint8_t> request_code;
std::string u8_request_info;
std::string u8_response_info;
std::vector<std::uint8_t> response_code;
std::wstring b64_response_code;
std::string b64RequestCode;
std::vector<uint8_t> RequestCode;
std::string utf8RequestInfo;
std::string utf8ResponseInfo;
std::vector<uint8_t> ResponseCode;
std::string b64ResponseCode;
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
std::cout << "[*] Your name: ";
if (!std::getline(std::cin, utf8username)) {
throw ARL::EOFError(__FILE__, __LINE__, "Abort.");
}
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
std::cout << "[*] Your organization: ";
if (!std::getline(std::cin, utf8organization)) {
throw ARL::EOFError(__FILE__, __LINE__, "Abort.");
}
std::wcout << std::endl;
std::wcout << L"[*] Input request code in Base64: (Input empty line to end)" << std::endl;
std::cout << std::endl;
std::cout << "[*] Input request code in Base64: (Double press ENTER to end)" << std::endl;
while (true) {
std::wstring s;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
std::string temp;
if (!std::getline(std::cin, temp)) {
throw ARL::EOFError(__FILE__, __LINE__, "Abort.");
}
if (s.empty()) {
if (temp.empty()) {
break;
}
b64_request_code.append(s);
b64RequestCode.append(temp);
}
if (b64_request_code.empty()) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Nothing inputs, abort!");
RequestCode = base64_decode(b64RequestCode);
if (RequestCode.size() != 256) {
throw ARL::AssertionError(__FILE__, __LINE__, "Broken request code. %zu", RequestCode.size());
}
request_code = base64_rfc4648::decode(cp_converter<-1, CP_UTF8>::convert(b64_request_code));
u8_request_info.resize((cipher.bits() + 7) / 8);
u8_request_info.resize(cipher.private_decrypt(request_code.data(), request_code.size(), u8_request_info.data(), RSA_PKCS1_PADDING));
while (u8_request_info.back() == '\x00') {
u8_request_info.pop_back();
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::wcout << L"[*] Request Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_request_info) << std::endl;
std::wcout << std::endl;
std::cout << "[*] Request Info:" << std::endl;
std::cout << utf8RequestInfo << std::endl;
std::cout << std::endl;
rapidjson::Document json;
rapidjson::Value N_Key;
@ -91,147 +77,55 @@ namespace nkg {
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//
// begin to parse
// Begin to parse
//
json.Parse(u8_request_info.c_str());
json.Parse(utf8RequestInfo.c_str());
//
// remove "Platform" info
// Remove "Platform" info
//
json.RemoveMember(u8"P");
json.RemoveMember("P");
//
// set "Name" info
// Set "Name" info
//
N_Key.SetString(u8"N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
//
// set "Organization" info
//
O_Key.SetString(u8"O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
//
// set "Time" info
//
T_Key.SetString(u8"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());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
b64_response_code = cp_converter<CP_UTF8, -1>::convert(base64_rfc4648::encode(response_code));
std::wcout << L"[*] Activation Code:" << std::endl;
std::wcout << b64_response_code << std::endl;
std::wcout << std::endl;
}
void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::string utf8SerialNumber = sn_generator.serial_number();
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
std::string u8_response_info;
std::vector<std::uint8_t> response_code;
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
}
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
}
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(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
//
// Set "Organization" info
//
O_Key.SetString("O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
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)));
json.AddMember(K_Key, K_Value, json.GetAllocator());
//
// 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());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
throw ARL::Exception(__FILE__, __LINE__, "Response info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
std::cout << "[*] Response Info:" << std::endl;
std::cout << utf8ResponseInfo << std::endl;
std::cout << std::endl;
resource_wrapper license_file{ resource_traits::win32::file_handle{}, CreateFileW(L"license_file", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) };
if (license_file.is_valid() == false) {
throw exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"CreateFileW failed.");
}
ResponseCode.resize((Cipher.Bits() + 7) / 8);
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
if (DWORD _; WriteFile(license_file.get(), response_code.data(), static_cast<DWORD>(response_code.size()), &_, NULL) == FALSE) {
throw exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"WriteFile failed.");
}
b64ResponseCode = base64_encode(ResponseCode);
std::wcout << L"[+] license_file has been generated." << std::endl;
std::cout << "[*] Activation Code:" << std::endl;
std::cout << b64ResponseCode << std::endl;
std::cout << std::endl;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -0,0 +1,183 @@
#include "SerialNumberGenerator.hpp"
#include "Exception.hpp"
#include <openssl/rand.h>
#include <openssl/des.h>
#include <iostream>
#include <algorithm>
#include "Base32.hpp"
namespace nkg {
SerialNumberGenerator::SerialNumberGenerator() noexcept :
m_Data{ 0x68 , 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32 } {}
void SerialNumberGenerator::SetLanguageSignature(NavicatLanguage Language) noexcept {
switch (Language) {
case NavicatLanguage::English:
m_Data[5] = 0xAC; // Must be 0xAC for English version.
m_Data[6] = 0x88; // Must be 0x88 for English version.
break;
case NavicatLanguage::SimplifiedChinese:
m_Data[5] = 0xCE; // Must be 0xCE for Simplified Chinese version.
m_Data[6] = 0x32; // Must be 0x32 for Simplified Chinese version.
break;
case NavicatLanguage::TraditionalChinese:
m_Data[5] = 0xAA; // Must be 0xAA for Traditional Chinese version.
m_Data[6] = 0x99; // Must be 0x99 for Traditional Chinese version.
break;
case NavicatLanguage::Japanese:
m_Data[5] = 0xAD; // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
m_Data[6] = 0x82; // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Polish:
m_Data[5] = 0xBB; // Must be 0xBB for Polish version. Discoverer: @dragonflylee
m_Data[6] = 0x55; // Must be 0x55 for Polish version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Spanish:
m_Data[5] = 0xAE; // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
m_Data[6] = 0x10; // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
break;
case NavicatLanguage::French:
m_Data[5] = 0xFA; // Must be 0xFA for French version. Discoverer: @Deltafox79
m_Data[6] = 0x20; // Must be 0x20 for French version. Discoverer: @Deltafox79
break;
case NavicatLanguage::German:
m_Data[5] = 0xB1; // Must be 0xB1 for German version. Discoverer: @dragonflylee
m_Data[6] = 0x60; // Must be 0x60 for German version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Korean:
m_Data[5] = 0xB5; // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
m_Data[6] = 0x60; // Must be 0x60 for Korean version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Russian:
m_Data[5] = 0xEE; // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
m_Data[6] = 0x16; // Must be 0x60 for Russian version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Portuguese:
m_Data[5] = 0xCD; // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
m_Data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
break;
}
}
void SerialNumberGenerator::SetLanguageSignature(uint8_t LanguageSignature0, uint8_t LanguageSignature1) noexcept {
m_Data[5] = LanguageSignature0;
m_Data[6] = LanguageSignature1;
}
void SerialNumberGenerator::SetProductSignature(NavicatProductType ProductType) noexcept {
switch (ProductType) {
case NavicatProductType::DataModeler:
m_Data[7] = 0x84;
break;
case NavicatProductType::Premium:
m_Data[7] = 0x65;
break;
case NavicatProductType::MySQL:
m_Data[7] = 0x68;
break;
case NavicatProductType::PostgreSQL:
m_Data[7] = 0x6C;
break;
case NavicatProductType::Oracle:
m_Data[7] = 0x70;
break;
case NavicatProductType::SQLServer:
m_Data[7] = 0x74;
break;
case NavicatProductType::SQLite:
m_Data[7] = 0x78;
break;
case NavicatProductType::MariaDB:
m_Data[7] = 0x7C;
break;
case NavicatProductType::MongoDB:
m_Data[7] = 0x80;
break;
case NavicatProductType::ReportViewer:
m_Data[7] = 0x0b;
default:
break;
}
}
void SerialNumberGenerator::SetProductSignature(uint8_t ProductSignature) noexcept {
m_Data[7] = ProductSignature;
}
void SerialNumberGenerator::SetVersion(uint8_t Version) {
if (Version < 0x10) {
m_Data[8] = static_cast<uint8_t>(Version << 4);
} else {
throw ARL::Exception(__FILE__, __LINE__, "Invalid version for Navicat.");
}
}
void SerialNumberGenerator::Generate() {
static auto translator = [](char c) {
#ifdef __APPLE__
//static const char StandardBase32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
//static const char NavicatBase32[] = "ABCDEFGH8JKLMN9PQRSTUVWXYZ234567";
switch (c) {
case 'I':
return '8';
case 'O':
return '9';
default:
return c;
}
#else
//static const char StandardBase32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
//static const char NavicatBase32[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
return c;
#endif
};
RAND_bytes(m_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*>(m_Data + 2),
reinterpret_cast<const_DES_cblock*>(m_Data + 2),
&schedule,
DES_ENCRYPT
);
m_SerialNumberShort = base32_encode(m_Data, sizeof(m_Data));
std::transform(m_SerialNumberShort.begin(), m_SerialNumberShort.end(), m_SerialNumberShort.begin(), translator);
m_SerialNumberLong.resize(20);
snprintf(m_SerialNumberLong.data(), m_SerialNumberLong.length(),
"%.4s-%.4s-%.4s-%.4s",
m_SerialNumberShort.c_str() + 0,
m_SerialNumberShort.c_str() + 4,
m_SerialNumberShort.c_str() + 8,
m_SerialNumberShort.c_str() + 12
);
while (m_SerialNumberLong.back() == '\x00') {
m_SerialNumberLong.pop_back();
}
}
[[nodiscard]]
const std::string& SerialNumberGenerator::GetSerialNumberShort() const noexcept {
return m_SerialNumberShort;
}
[[nodiscard]]
const std::string& SerialNumberGenerator::GetSerialNumberLong() const noexcept {
return m_SerialNumberLong;
}
void SerialNumberGenerator::ShowInConsole() const {
std::cout << "[*] Serial number:" << std::endl;
std::cout << m_SerialNumberLong << std::endl;
std::cout << std::endl;
}
}

View File

@ -0,0 +1,65 @@
#pragma once
#include <stdint.h>
#include <string>
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:
uint8_t m_Data[10];
std::string m_SerialNumberShort;
std::string m_SerialNumberLong;
public:
SerialNumberGenerator() noexcept;
void SetLanguageSignature(NavicatLanguage Language) noexcept;
void SetLanguageSignature(uint8_t LanguageSignature0, uint8_t LanguageSignature1) noexcept;
void SetProductSignature(NavicatProductType ProductType) noexcept;
void SetProductSignature(uint8_t ProductSignature) noexcept;
void SetVersion(uint8_t Version);
void Generate();
[[nodiscard]]
const std::string& GetSerialNumberShort() const noexcept;
[[nodiscard]]
const std::string& GetSerialNumberLong() const noexcept;
void ShowInConsole() const;
};
}

View File

@ -1,120 +0,0 @@
#include "base32_rfc4648.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\base32_rfc4648.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
char base32_rfc4648::symbol(alphabet_index_t idx) {
return alphabet[idx];
}
base32_rfc4648::alphabet_index_t base32_rfc4648::reverse_symbol(char c) {
if ('A' <= c && c <= 'Z') {
return c - 'A';
} else if ('2' <= c && c <= '7') {
return c - '2' + 26;
} else {
throw decoding_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Non-base32 digit is found");
}
}
std::string base32_rfc4648::encode(const std::vector<uint8_t>& data) {
return encode(data.data(), data.size());
}
std::string base32_rfc4648::encode(const void* data_ptr, size_t data_size) {
std::string retval;
if (data_size) {
retval.reserve((data_size * 8 + 4) / 5);
auto p = reinterpret_cast<const uint8_t*>(data_ptr);
alphabet_index_t left_bits = 0;
alphabet_index_t bit_buffer = 0;
for (size_t i = 0; i < data_size; ++i) {
bit_buffer = (bit_buffer << 8) | p[i];
left_bits += 8;
while (left_bits >= 5) {
alphabet_index_t idx = (bit_buffer >> (left_bits - 5)) & 0x1f;
retval.push_back(symbol(idx));
left_bits -= 5;
}
}
if (left_bits > 0) {
alphabet_index_t idx = (bit_buffer << (5 - left_bits)) & 0x1f;
retval.push_back(symbol(idx));
}
switch (data_size % 5) {
case 0:
break;
case 1:
retval.append(6, padding_character);
break;
case 2:
retval.append(4, padding_character);
break;
case 3:
retval.append(3, padding_character);
break;
case 4:
retval.append(1, padding_character);
break;
default:
__assume(false);
}
}
return retval;
}
std::vector<uint8_t> base32_rfc4648::decode(std::string_view b32_string) {
if (b32_string.length() % 8 == 0) {
std::vector<uint8_t> retval;
size_t count_of_padding = std::distance(b32_string.crbegin(), std::find_if_not(b32_string.crbegin(), b32_string.crend(), [](char c) -> bool { return c == padding_character; }));
switch (count_of_padding) {
case 1:
retval.reserve(b32_string.length() / 8 * 5 - (5 - 4));
break;
case 3:
retval.reserve(b32_string.length() / 8 * 5 - (5 - 3));
break;
case 4:
retval.reserve(b32_string.length() / 8 * 5 - (5 - 2));
break;
case 6:
retval.reserve(b32_string.length() / 8 * 5 - (5 - 1));
break;
default:
throw decoding_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Incorrect padding");
}
size_t count_of_encoded = b32_string.length() - count_of_padding;
alphabet_index_t left_bits = 0;
alphabet_index_t bit_buffer = 0;
for (size_t i = 0; i < count_of_encoded; ++i) {
bit_buffer = (bit_buffer << 5) | reverse_symbol(b32_string[i]);
left_bits += 5;
while (left_bits >= 8) {
auto val = static_cast<uint8_t>((bit_buffer >> (left_bits - 8)) & 0xff);
retval.push_back(val);
left_bits -= 8;
}
}
return retval;
} else {
throw decoding_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Incorrect padding");
}
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,39 +0,0 @@
#pragma once
#include <limits>
#include <string>
#include <vector>
#include <algorithm>
#include "exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\base32_rfc4648.hpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
struct base32_rfc4648 {
using alphabet_index_t = size_t;
static constexpr const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static constexpr const char padding_character = '=';
class decoding_error : public ::nkg::exception {
public:
decoding_error(std::string_view file, int line, std::string_view message) noexcept :
::nkg::exception(file, line, message) {}
};
static char symbol(alphabet_index_t idx);
static alphabet_index_t reverse_symbol(char c);
static std::string encode(const std::vector<uint8_t>& data);
static std::string encode(const void* data_ptr, size_t data_size);
static std::vector<uint8_t> decode(std::string_view b32_string);
};
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,103 +0,0 @@
#include "base64_rfc4648.hpp"
#include <openssl/bio.h>
#include <openssl/evp.h>
#include "resource_wrapper.hpp"
#include "resource_traits/openssl/bio.hpp"
#include "resource_traits/openssl/bio_chain.hpp"
#pragma comment(lib, "libcrypto")
#pragma comment(lib, "crypt32") // required by libcrypto.lib
#pragma comment(lib, "ws2_32") // required by libcrypto.lib
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\base64_rfc4648.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
std::string base64_rfc4648::encode(const std::vector<std::uint8_t>& data) {
resource_wrapper bio_b64{ resource_traits::openssl::bio_chain{}, BIO_new(BIO_f_base64()) };
if (bio_b64.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
BIO_set_flags(bio_b64.get(), BIO_FLAGS_BASE64_NO_NL);
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
BIO_push(bio_b64.get(), bio_memory.get());
for (size_t written_size = 0, left_size = data.size(); left_size != 0;) {
int size_to_write = static_cast<int>(std::min(left_size, static_cast<size_t>(INT_MAX)));
int r = BIO_write(bio_b64.get(), data.data() + written_size, size_to_write);
if (r > 0) {
written_size += r;
left_size -= r;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_write failed.");
}
}
BIO_flush(bio_b64.get());
const char* pch = nullptr;
long lch = BIO_get_mem_data(bio_memory.get(), &pch);
bio_memory.discard(); // the bio_chain `bio_b64` will free it
return std::string(pch, lch);
}
std::vector<uint8_t> base64_rfc4648::decode(std::string_view b64_string) {
resource_wrapper bio_b64{ resource_traits::openssl::bio_chain{}, BIO_new(BIO_f_base64()) };
if (bio_b64.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
BIO_set_flags(bio_b64.get(), BIO_FLAGS_BASE64_NO_NL);
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
BIO_push(bio_b64.get(), bio_memory.get());
for (size_t written_length = 0, left_length = b64_string.length(); left_length != 0;) {
int length_to_write = static_cast<int>(std::min(left_length, static_cast<size_t>(INT_MAX)));
int r = BIO_write(bio_memory.get(), b64_string.data() + written_length, length_to_write);
if (r > 0) {
written_length += r;
left_length -= r;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_write failed.");
}
}
std::vector<uint8_t> retval;
retval.reserve(b64_string.length() * 3 / 4 + 1);
for (uint8_t buf[256];;) {
auto len = BIO_read(bio_b64.get(), buf, sizeof(buf));
if (len > 0) {
retval.insert(retval.end(), buf, buf + len);
} else {
break;
}
}
bio_memory.discard(); // the bio_chain `bio_b64` will free it
return retval;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -1,20 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include "exception.hpp"
namespace nkg {
struct base64_rfc4648 {
class backend_error : public ::nkg::exception {
public:
backend_error(std::string_view file, int line, std::string_view message) noexcept :
::nkg::exception(file, line, message) {}
};
static std::string encode(const std::vector<std::uint8_t>& data);
static std::vector<uint8_t> decode(std::string_view str_b64);
};
}

96
navicat-keygen/main.cpp Normal file
View File

@ -0,0 +1,96 @@
#include <stdio.h>
#include <string.h>
#include "Exception.hpp"
#include "ExceptionGeneric.hpp"
#include "RSACipher.hpp"
#include "SerialNumberGenerator.hpp"
namespace nkg {
using fnCollectInformation = SerialNumberGenerator();
SerialNumberGenerator CollectInformationNormal();
SerialNumberGenerator CollectInformationAdvanced();
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
}
static void Welcome() {
puts("**********************************************************");
puts("* Navicat Keygen (macOS) by @DoubleLabyrinth *");
puts("* Version: 5.0 *");
puts("**********************************************************");
puts("");
}
static void Help() {
puts("Usage:");
puts(" navicat-keygen [--adv] <RSA-2048 Private Key File>");
puts("");
puts(" [--adv] Enable advance mode.");
puts(" This parameter is optional.");
puts("");
puts(" <RSA-2048 Private Key File> A path to an RSA-2048 private key file.");
puts(" This parameter must be specified.");
puts("");
puts("Example:");
puts(" ./navicat-keygen ./RegPrivateKey.pem");
}
int main(int argc, const char* argv[]) {
Welcome();
if (argc == 2 || argc == 3) {
nkg::fnCollectInformation* lpfnCollectInformation = nullptr;
if (argc == 3) {
if (strcasecmp(argv[1], "--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 ARL::Exception(__FILE__, __LINE__, "RSA key length mismatches.")
.PushHint("You must provide an RSA key whose modulus length is 2048 bits.");
}
auto Generator = lpfnCollectInformation();
Generator.Generate();
Generator.ShowInConsole();
GenerateLicenseText(Cipher, Generator);
return 0;
} catch (ARL::EOFError&) {
return ECANCELED;
} catch (ARL::Exception& e) {
printf("[-] %s:%zu ->\n", e.ExceptionFile(), e.ExceptionLine());
printf(" %s\n", e.ExceptionMessage());
if (e.HasErrorCode()) {
printf(" %s (0x%zx)\n", e.ErrorString(), e.ErrorCode());
}
for (const auto& Hint : e.Hints()) {
printf(" Hints: %s\n", Hint.c_str());
}
return -1;
} catch (std::exception& e) {
printf("[-] %s\n", e.what());
return -1;
}
} else {
Help();
return -1;
}
}

View File

@ -1,187 +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>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{6d262af4-5dac-4f0c-b3d6-23c9cbea9756}</ProjectGuid>
<RootNamespace>navicatkeygen</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</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\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" />
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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="base32_rfc4648.cpp" />
<ClCompile Include="base64_rfc4648.cpp" />
<ClCompile Include="CollectInformation.cpp" />
<ClCompile Include="GenerateLicense.cpp" />
<ClCompile Include="navicat_serial_generator.cpp" />
<ClCompile Include="wmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="base32_rfc4648.hpp" />
<ClInclude Include="base64_rfc4648.hpp" />
<ClInclude Include="navicat_serial_generator.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,48 +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;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;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="wmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="base64_rfc4648.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="navicat_serial_generator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CollectInformation.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="GenerateLicense.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="base32_rfc4648.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="base64_rfc4648.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="navicat_serial_generator.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="base32_rfc4648.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>

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>

View File

@ -1,196 +0,0 @@
#include "navicat_serial_generator.hpp"
#include <algorithm>
#include <openssl/evp.h>
#include <openssl/rand.h>
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
#include <openssl/provider.h>
#endif
#include "resource_wrapper.hpp"
#include "resource_traits/openssl/evp_cipher_ctx.hpp"
#include <fmt/format.h>
#include "base32_rfc4648.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\navicat_serial_generator.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
char navicat_serial_generator::_replace_confusing_chars(char c) noexcept {
if (c == 'I') {
return '8';
} else if (c == 'O') {
return '9';
} else {
return c;
}
};
navicat_serial_generator::navicat_serial_generator() noexcept :
m_data{ 0x68 , 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32 }, m_des_key{} {}
void navicat_serial_generator::set_software_language(navicat_software_language lang) noexcept {
switch (lang) {
case navicat_software_language::English:
m_data[5] = 0xAC; // Must be 0xAC for English version.
m_data[6] = 0x88; // Must be 0x88 for English version.
break;
case navicat_software_language::SimplifiedChinese:
m_data[5] = 0xCE; // Must be 0xCE for Simplified Chinese version.
m_data[6] = 0x32; // Must be 0x32 for Simplified Chinese version.
break;
case navicat_software_language::TraditionalChinese:
m_data[5] = 0xAA; // Must be 0xAA for Traditional Chinese version.
m_data[6] = 0x99; // Must be 0x99 for Traditional Chinese version.
break;
case navicat_software_language::Japanese:
m_data[5] = 0xAD; // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
m_data[6] = 0x82; // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
break;
case navicat_software_language::Polish:
m_data[5] = 0xBB; // Must be 0xBB for Polish version. Discoverer: @dragonflylee
m_data[6] = 0x55; // Must be 0x55 for Polish version. Discoverer: @dragonflylee
break;
case navicat_software_language::Spanish:
m_data[5] = 0xAE; // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
m_data[6] = 0x10; // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
break;
case navicat_software_language::French:
m_data[5] = 0xFA; // Must be 0xFA for French version. Discoverer: @Deltafox79
m_data[6] = 0x20; // Must be 0x20 for French version. Discoverer: @Deltafox79
break;
case navicat_software_language::German:
m_data[5] = 0xB1; // Must be 0xB1 for German version. Discoverer: @dragonflylee
m_data[6] = 0x60; // Must be 0x60 for German version. Discoverer: @dragonflylee
break;
case navicat_software_language::Korean:
m_data[5] = 0xB5; // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
m_data[6] = 0x60; // Must be 0x60 for Korean version. Discoverer: @dragonflylee
break;
case navicat_software_language::Russian:
m_data[5] = 0xEE; // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
m_data[6] = 0x16; // Must be 0x60 for Russian version. Discoverer: @dragonflylee
break;
case navicat_software_language::Portuguese:
m_data[5] = 0xCD; // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
m_data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
break;
}
}
void navicat_serial_generator::set_software_language(uint8_t lang_sig0, uint8_t lang_sig1) noexcept {
m_data[5] = lang_sig0;
m_data[6] = lang_sig1;
}
void navicat_serial_generator::set_software_type(navicat_software_type software_type) noexcept {
switch (software_type) {
case navicat_software_type::DataModeler:
m_data[7] = 0x84;
break;
case navicat_software_type::Premium:
m_data[7] = 0x65;
break;
case navicat_software_type::MySQL:
m_data[7] = 0x68;
break;
case navicat_software_type::PostgreSQL:
m_data[7] = 0x6C;
break;
case navicat_software_type::Oracle:
m_data[7] = 0x70;
break;
case navicat_software_type::SQLServer:
m_data[7] = 0x74;
break;
case navicat_software_type::SQLite:
m_data[7] = 0x78;
break;
case navicat_software_type::MariaDB:
m_data[7] = 0x7C;
break;
case navicat_software_type::MongoDB:
m_data[7] = 0x80;
break;
case navicat_software_type::ReportViewer:
m_data[7] = 0xb;
break;
case navicat_software_type::ChartsCreator:
m_data[7] = 0x86;
break;
case navicat_software_type::ChartsViewer:
m_data[7] = 0x88;
break;
default:
break;
}
}
void navicat_serial_generator::set_software_type(uint8_t software_type_sig) noexcept {
m_data[7] = software_type_sig;
}
void navicat_serial_generator::set_software_version(int ver) {
if (1 <= ver && ver < 16) {
static_assert(sizeof(m_des_key) == sizeof(s_des_key0));
m_data[8] = static_cast<std::uint8_t>((ver << 4) | (m_data[8] & 0x0f));
memcpy(m_des_key, s_des_key0, sizeof(s_des_key0));
} else if (16 <= ver && ver < 32) {
static_assert(sizeof(m_des_key) == sizeof(s_des_key1));
m_data[8] = static_cast<std::uint8_t>(((ver - 16) << 4) | (m_data[8] & 0x0f));
memcpy(m_des_key, s_des_key1, sizeof(s_des_key1));
} else {
throw version_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid navicat version.");
}
}
void navicat_serial_generator::generate() {
RAND_bytes(m_data + 2, 3);
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
if (!OSSL_PROVIDER_available(nullptr, "legacy")) {
if (OSSL_PROVIDER_load(nullptr, "legacy") == nullptr) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_PROVIDER_load failed.");
}
}
#endif
resource_wrapper evp_cipher_context{ resource_traits::openssl::evp_cipher_ctx{}, EVP_CIPHER_CTX_new() };
if (!evp_cipher_context.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_CIPHER_CTX_new failed.");
}
if (EVP_EncryptInit(evp_cipher_context.get(), EVP_des_ecb(), m_des_key, nullptr) <= 0) { // return 1 for success and 0 for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_EncryptInit failed.");
}
if (int _; EVP_EncryptUpdate(evp_cipher_context.get(), m_data + 2, &_, m_data + 2, 8) <= 0) { // return 1 for success and 0 for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_EncryptUpdate failed.");
}
m_serial_number = base32_rfc4648::encode(m_data, sizeof(m_data));
std::transform(m_serial_number.begin(), m_serial_number.end(), m_serial_number.begin(), _replace_confusing_chars);
std::string_view sn = m_serial_number;
m_serial_number_formatted = fmt::format("{}-{}-{}-{}", sn.substr(0, 4), sn.substr(4, 4), sn.substr(8, 4), sn.substr(12, 4));
}
[[nodiscard]]
const std::string& navicat_serial_generator::serial_number() const noexcept {
return m_serial_number;
}
[[nodiscard]]
const std::string& navicat_serial_generator::serial_number_formatted() const noexcept {
return m_serial_number_formatted;
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,82 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include "exception.hpp"
namespace nkg {
enum class navicat_software_language {
English,
SimplifiedChinese,
TraditionalChinese,
Japanese,
Polish,
Spanish,
French,
German,
Korean,
Russian,
Portuguese
};
enum class navicat_software_type {
DataModeler,
Premium,
MySQL,
PostgreSQL,
Oracle,
SQLServer,
SQLite,
MariaDB,
MongoDB,
ReportViewer,
ChartsCreator,
ChartsViewer
};
class navicat_serial_generator {
public:
class version_error;
class backend_error;
private:
static inline const uint8_t s_des_key0[8] = {0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27};
static inline const uint8_t s_des_key1[8] = {0xE9, 0x7F, 0xB0, 0x60, 0x77, 0x45, 0x90, 0xAE};
uint8_t m_data[10];
uint8_t m_des_key[8];
std::string m_serial_number;
std::string m_serial_number_formatted;
static char _replace_confusing_chars(char c) noexcept;
public:
navicat_serial_generator() noexcept;
void set_software_language(navicat_software_language lang) noexcept;
void set_software_language(uint8_t lang_sig0, uint8_t lang_sig1) noexcept;
void set_software_type(navicat_software_type software_type) noexcept;
void set_software_type(uint8_t software_type_sig) noexcept;
void set_software_version(int Version);
void generate();
[[nodiscard]]
const std::string& serial_number() const noexcept;
[[nodiscard]]
const std::string& serial_number_formatted() const noexcept;
};
class navicat_serial_generator::version_error : public ::nkg::exception {
using ::nkg::exception::exception;
};
class navicat_serial_generator::backend_error : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

@ -1,121 +0,0 @@
#include <stdio.h>
#include <functional>
#include "exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#include "cp_converter.hpp"
#include "base64_rfc4648.hpp"
#include "navicat_serial_generator.hpp"
#include "rsa_cipher.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\wmain.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
using fnCollectInformation = std::function<navicat_serial_generator()>;
using fnGenerateLicense = std::function<void(const rsa_cipher& cipher, const navicat_serial_generator& generator)>;
navicat_serial_generator CollectInformationNormal();
navicat_serial_generator CollectInformationAdvanced();
void GenerateLicenseText(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator);
void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator);
}
static void welcome() {
_putws(L"***************************************************");
_putws(L"* navicat-keygen by @DoubleLabyrinth *");
_putws(L"* version: 16.0.7.0-2 *");
_putws(L"***************************************************");
_putws(L"");
}
static void help() {
_putws(L"Usage:");
_putws(L" navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>");
_putws(L"");
_putws(L" <-bin|-text> Specify \"-bin\" to generate \"license_file\" used by Navicat 11.");
_putws(L" Specify \"-text\" to generate base64-encoded activation code.");
_putws(L" This parameter is mandatory.");
_putws(L"");
_putws(L" [-adv] Enable advance mode.");
_putws(L" This parameter is optional.");
_putws(L"");
_putws(L" <RSA-2048 Private Key File> A path to an RSA-2048 private key file.");
_putws(L" This parameter is mandatory.");
_putws(L"");
_putws(L"Example:");
_putws(L" navicat-keygen.exe -text .\\RegPrivateKey.pem");
}
int wmain(int argc, wchar_t* argv[]) {
welcome();
if (argc == 3 || argc == 4) {
nkg::fnCollectInformation lpfnCollectInformation;
nkg::fnGenerateLicense lpfnGenerateLicense;
if (_wcsicmp(argv[1], L"-bin") == 0) {
lpfnGenerateLicense = nkg::GenerateLicenseBinary;
} else if (_wcsicmp(argv[1], L"-text") == 0) {
lpfnGenerateLicense = nkg::GenerateLicenseText;
} else {
help();
return -1;
}
if (argc == 3) {
lpfnCollectInformation = nkg::CollectInformationNormal;
} else if (argc == 4 && _wcsicmp(argv[2], L"-adv") == 0) {
lpfnCollectInformation = nkg::CollectInformationAdvanced;
} else {
help();
return -1;
}
try {
nkg::rsa_cipher cipher;
cipher.import_private_key_file(nkg::cp_converter<-1, CP_UTF8>::convert(argv[argc - 1]));
if (cipher.bits() != 2048) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"RSA key length != 2048 bits.")
.push_hint(u8"You must provide an RSA key whose modulus length is 2048 bits.");
}
auto sn_generator = lpfnCollectInformation();
sn_generator.generate();
_putws(L"[*] Serial number:");
_putws(nkg::cp_converter<CP_UTF8, -1>::convert(sn_generator.serial_number_formatted()).c_str());
_putws(L"");
lpfnGenerateLicense(cipher, sn_generator);
return 0;
} catch (nkg::exceptions::operation_canceled_exception&) {
return -1;
} catch (nkg::exception& e) {
wprintf_s(L"[-] %s:%d ->\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.source_file()).c_str(), e.source_line());
wprintf_s(L" %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.custom_message()).c_str());
if (e.error_code_exists()) {
wprintf_s(L" %s (0x%zx)\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.error_string()).c_str(), e.error_code());
}
for (auto& hint : e.hints()) {
wprintf_s(L" Hints: %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(hint).c_str());
}
return -1;
} catch (std::exception& e) {
wprintf_s(L"[-] %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.what()).c_str());
return -1;
}
} else {
help();
return -1;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -0,0 +1,95 @@
#include "CapstoneDisassembler.hpp"
namespace nkg {
CapstoneDisassembler::CapstoneDisassembler(const CapstoneEngine& Engine) :
ARL::ResourceWrapper<ARL::ResourceTraits::CapstoneInsn>(cs_malloc(Engine)),
m_Engine(Engine),
m_CurrentState{},
m_NextState{},
m_lpCurrentInsn(nullptr)
{
if (IsValid() == false) {
throw ARL::CapstoneError(__FILE__, __LINE__, cs_errno(Engine), "cs_malloc failed.");
}
}
CapstoneDisassembler& CapstoneDisassembler::SetContext(const CapstoneContext& Ctx) noexcept {
m_lpCurrentInsn = nullptr;
m_CurrentState.lpMachineCode = nullptr;
m_CurrentState.cbMachineCode = 0;
m_CurrentState.Address = 0;
m_NextState = Ctx;
return *this;
}
[[nodiscard]]
const CapstoneContext& CapstoneDisassembler::GetContext() const noexcept {
return m_NextState;
}
[[nodiscard]]
bool CapstoneDisassembler::Next() noexcept {
bool bSucceed;
CapstoneContext backup = m_NextState;
bSucceed = cs_disasm_iter(m_Engine.Get(), reinterpret_cast<const uint8_t**>(&m_NextState.lpMachineCode), &m_NextState.cbMachineCode, &m_NextState.Address, Get());
if (bSucceed) {
if (m_lpCurrentInsn == nullptr) {
m_lpCurrentInsn = Get();
}
m_CurrentState = backup;
} else {
m_lpCurrentInsn = nullptr;
}
return bSucceed;
}
[[nodiscard]]
const cs_insn* CapstoneDisassembler::GetInstruction() const noexcept {
return m_lpCurrentInsn;
}
[[nodiscard]]
const CapstoneContext& CapstoneDisassembler::GetInstructionContext() const noexcept {
return m_CurrentState;
}
CapstoneEngine::CapstoneEngine(cs_arch ArchType, cs_mode Mode) {
auto err = cs_open(ArchType, Mode, GetAddressOf());
if (err != CS_ERR_OK) {
throw ARL::CapstoneError(__FILE__, __LINE__, err, "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 ARL::CapstoneError(__FILE__, __LINE__, err, "cs_option failed.");
}
}
const char* CapstoneEngine::GetGroupName(unsigned int group_id) const noexcept {
return cs_group_name(Get(), group_id);
}
const char* CapstoneEngine::GetInstructionName(unsigned int instruction_id) const noexcept {
return cs_insn_name(Get(), instruction_id);
}
const char* CapstoneEngine::GetRegisterName(unsigned int register_id) const noexcept {
return cs_reg_name(Get(), register_id);
}
[[nodiscard]]
CapstoneDisassembler CapstoneEngine::CreateDisassembler() const {
return CapstoneDisassembler(*this);
}
}

View File

@ -0,0 +1,63 @@
#pragma once
#include <capstone/capstone.h>
#include "ExceptionCapstone.hpp"
#include "ResourceWrapper.hpp"
#include "ResourceTraitsCapstone.hpp"
namespace nkg {
struct CapstoneContext {
const void* lpMachineCode;
size_t cbMachineCode;
uint64_t Address;
};
class CapstoneEngine;
class CapstoneDisassembler : private ARL::ResourceWrapper<ARL::ResourceTraits::CapstoneInsn> {
friend class CapstoneEngine;
private:
const CapstoneEngine& m_Engine;
CapstoneContext m_CurrentState;
CapstoneContext m_NextState;
cs_insn* m_lpCurrentInsn;
CapstoneDisassembler(const CapstoneEngine& Engine);
public:
CapstoneDisassembler& SetContext(const CapstoneContext& Ctx) noexcept;
[[nodiscard]]
const CapstoneContext& GetContext() const noexcept;
[[nodiscard]]
bool Next() noexcept;
[[nodiscard]]
const cs_insn* GetInstruction() const noexcept;
[[nodiscard]]
const CapstoneContext& GetInstructionContext() const noexcept;
};
class CapstoneEngine : private ARL::ResourceWrapper<ARL::ResourceTraits::CapstoneHandle> {
friend class CapstoneDisassembler;
public:
CapstoneEngine(cs_arch ArchType, cs_mode Mode);
void Option(cs_opt_type Type, cs_opt_value Value);
const char* GetGroupName(unsigned int group_id) const noexcept;
const char* GetInstructionName(unsigned int instruction_id) const noexcept;
const char* GetRegisterName(unsigned int register_id) const noexcept;
[[nodiscard]]
CapstoneDisassembler CreateDisassembler() const;
};
}

View File

@ -0,0 +1,38 @@
#pragma once
#include <capstone/capstone.h>
#include "Exception.hpp"
namespace ARL {
class CapstoneError final : public Exception {
private:
cs_err m_ErrorCode;
public:
template<typename... __ArgTypes>
CapstoneError(const char* SourceFile, size_t SourceLine, cs_err ErrorCode, const char* Format, __ArgTypes&&... Args) noexcept :
Exception(SourceFile, SourceLine, Format, std::forward<__ArgTypes>(Args)...),
m_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 m_ErrorCode;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
return cs_strerror(m_ErrorCode);
}
};
}

View File

@ -0,0 +1,38 @@
#pragma once
#include <keystone/keystone.h>
#include "Exception.hpp"
namespace ARL {
class KeystoneError final : public Exception {
private:
ks_err m_ErrorCode;
public:
template<typename... __ArgTypes>
KeystoneError(const char* SourceFile, size_t SourceLine, ks_err ErrorCode, const char* Format, __ArgTypes&&... Args) noexcept :
Exception(SourceFile, SourceLine, Format, std::forward<__ArgTypes>(Args)...),
m_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 m_ErrorCode;
}
[[nodiscard]]
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual const char* ErrorString() const noexcept override {
return ks_strerror(m_ErrorCode);
}
};
}

View File

@ -0,0 +1,40 @@
#include "KeystoneAssembler.hpp"
namespace nkg {
KeystoneAssembler::KeystoneAssembler(const KeystoneEngine& Engine) noexcept :
m_Engine(Engine) {}
[[nodiscard]]
std::vector<uint8_t> KeystoneAssembler::GenerateMachineCode(std::string_view AssemblyCode, uint64_t Address) const {
ARL::ResourceWrapper pbMachineCode(ARL::ResourceTraits::KeystoneMalloc{});
size_t cbMachineCode = 0;
size_t InstructionsProcessed = 0;
if (ks_asm(m_Engine, AssemblyCode.data(), Address, pbMachineCode.GetAddressOf(), &cbMachineCode, &InstructionsProcessed) != 0) {
throw ARL::KeystoneError(__FILE__, __LINE__, ks_errno(m_Engine), "ks_asm failed.");
}
return std::vector<uint8_t>(pbMachineCode.Get(), pbMachineCode.Get() + cbMachineCode);
}
KeystoneEngine::KeystoneEngine(ks_arch ArchType, ks_mode Mode) {
auto err = ks_open(ArchType, Mode, GetAddressOf());
if (err != KS_ERR_OK) {
throw ARL::KeystoneError(__FILE__, __LINE__, err, "ks_open failed.");
}
}
void KeystoneEngine::Option(ks_opt_type Type, ks_opt_value Value) {
auto err = ks_option(Get(), Type, Value);
if (err != KS_ERR_OK) {
throw ARL::KeystoneError(__FILE__, __LINE__, err, "ks_option failed.");
}
}
KeystoneAssembler KeystoneEngine::CreateAssembler() const {
return KeystoneAssembler(*this);
}
}

View File

@ -0,0 +1,40 @@
#pragma once
#include "ExceptionKeystone.hpp"
#include "ResourceWrapper.hpp"
#include "ResourceTraitsKeystone.hpp"
#include <vector>
#include <string>
namespace nkg {
class KeystoneEngine;
class KeystoneAssembler {
friend class KeystoneEngine;
private:
const KeystoneEngine& m_Engine;
KeystoneAssembler(const KeystoneEngine& Engine) noexcept;
public:
[[nodiscard]]
std::vector<uint8_t> GenerateMachineCode(std::string_view AssemblyCode, uint64_t Address = 0) const;
};
class KeystoneEngine : private ARL::ResourceWrapper<ARL::ResourceTraits::KeystoneHandle> {
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;
};
}

View File

@ -0,0 +1,151 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <type_traits>
namespace ARL {
template<typename __PtrType1, typename __PtrType2>
[[nodiscard]]
inline ptrdiff_t AddressDelta(__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>
[[nodiscard]]
inline __PtrType AddressOffset(__PtrType p, ptrdiff_t 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>
[[nodiscard]]
inline __ReturnType AddressOffsetWithCast(__PtrType p, ptrdiff_t 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
)
);
}
template<typename __PtrType, typename __BeginPtrType, typename __EndPtrType>
[[nodiscard]]
inline bool AddressIsInRange(__PtrType p, __BeginPtrType begin, __EndPtrType end) {
static_assert(std::is_pointer_v<__PtrType>);
static_assert(std::is_pointer_v<__BeginPtrType>);
static_assert(std::is_pointer_v<__EndPtrType>);
return
reinterpret_cast<const volatile char*>(begin) <= reinterpret_cast<const volatile char*>(p) &&
reinterpret_cast<const volatile char*>(p) < reinterpret_cast<const volatile char*>(end);
}
template<typename __PtrType, typename __BasePtrType>
[[nodiscard]]
inline bool AddressIsInRange(__PtrType p, __BasePtrType base, size_t size) {
static_assert(std::is_pointer_v<__PtrType>);
static_assert(std::is_pointer_v<__BasePtrType>);
return AddressIsInRange(p, base, AddressOffset(base, size));
}
template<typename __PtrType1, typename __PtrType2, typename __BeginPtrType, typename __EndPtrType>
[[nodiscard]]
inline bool AddressIsInRangeEx(__PtrType1 p1, __PtrType2 p2, __BeginPtrType begin, __EndPtrType end) {
static_assert(std::is_pointer_v<__PtrType1>);
static_assert(std::is_pointer_v<__PtrType2>);
static_assert(std::is_pointer_v<__BeginPtrType>);
static_assert(std::is_pointer_v<__EndPtrType>);
return
reinterpret_cast<const volatile char*>(begin) <= reinterpret_cast<const volatile char*>(p1) &&
reinterpret_cast<const volatile char*>(p1) <= reinterpret_cast<const volatile char*>(p2) &&
reinterpret_cast<const volatile char*>(p2) <= reinterpret_cast<const volatile char*>(end);
}
template<typename __PtrType, typename __BeginPtrType, typename __EndPtrType>
[[nodiscard]]
inline bool AddressIsInRangeEx(__PtrType p, size_t s, __BeginPtrType begin, __EndPtrType end) {
static_assert(std::is_pointer_v<__PtrType>);
static_assert(std::is_pointer_v<__BeginPtrType>);
static_assert(std::is_pointer_v<__EndPtrType>);
return AddressIsInRange(p, AddressDelta(p, s), begin, end);
}
template<typename __PtrType1, typename __PtrType2, typename __BasePtrType>
[[nodiscard]]
inline bool AddressIsInRangeEx(__PtrType1 p1, __PtrType2 p2, __BasePtrType base, size_t size) {
static_assert(std::is_pointer_v<__PtrType1>);
static_assert(std::is_pointer_v<__PtrType2>);
static_assert(std::is_pointer_v<__BasePtrType>);
return AddressIsInRangeEx(p1, p2, base, AddressOffset(base, size));
}
template<typename __PtrType, typename __BasePtrType>
[[nodiscard]]
inline bool AddressIsInRangeEx(__PtrType p, size_t s, __BasePtrType base, size_t size) {
static_assert(std::is_pointer_v<__PtrType>);
static_assert(std::is_pointer_v<__BasePtrType>);
return AddressIsInRangeEx(p, AddressOffset(p, s), base, AddressOffset(base, size));
}
template<typename __ReadType, typename __PtrType>
[[nodiscard]]
inline __ReadType AddressRead(__PtrType p) noexcept {
static_assert(std::is_trivial_v<__ReadType> && std::is_standard_layout_v<__ReadType>);
static_assert(std::is_pointer_v<__PtrType>);
return *reinterpret_cast<const volatile __ReadType*>(p);
}
template<typename __ReadType, typename __PtrType>
[[nodiscard]]
inline __ReadType AddressRead(__PtrType p, ptrdiff_t offset) noexcept {
static_assert(std::is_trivial_v<__ReadType> && std::is_standard_layout_v<__ReadType>);
static_assert(std::is_pointer_v<__PtrType>);
return *reinterpret_cast<const volatile __ReadType*>(
reinterpret_cast<const volatile char*>(p) + offset
);
}
template<typename __ReadType, typename __PtrType>
[[nodiscard]]
inline __ReadType AddressRead(__PtrType p, size_t scale, ptrdiff_t index) noexcept {
static_assert(std::is_trivial_v<__ReadType> && std::is_standard_layout_v<__ReadType>);
static_assert(std::is_pointer_v<__PtrType>);
return *reinterpret_cast<const volatile __ReadType*>(
reinterpret_cast<const volatile char*>(p) + scale * index
);
}
template<typename __WriteType, typename __PtrType>
inline void AddressWrite(__PtrType p, const __WriteType& value) noexcept {
static_assert(std::is_trivial_v<__WriteType> && std::is_standard_layout_v<__WriteType>);
static_assert(std::is_pointer_v<__PtrType>);
*reinterpret_cast<volatile __WriteType*>(p) = value;
}
template<typename __WriteType, typename __PtrType>
inline void AddressWrite(__PtrType p, ptrdiff_t offset, const __WriteType& value) noexcept {
static_assert(std::is_trivial_v<__WriteType> && std::is_standard_layout_v<__WriteType>);
static_assert(std::is_pointer_v<__PtrType>);
*reinterpret_cast<volatile __WriteType*>(
reinterpret_cast<volatile char*>(p) + offset
) = value;
}
template<typename __WriteType, typename __PtrType>
inline void AddressWrite(__PtrType p, size_t scale, ptrdiff_t index, const __WriteType& value) noexcept {
static_assert(std::is_trivial_v<__WriteType> && std::is_standard_layout_v<__WriteType>);
static_assert(std::is_pointer_v<__PtrType>);
*reinterpret_cast<volatile __WriteType*>(
reinterpret_cast<volatile char*>(p) + scale * index
) = value;
}
}

166
navicat-patcher/Misc.cpp Normal file
View File

@ -0,0 +1,166 @@
#include "Misc.hpp"
#include <stdint.h>
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include "ExceptionSystem.hpp"
static jmp_buf g_jmbuf;
static void SIGSEGV_handler(int sig) {
siglongjmp(g_jmbuf, 1);
}
//
// read byte(s) at address `p` as __Type to `out`
// succeed if return true, otherwise return false
//
template<typename __Type>
static inline bool probe_for_read(const void* p, void* out) {
int r = sigsetjmp(g_jmbuf, 1);
if (r == 0) {
*reinterpret_cast<__Type*>(out) = *reinterpret_cast<const __Type*>(p);
return true;
} else {
return false;
}
}
namespace nkg::Misc {
//
// 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) {
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>(pbBegin));
}
for (int i = 0; i < 16; ++i) {
if (pbBegin + i < lpMemBegin || pbBegin + i >= lpMemEnd) {
printf(" ");
Values[i] = 0xfffe;
} else if (probe_for_read<uint8_t>(pbBegin + i, Values + i)) {
printf("%02x ", Values[i]);
} else {
printf("?? ");
Values[i] = 0xffff;
}
}
printf(" ");
for (int i = 0; i < 16; ++i) {
if (0x20 <= Values[i] && Values[i] < 0x7f) {
printf("%c", Values[i]);
} else if (Values[i] == 0xfffe) {
printf(" ");
} else {
printf(".");
}
}
printf("\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);
}
[[nodiscard]]
bool FsIsExist(std::string_view szPath) {
struct stat s = {};
if (stat(szPath.data(), &s) == 0) {
return true;
} else {
if (errno == ENOENT) {
return false;
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "stat failed.");
}
}
}
[[nodiscard]]
bool FsIsFile(std::string_view szPath) {
struct stat s = {};
if (stat(szPath.data(), &s) == 0) {
return S_ISREG(s.st_mode);
} else {
if (errno == ENOENT) {
return false;
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "stat failed.");
}
}
}
[[nodiscard]]
bool FsIsDirectory(std::string_view szPath) {
struct stat s = {};
if (stat(szPath.data(), &s) == 0) {
return S_ISDIR(s.st_mode);
} else {
if (errno == ENOENT) {
return false;
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "stat failed.");
}
}
}
[[nodiscard]]
std::string FsCurrentWorkingDirectory() {
std::string path(256, '\x00');
while (getcwd(path.data(), path.size()) == 0) {
if (errno == ERANGE) {
path.resize(path.size() * 2);
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "getcwd failed.");
}
}
path.resize(strlen(path.data()));
return path;
}
}

31
navicat-patcher/Misc.hpp Normal file
View File

@ -0,0 +1,31 @@
#pragma once
#include <stddef.h>
#include <string>
namespace nkg::Misc {
//
// Print memory data in [lpMemBegin, lpMemEnd)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
//
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.
//
void PrintMemory(const void* lpMem, size_t cbMem, const void* lpBase) noexcept;
[[nodiscard]]
bool FsIsExist(std::string_view szPath);
[[nodiscard]]
bool FsIsFile(std::string_view szPath);
[[nodiscard]]
bool FsIsDirectory(std::string_view szPath);
[[nodiscard]]
std::string FsCurrentWorkingDirectory();
}

View File

@ -0,0 +1,88 @@
#include "PatchSolutions.hpp"
#include "Misc.hpp"
#include <memory.h>
namespace nkg {
const char PatchSolution0::Keyword[451] =
"-----BEGIN PUBLIC KEY-----\x00"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I\x00"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv\x00"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF\x00"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2\x00"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt\x00"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ\x00"
"awIDAQAB\x00"
"-----END PUBLIC KEY-----";
PatchSolution0::PatchSolution0(const X64ImageInterpreter& Image) :
m_Image(Image) {}
[[nodiscard]]
bool PatchSolution0::FindPatchOffset() noexcept {
try {
auto lpPatch = m_Image.SearchSection("__TEXT", "__cstring", [](const void* base, size_t i, size_t size) {
if (i + sizeof(Keyword) <= size) {
auto p = ARL::AddressOffset(base, i);
return memcmp(p, Keyword, sizeof(Keyword) - 1) == 0;
} else {
return false;
}
});
if (lpPatch) {
m_PatchOffset = m_Image.ConvertPtrToOffset(lpPatch);
} else {
throw ARL::Exception(__FILE__, __LINE__, "not found.");
}
printf("[+] PatchSolution0 ...... Ready to apply.\n");
printf(" Keyword offset = +0x%.8x\n", m_PatchOffset.value());
return true;
} catch (...) {
printf("[-] PatchSolution0 ...... Omitted.\n");
return false;
}
}
[[nodiscard]]
bool PatchSolution0::CheckKey(const RSACipher& Cipher) const noexcept {
try {
return Cipher.Bits() == 2048;
} catch (...) {
return false;
}
}
void PatchSolution0::MakePatch(const RSACipher& Cipher) const {
if (m_PatchOffset.has_value()) {
std::string szPublicKeyPEM = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto& c : szPublicKeyPEM) {
if (c == '\n') {
c = '\x00';
}
}
while (szPublicKeyPEM.length() < sizeof(Keyword)) {
szPublicKeyPEM.push_back('\x00');
}
auto lpPatch = m_Image.ImageOffset(m_PatchOffset.value());
puts("**************************************************************");
puts("* PatchSolution0 *");
puts("**************************************************************");
printf("[*] Previous:\n");
Misc::PrintMemory(lpPatch, sizeof(Keyword), m_Image.ImageBase());
memcpy(lpPatch, szPublicKeyPEM.data(), sizeof(Keyword));
printf("[*] After:\n");
Misc::PrintMemory(lpPatch, sizeof(Keyword), m_Image.ImageBase());
printf("\n");
} else {
throw ARL::Exception(__FILE__, __LINE__, "PatchSolution0: not ready yet.");
}
}
}

View File

@ -0,0 +1,129 @@
#include "PatchSolutions.hpp"
#include "Misc.hpp"
#include <memory.h>
namespace nkg {
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
};
PatchSolution1::PatchSolution1(const X64ImageInterpreter& Image) :
m_Image(Image) {}
[[nodiscard]]
bool PatchSolution1::FindPatchOffset() noexcept {
try {
void* lpPatch = nullptr;
for (size_t i = 0; i < m_Image.NumberOfSections(); ++i) {
auto section = m_Image.ImageSection(i);
if (section->size >= sizeof(Keyword)) {
lpPatch = m_Image.SearchSection(section, [](const void* base, size_t i, size_t size) {
if (i + sizeof(Keyword) <= size) {
return memcmp(ARL::AddressOffset(base, i), Keyword, sizeof(Keyword)) == 0;
} else {
return false;
}
});
if (lpPatch) {
m_PatchOffset = m_Image.ConvertPtrToOffset(lpPatch);
break;
}
}
}
if (lpPatch) {
printf("[+] PatchSolution1 ...... Ready to apply.\n");
printf(" Keyword offset = +0x%.8x\n", m_PatchOffset.value());
return true;
} else {
throw ARL::Exception(__FILE__, __LINE__, "not found.");
}
} catch (...) {
printf("[-] PatchSolution1 ...... Omitted.\n");
return false;
}
}
[[nodiscard]]
bool PatchSolution1::CheckKey(const RSACipher& Cipher) const noexcept {
try {
return Cipher.Bits() == 2048;
} catch (...) {
return false;
}
}
void PatchSolution1::MakePatch(const RSACipher& Cipher) const {
if (m_PatchOffset.has_value()) {
auto szPublicKeyPEM = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKeyPEM.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKeyPEM.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKeyPEM.erase(pos, strlen("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKeyPEM.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKeyPEM.find("-----END PUBLIC KEY-----", pos)) {
szPublicKeyPEM.erase(pos, strlen("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKeyPEM.find('\n'); pos != std::string::npos; pos = szPublicKeyPEM.find('\n', pos)) {
szPublicKeyPEM.erase(pos, 1);
}
for (size_t i = 0, key = 8; i < szPublicKeyPEM.length(); ++i, --key) {
if (key == 0) {
key = 8;
}
szPublicKeyPEM[i] ^= static_cast<char>(0xBB - key);
}
while (szPublicKeyPEM.length() < sizeof(Keyword)) {
szPublicKeyPEM.push_back('\x00');
}
auto lpPatch = m_Image.ImageOffset(m_PatchOffset.value());
puts("**************************************************************");
puts("* PatchSolution1 *");
puts("**************************************************************");
printf("[*] Previous:\n");
Misc::PrintMemory(lpPatch, sizeof(Keyword), m_Image.ImageBase());
memcpy(lpPatch, szPublicKeyPEM.data(), sizeof(Keyword));
printf("[*] After:\n");
Misc::PrintMemory(lpPatch, sizeof(Keyword), m_Image.ImageBase());
printf("\n");
} else {
throw ARL::Exception(__FILE__, __LINE__, "PatchSolution1: not ready yet.");
}
}
}

View File

@ -0,0 +1,301 @@
#include "PatchSolutions.hpp"
#include "Misc.hpp"
#include <string.h>
namespace nkg {
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";
PatchSolution2::PatchSolution2(const X64ImageInterpreter& Image) :
m_Image(Image),
m_DisassemblerEngine(CS_ARCH_X86, CS_MODE_64),
m_AssemblerEngine(KS_ARCH_X86, KS_MODE_64)
{
m_DisassemblerEngine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
[[nodiscard]]
const char* PatchSolution2::TryResolveStubHelper(const void* lpStubHelperProc) const {
if (auto dyld_info = m_Image.SpecialLoadCommand<LC_DYLD_INFO_ONLY>(); dyld_info) {
auto Disassembler = m_DisassemblerEngine.CreateDisassembler();
// A stub-helper proc must look like:
// push xxxxh;
// jmp loc_xxxxxxxx
// which should be 10 bytes long.
Disassembler.SetContext({ lpStubHelperProc, 10, 0 });
if (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (strcasecmp(lpInsn->mnemonic, "push") == 0 && lpInsn->detail->x86.operands[0].type == X86_OP_IMM) {
auto pbBindOpcode =
m_Image.ImageOffset<const uint8_t*>(dyld_info->lazy_bind_off) +
lpInsn->detail->x86.operands[0].imm;
while ((*pbBindOpcode & BIND_OPCODE_MASK) != BIND_OPCODE_DONE) {
switch (*pbBindOpcode & 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
++pbBindOpcode;
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 (*(++pbBindOpcode) & 0x80u) {}
++pbBindOpcode;
break;
case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: // 0x40
return reinterpret_cast<const char *>(pbBindOpcode + 1);
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 nullptr;
default:
return nullptr;
}
}
}
}
}
return nullptr;
}
[[nodiscard]]
bool PatchSolution2::FindPatchOffset() noexcept {
try {
std::optional<X64ImageOffset> KeywordOffset;
std::optional<X64ImageOffset> FunctionOffset;
std::optional<X64ImageAddress> StdStringAppendStubRva;
auto section__text = m_Image.ImageSection("__TEXT", "__text");
auto section__stubs = m_Image.ImageSection("__TEXT", "__stubs");
auto sectionview__text = m_Image.ImageSectionView(section__text);
auto sectionview__stubs = m_Image.ImageSectionView(section__stubs);
auto Disassembler = m_DisassemblerEngine.CreateDisassembler();
auto p = m_Image.SearchSection("__TEXT", "__const", [](const void* base, size_t i, size_t size) {
if (i + sizeof(Keyword) <= size) {
return memcmp(ARL::AddressOffset(base, i), Keyword, sizeof(Keyword)) == 0;
} else {
return false;
}
});
if (p) {
KeywordOffset = m_Image.ConvertPtrToOffset(p);
} else {
throw ARL::Exception(__FILE__, __LINE__, "Keyword is not found.");
}
p = m_Image.SearchSection(section__text, [section__text, KeywordRva = m_Image.ConvertOffsetToRva(KeywordOffset.value())](const void* base, size_t i, size_t size) {
if (i + sizeof(uint32_t) <= size) {
auto rip = i + section__text->addr + sizeof(uint32_t);
auto off = ARL::AddressRead<uint32_t>(ARL::AddressOffset(base, i));
return rip + off == KeywordRva;
} else {
return false;
}
});
if (p) {
p = m_Image.SearchSection(
section__text,
ARL::AddressDelta(p, sectionview__text) >= 0xc0 ? ARL::AddressDelta(p, sectionview__text) - 0xc0 : 0,
[p](const void* base, size_t i, size_t size) {
static const uint8_t FunctionHeader[9] = {
0x55, // push rbp
0x48, 0x89, 0xe5, // mov rbp, rsp
0x41, 0x57, // push r15
0x41, 0x56, // push r14
0x53, // push rbx
};
if (ARL::AddressOffset(base, i + sizeof(FunctionHeader)) <= p) {
return memcmp(ARL::AddressOffset(base, i), FunctionHeader, sizeof(FunctionHeader)) == 0;
} else {
return false;
}
}
);
if (p) {
FunctionOffset = m_Image.ConvertPtrToOffset(p);
} else {
throw ARL::Exception(__FILE__, __LINE__, "Function header is not found.");
}
} else {
throw ARL::Exception(__FILE__, __LINE__, "Xref of Keyword is not found.");
}
Disassembler.SetContext({ sectionview__stubs, section__stubs->size, section__stubs->addr });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// As far as I know, all stub functions have a pattern looking like:
// jmp qword ptr [RIP + xxxx]
//
if (strcasecmp(lpInsn->mnemonic, "jmp") == 0 && lpInsn->detail->x86.operands[0].type == X86_OP_MEM && lpInsn->detail->x86.operands[0].mem.base == X86_REG_RIP) {
try {
X64ImageAddress la_symbol_ptr_rva = Disassembler.GetContext().Address + lpInsn->detail->x86.operands[0].mem.disp;
X64ImageOffset la_symbol_ptr_offset = m_Image.ConvertRvaToOffset(la_symbol_ptr_rva);
X64ImageAddress stub_helper_rva = ARL::AddressRead<uint64_t>(m_Image.ImageBase(), la_symbol_ptr_offset);
X64ImageOffset stub_helper_offset = m_Image.ConvertRvaToOffset(stub_helper_rva);
//
// __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'
//
auto lpszSymbolName = TryResolveStubHelper(m_Image.ImageOffset(stub_helper_offset));
if (lpszSymbolName && strcmp(lpszSymbolName, "__ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKc") == 0) {
StdStringAppendStubRva = Disassembler.GetInstructionContext().Address;
break;
}
} catch (...) {
continue;
}
}
}
if (StdStringAppendStubRva.has_value()) {
m_KeywordOffset = KeywordOffset.value();
m_FunctionOffset = FunctionOffset.value();
m_StdStringAppendStubRva = StdStringAppendStubRva.value();
} else {
throw ARL::Exception(__FILE__, __LINE__, "std::string::append(const char*) is not found.");
}
printf("[+] PatchSolution2 ...... Ready to apply.\n");
printf(" Keyword offset = +0x%.8x\n", m_KeywordOffset.value());
printf(" CSRegistrationCenter::obtainPublicKey RVA = 0x%.16llx\n", m_Image.ConvertOffsetToRva(m_FunctionOffset.value()));
printf(" std::string::append(const char*) RVA = 0x%.16llx\n", m_StdStringAppendStubRva.value());
return true;
} catch (...) {
printf("[-] PatchSolution2 ...... Omitted.\n");
return false;
}
}
[[nodiscard]]
bool PatchSolution2::CheckKey(const RSACipher& Cipher) const noexcept {
return Cipher.Bits() == 2048;
}
void PatchSolution2::MakePatch(const RSACipher& Cipher) const {
if (m_KeywordOffset.has_value() && m_FunctionOffset.has_value() && m_StdStringAppendStubRva.has_value()) {
//
// Prepare public key string
//
auto szPublicKeyPEM = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKeyPEM.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKeyPEM.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKeyPEM.erase(pos, strlen("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKeyPEM.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKeyPEM.find("-----END PUBLIC KEY-----", pos)) {
szPublicKeyPEM.erase(pos, strlen("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKeyPEM.find('\n'); pos != std::string::npos; pos = szPublicKeyPEM.find('\n', pos)) {
szPublicKeyPEM.erase(pos, 1);
}
//
// Prepare new function opcodes
//
auto Assembler = m_AssemblerEngine.CreateAssembler();
auto MachineCode = Assembler.GenerateMachineCode(
[KeywordRva = m_Image.ConvertOffsetToRva(m_KeywordOffset.value()), StdStringAppendStubRva = m_StdStringAppendStubRva.value()]() -> std::string {
const char asm_template[] =
"push rbp;"
"mov rbp, rsp;"
"xor rax, rax;" // initialize std::string with null
"mov qword ptr[rdi], rax;"
"mov qword ptr[rdi + 0x8], rax;"
"mov qword ptr[rdi + 0x10], rax;"
"lea rsi, qword ptr[0x%.16llx];" // filled with address to Keyword
"call 0x%.16llx;" // filled with address to std::string::append(const char*)
"leave;"
"ret;";
std::string asm_string;
int l = snprintf(nullptr, 0, asm_template, KeywordRva, StdStringAppendStubRva);
if (l < 0) {
std::terminate();
}
asm_string.resize(l + 1);
l = snprintf(asm_string.data(), asm_string.length(), asm_template, KeywordRva, StdStringAppendStubRva);
if (l < 0) {
std::terminate();
}
while (asm_string.back() == '\x00') {
asm_string.pop_back();
}
return asm_string;
}().c_str(),
m_Image.ConvertOffsetToRva(m_FunctionOffset.value())
);
puts("**************************************************************");
puts("* PatchSolution2 *");
puts("**************************************************************");
auto lpKeyword = m_Image.ImageOffset(m_KeywordOffset.value());
auto lpFunction = m_Image.ImageOffset(m_FunctionOffset.value());
printf("[*] Previous:\n");
Misc::PrintMemory(lpKeyword, szPublicKeyPEM.length() + 1, m_Image.ImageBase());
memcpy(lpKeyword, szPublicKeyPEM.c_str(), szPublicKeyPEM.length() + 1); // with a null-terminator
printf("[*] After:\n");
Misc::PrintMemory(lpKeyword, szPublicKeyPEM.length() + 1, m_Image.ImageBase());
printf("\n");
printf("[*] Previous:\n");
Misc::PrintMemory(lpFunction, MachineCode.size(), m_Image.ImageBase());
memcpy(lpFunction, MachineCode.data(), MachineCode.size());
printf("[*] After:\n");
Misc::PrintMemory(lpFunction, MachineCode.size(), m_Image.ImageBase());
printf("\n");
} else {
throw ARL::Exception(__FILE__, __LINE__, "PatchSolution2: not ready yet.");
}
}
}

View File

@ -0,0 +1,438 @@
#include "PatchSolutions.hpp"
#include "Misc.hpp"
#include <string.h>
namespace nkg {
PatchSolution3::PatchSolution3(const X64ImageInterpreter& Image) :
m_Image(Image),
m_DisassemblerEngine(CS_ARCH_X86, CS_MODE_64),
m_AssemblerEngine(KS_ARCH_X86, KS_MODE_64),
m_lpfnGenerateKeyA(nullptr),
m_lpfnGenerateKeyB(nullptr)
{
m_DisassemblerEngine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
void PatchSolution3::ScanInstructions(std::map<X64ImageAddress, X64ImageSize>& Instructions, const section_64* lpSection, const void* lpProcStart) const {
auto Disassembler = m_DisassemblerEngine.CreateDisassembler();
auto lpMachineCode = lpProcStart;
auto cbMachineCode = lpSection->size - ARL::AddressDelta(lpMachineCode, m_Image.ImageSectionView(lpSection));
auto Address = lpSection->addr + ARL::AddressDelta(lpMachineCode, m_Image.ImageSectionView(lpSection));
Disassembler.SetContext({ lpMachineCode, cbMachineCode, Address });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (Instructions.find(lpInsn->address) == Instructions.end()) {
Instructions.emplace(lpInsn->address, lpInsn->size);
if (lpInsn->mnemonic[0] == 'J' || lpInsn->mnemonic[0] == 'j') {
if (lpInsn->detail->x86.operands[0].type != X86_OP_IMM) { // "jxx reg" / "jxx qword ptr [xxx]" won't be handled.
return;
}
ScanInstructions(Instructions, lpSection, m_Image.ConvertRvaToPtr(lpInsn->detail->x86.operands[0].imm));
if (strcasecmp(lpInsn->mnemonic, "jmp") == 0) {
return;
}
} else if (strcasecmp(lpInsn->mnemonic, "ret") == 0) {
return;
}
} else {
return;
}
}
}
[[nodiscard]]
const char* PatchSolution3::TryResolveStubHelper(const void* lpStubHelperProc) const {
if (auto dyld_info = m_Image.SpecialLoadCommand<LC_DYLD_INFO_ONLY>(); dyld_info) {
auto Disassembler = m_DisassemblerEngine.CreateDisassembler();
// A stub-helper proc must look like:
// push xxxxh;
// jmp loc_xxxxxxxx
// which should be 10 bytes long.
Disassembler.SetContext({ lpStubHelperProc, 10, 0 });
if (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (strcasecmp(lpInsn->mnemonic, "push") == 0 && lpInsn->detail->x86.operands[0].type == X86_OP_IMM) {
auto pbBindOpcode =
m_Image.ImageOffset<const uint8_t*>(dyld_info->lazy_bind_off) +
lpInsn->detail->x86.operands[0].imm;
while ((*pbBindOpcode & BIND_OPCODE_MASK) != BIND_OPCODE_DONE) {
switch (*pbBindOpcode & 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
++pbBindOpcode;
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 (*(++pbBindOpcode) & 0x80u) {}
++pbBindOpcode;
break;
case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: // 0x40
return reinterpret_cast<const char *>(pbBindOpcode + 1);
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 nullptr;
default:
return nullptr;
}
}
}
}
}
return nullptr;
}
[[nodiscard]]
bool PatchSolution3::FindPatchOffset() noexcept {
try {
auto section__text = m_Image.ImageSection("__TEXT", "__text");
auto section__cstring = m_Image.ImageSection("__TEXT", "__cstring");
auto section__stubs = m_Image.ImageSection("__TEXT", "__stubs");
auto sectionview__stubs = m_Image.ImageSectionView(section__stubs);
auto Disassembler = m_DisassemblerEngine.CreateDisassembler();
auto Assembler = m_AssemblerEngine.CreateAssembler();
void* lpfnGenerateKeyA = nullptr;
void* lpfnGenerateKeyB = nullptr;
std::optional<X64ImageAddress> StdStringAppendStubRva;
std::vector<uint8_t> fnNewGenerateKeyA;
std::vector<uint8_t> fnNewGenerateKeyB;
//
// find fnGenerateKeyA
//
if (auto lpKeyword = m_Image.SearchSection(section__cstring, [](const void* base, size_t i, size_t size) {
static const char Keyword[] = "K\xd8\x00MjZAGa6R";
if (i + sizeof(Keyword) <= size) {
return memcmp(ARL::AddressOffset(base, i), Keyword, sizeof(Keyword)) == 0;
} else {
return false;
}
}); lpKeyword) {
if (auto lpXrefKeyword = m_Image.SearchSection(section__text, [section__text, KeywordRva = m_Image.ConvertPtrToRva(lpKeyword)](const void* base, size_t i, size_t size) {
if (i + sizeof(uint32_t) <= size) {
auto rip = section__text->addr + (i + 4);
auto off = ARL::AddressRead<uint32_t>(base, i);
return rip + off == KeywordRva;
} else {
return false;
}
}); lpXrefKeyword) {
static const uint8_t FunctionHeader[] = {
0x55, // push rbp
0x48, 0x89, 0xe5 // mov rbp, rsp
};
for (int i = -0x90; i + static_cast<int>(sizeof(FunctionHeader)) < 0; ++i) {
if (memcmp(ARL::AddressOffset(lpXrefKeyword, i), FunctionHeader, sizeof(FunctionHeader)) == 0) {
lpfnGenerateKeyA = ARL::AddressOffset(lpXrefKeyword, i);
break;
}
}
if (lpfnGenerateKeyA == nullptr) {
throw ARL::Exception(__FILE__, __LINE__, "fnGenerateKeyA is not found.");
}
} else {
throw ARL::Exception(__FILE__, __LINE__, "fnGenerateKeyA is not found.");
}
} else {
throw ARL::Exception(__FILE__, __LINE__, "fnGenerateKeyA is not found.");
}
//
// find fnGenerateKeyB
//
if (auto lpKeyword = m_Image.SearchSection(section__cstring, [](const void* base, size_t i, size_t size) {
static const char Keyword[] = "me30I";
if (i + sizeof(Keyword) <= size) {
return memcmp(ARL::AddressOffset(base, i), Keyword, sizeof(Keyword)) == 0;
} else {
return false;
}
}); lpKeyword) {
if (auto lpXrefKeyword = m_Image.SearchSection(section__text, [section__text, KeywordRva = m_Image.ConvertPtrToRva(lpKeyword)](const void* base, size_t i, size_t size) {
if (i + sizeof(uint32_t) <= size) {
auto rip = section__text->addr + (i + 4);
auto off = ARL::AddressRead<uint32_t>(base, i);
return rip + off == KeywordRva;
} else {
return false;
}
}); lpXrefKeyword) {
static const uint8_t FunctionHeader[] = {
0x55, // push rbp
0x48, 0x89, 0xe5 // mov rbp, rsp
};
for (int i = -0x9A; i + static_cast<int>(sizeof(FunctionHeader)) < 0; ++i) {
if (memcmp(ARL::AddressOffset(lpXrefKeyword, i), FunctionHeader, sizeof(FunctionHeader)) == 0) {
lpfnGenerateKeyB = ARL::AddressOffset(lpXrefKeyword, i);
}
}
if (lpfnGenerateKeyB == nullptr) {
throw ARL::Exception(__FILE__, __LINE__, "fnGenerateKeyB is not found.");
}
} else {
throw ARL::Exception(__FILE__, __LINE__, "fnGenerateKeyB is not found.");
}
} else {
throw ARL::Exception(__FILE__, __LINE__, "fnGenerateKeyB is not found.");
}
//
// find std::string::append(const char*)
//
Disassembler.SetContext({ sectionview__stubs, section__stubs->size, section__stubs->addr });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// As far as I know, all stub functions have a pattern looking like:
// jmp qword ptr [RIP + xxxx]
//
if (strcasecmp(lpInsn->mnemonic, "jmp") == 0 && lpInsn->detail->x86.operands[0].type == X86_OP_MEM && lpInsn->detail->x86.operands[0].mem.base == X86_REG_RIP) {
try {
X64ImageAddress la_symbol_ptr_rva = Disassembler.GetContext().Address + lpInsn->detail->x86.operands[0].mem.disp;
X64ImageOffset la_symbol_ptr_offset = m_Image.ConvertRvaToOffset(la_symbol_ptr_rva);
X64ImageAddress stub_helper_rva = ARL::AddressRead<uint64_t>(m_Image.ImageBase(), la_symbol_ptr_offset);
X64ImageOffset stub_helper_offset = m_Image.ConvertRvaToOffset(stub_helper_rva);
//
// __ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKcm
// is the mangled name of "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::append(char const*, size_t)",
// which is, as known as, "std::string::append(const char*, size_t)"
// You can demangle it by c++flit
// e.g.
// c++filt -_ '__ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKcm'
//
auto lpszSymbolName = TryResolveStubHelper(m_Image.ImageOffset(stub_helper_offset));
if (lpszSymbolName && strcmp(lpszSymbolName, "__ZNSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6appendEPKcm") == 0) {
StdStringAppendStubRva = Disassembler.GetInstructionContext().Address;
break;
}
} catch (...) {
continue;
}
}
}
if (StdStringAppendStubRva.has_value() == false) {
throw ARL::Exception(__FILE__, __LINE__, "std::string::append(const char*) is not found.");
}
fnNewGenerateKeyA = Assembler.GenerateMachineCode(
[&StdStringAppendStubRva]() -> std::string {
const char asm_template[] =
"push rbp;"
"mov rbp, rsp;"
"xor rax, rax;" // initialize std::string with null
"mov qword ptr[rdi], rax;"
"mov qword ptr[rdi + 0x8], rax;"
"mov qword ptr[rdi + 0x10], rax;"
"mov edx, 0x188;"
"lea rsi, qword ptr [rip + KeyA];"
"call 0x%.16llx;" // filled with address to std::string::append(const char*, size_t)
"leave;"
"ret;"
"KeyA:";
std::string asm_string;
int l = snprintf(nullptr, 0, asm_template, StdStringAppendStubRva.value());
if (l < 0) {
std::terminate();
}
asm_string.resize(l + 1);
l = snprintf(asm_string.data(), asm_string.length(), asm_template, StdStringAppendStubRva.value());
if (l < 0) {
std::terminate();
}
while (asm_string.back() == '\x00') {
asm_string.pop_back();
}
return asm_string;
}().c_str(),
m_Image.ConvertPtrToRva(lpfnGenerateKeyA)
);
fnNewGenerateKeyB = Assembler.GenerateMachineCode(
[&StdStringAppendStubRva]() -> std::string {
const char asm_template[] =
"push rbp;"
"mov rbp, rsp;"
"xor rax, rax;" // initialize std::string with null
"mov qword ptr[rdi], rax;"
"mov qword ptr[rdi + 0x8], rax;"
"mov qword ptr[rdi + 0x10], rax;"
"mov edx, 0x188;"
"lea rsi, qword ptr [rip + KeyB];"
"call 0x%.16llx;" // filled with address to std::string::append(const char*, size_t)
"leave;"
"ret;"
"KeyB:";
std::string asm_string;
int l = snprintf(nullptr, 0, asm_template, StdStringAppendStubRva.value());
if (l < 0) {
std::terminate();
}
asm_string.resize(l + 1);
l = snprintf(asm_string.data(), asm_string.length(), asm_template, StdStringAppendStubRva.value());
if (l < 0) {
std::terminate();
}
while (asm_string.back() == '\x00') {
asm_string.pop_back();
}
return asm_string;
}().c_str(),
m_Image.ConvertPtrToRva(lpfnGenerateKeyB)
);
{
std::map<X64ImageAddress, X64ImageSize> InstructionMap;
ScanInstructions(InstructionMap, section__text, lpfnGenerateKeyA);
// merging
for (auto it = InstructionMap.begin(); it != InstructionMap.end(); ++it) {
for (auto next_it = std::next(it); it->first + it->second == next_it->first; next_it = InstructionMap.erase(next_it)) {
it->second += next_it->second;
}
}
if (auto it = InstructionMap.find(m_Image.ConvertPtrToRva(lpfnGenerateKeyA)); it != InstructionMap.end()) {
if (fnNewGenerateKeyA.size() + 0x188 > it->second) {
throw ARL::Exception(__FILE__, __LINE__, "No enough space.");
}
} else {
throw ARL::AssertionError(__FILE__, __LINE__, "Something unexpected happened.");
}
}
{
std::map<X64ImageAddress, X64ImageSize> InstructionMap;
ScanInstructions(InstructionMap, section__text, lpfnGenerateKeyB);
// merging
for (auto it = InstructionMap.begin(); it != InstructionMap.end(); ++it) {
for (auto next_it = std::next(it); it->first + it->second == next_it->first; next_it = InstructionMap.erase(next_it)) {
it->second += next_it->second;
}
}
if (auto it = InstructionMap.find(m_Image.ConvertPtrToRva(lpfnGenerateKeyB)); it != InstructionMap.end()) {
if (fnNewGenerateKeyB.size() + 0x188 > it->second) {
throw ARL::Exception(__FILE__, __LINE__, "No enough space.");
}
} else {
throw ARL::AssertionError(__FILE__, __LINE__, "Something unexpected happened.");
}
}
m_lpfnGenerateKeyA = lpfnGenerateKeyA;
m_lpfnGenerateKeyB = lpfnGenerateKeyB;
m_fnNewGenerateKeyA = std::move(fnNewGenerateKeyA);
m_fnNewGenerateKeyB = std::move(fnNewGenerateKeyB);
printf("[+] PatchSolution3 ...... Ready to apply.\n");
printf(" fnGenerateKeyA RVA = 0x%.16llx\n", m_Image.ConvertPtrToRva(m_lpfnGenerateKeyA));
printf(" fnGenerateKeyB RVA = 0x%.16llx\n", m_Image.ConvertPtrToRva(m_lpfnGenerateKeyB));
printf(" std::string::append(const char*, size_t) RVA = 0x%.16llx\n", StdStringAppendStubRva.value());
return true;
} catch (...) {
printf("[-] PatchSolution3 ...... Omitted.\n");
return false;
}
}
[[nodiscard]]
bool PatchSolution3::CheckKey(const RSACipher& Cipher) const noexcept {
return Cipher.Bits() == 2048;
}
void PatchSolution3::MakePatch(const RSACipher& Cipher) const {
if (m_lpfnGenerateKeyA && m_lpfnGenerateKeyB && m_fnNewGenerateKeyA.size() && m_fnNewGenerateKeyB.size()) {
//
// Prepare public key string
//
auto szKeyA = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szKeyA.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szKeyA.find("-----BEGIN PUBLIC KEY-----", pos)) {
szKeyA.erase(pos, strlen("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szKeyA.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szKeyA.find("-----END PUBLIC KEY-----", pos)) {
szKeyA.erase(pos, strlen("-----END PUBLIC KEY-----"));
}
for (auto pos = szKeyA.find('\n'); pos != std::string::npos; pos = szKeyA.find('\n', pos)) {
szKeyA.erase(pos, 1);
}
if (szKeyA.size() < 0x188) {
szKeyA.append(0x188 - szKeyA.size(), '\x00');
}
auto szKeyB = std::string(0x188, '\x00');
puts("**************************************************************");
puts("* PatchSolution3 *");
puts("**************************************************************");
printf("[*] Previous:\n");
Misc::PrintMemory(m_lpfnGenerateKeyA, m_fnNewGenerateKeyA.size() + 0x188, m_Image.ImageBase());
memcpy(m_lpfnGenerateKeyA, m_fnNewGenerateKeyA.data(), m_fnNewGenerateKeyA.size());
memcpy(ARL::AddressOffset(m_lpfnGenerateKeyA, m_fnNewGenerateKeyA.size()), szKeyA.data(), 0x188);
printf("[*] After:\n");
Misc::PrintMemory(m_lpfnGenerateKeyA, m_fnNewGenerateKeyA.size() + 0x188, m_Image.ImageBase());
printf("\n");
printf("[*] Previous:\n");
Misc::PrintMemory(m_lpfnGenerateKeyB, m_fnNewGenerateKeyB.size() + 0x188, m_Image.ImageBase());
memcpy(m_lpfnGenerateKeyB, m_fnNewGenerateKeyB.data(), m_fnNewGenerateKeyB.size());
memcpy(ARL::AddressOffset(m_lpfnGenerateKeyB, m_fnNewGenerateKeyB.size()), szKeyB.data(), 0x188);
printf("[*] After:\n");
Misc::PrintMemory(m_lpfnGenerateKeyB, m_fnNewGenerateKeyB.size() + 0x188, m_Image.ImageBase());
printf("\n");
} else {
throw ARL::Exception(__FILE__, __LINE__, "PatchSolution3: not ready yet.");
}
}
}

View File

@ -0,0 +1,145 @@
#pragma once
#include "Exception.hpp"
#include "RSACipher.hpp"
#include "ResourceTraitsUnix.hpp"
#include "CapstoneDisassembler.hpp"
#include "KeystoneAssembler.hpp"
#include "X64ImageInterpreter.hpp"
#include <map>
#include <optional>
namespace nkg {
class PatchSolution {
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;
};
class PatchSolution0 final : public PatchSolution {
private:
static const char Keyword[451];
const X64ImageInterpreter& m_Image;
std::optional<X64ImageOffset> m_PatchOffset;
public:
PatchSolution0(const X64ImageInterpreter& Image);
[[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& Cipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& Cipher) const override;
};
class PatchSolution1 final : public PatchSolution {
private:
static const uint8_t Keyword[0x188];
const X64ImageInterpreter& m_Image;
std::optional<X64ImageOffset> m_PatchOffset;
public:
PatchSolution1(const X64ImageInterpreter& Image);
[[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& Cipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& Cipher) const override;
};
class PatchSolution2 final : public PatchSolution {
private:
static const char Keyword[1114];
const X64ImageInterpreter& m_Image;
CapstoneEngine m_DisassemblerEngine;
KeystoneEngine m_AssemblerEngine;
std::optional<X64ImageOffset> m_KeywordOffset;
std::optional<X64ImageOffset> m_FunctionOffset;
std::optional<X64ImageAddress> m_StdStringAppendStubRva;
[[nodiscard]]
const char* TryResolveStubHelper(const void* lpStubHelperProc) const;
public:
PatchSolution2(const X64ImageInterpreter& Image);
[[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& Cipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& Cipher) const override;
};
class PatchSolution3 final : public PatchSolution {
private:
const X64ImageInterpreter& m_Image;
CapstoneEngine m_DisassemblerEngine;
KeystoneEngine m_AssemblerEngine;
void* m_lpfnGenerateKeyA;
void* m_lpfnGenerateKeyB;
std::vector<uint8_t> m_fnNewGenerateKeyA;
std::vector<uint8_t> m_fnNewGenerateKeyB;
void ScanInstructions(
std::map<X64ImageAddress, X64ImageSize>& Instructions,
const section_64* lpSection,
const void* lpProcStart
) const;
[[nodiscard]]
const char* TryResolveStubHelper(const void* lpStubHelperProc) const;
public:
PatchSolution3(const X64ImageInterpreter& Image);
[[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& Cipher) const noexcept override;
// NOLINTNEXTLINE: mark "virtual" explicitly for more readability
virtual void MakePatch(const RSACipher& Cipher) const override;
};
}

View File

@ -0,0 +1,40 @@
#pragma once
#include <capstone/capstone.h>
#include "ExceptionCapstone.hpp"
namespace ARL::ResourceTraits {
struct CapstoneHandle {
using HandleType = csh;
static inline const HandleType InvalidValue = 0;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(HandleType& Handle) {
if (auto err = cs_close(&Handle); err != CS_ERR_OK) {
throw ARL::CapstoneError(__FILE__, __LINE__, err, "ks_close failed.");
}
}
};
struct CapstoneInsn {
using HandleType = cs_insn*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) noexcept {
cs_free(Handle, 1);
}
};
}

View File

@ -0,0 +1,41 @@
#pragma once
#include <keystone/keystone.h>
#include "ExceptionKeystone.hpp"
namespace ARL::ResourceTraits {
struct KeystoneHandle {
using HandleType = ks_engine*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) {
auto err = ks_close(Handle);
if (err != KS_ERR_OK) {
throw ARL::KeystoneError(__FILE__, __LINE__, err, "ks_close failed.");
}
}
};
struct KeystoneMalloc {
using HandleType = uint8_t*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) noexcept {
ks_free(Handle);
}
};
}

View File

@ -0,0 +1,38 @@
#pragma once
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
#include "ExceptionSystem.hpp"
namespace ARL::ResourceTraits {
struct FileDescriptor {
using HandleType = int;
static inline const HandleType InvalidValue = -1;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Release(const HandleType& Handle) {
if (close(Handle) != 0) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "close failed.");
}
}
};
struct MapView {
using HandleType = void*;
static inline const HandleType InvalidValue = MAP_FAILED;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
};
}

View File

@ -0,0 +1,143 @@
#include "X64ImageInterpreter.hpp"
namespace nkg {
[[nodiscard]]
X64ImageInterpreter X64ImageInterpreter::Parse(const void* lpImage, size_t cbImage) {
X64ImageInterpreter Interpreter;
Interpreter.m_MachOSize = cbImage;
Interpreter.m_MachOHeader = reinterpret_cast<const mach_header_64*>(lpImage);
if (Interpreter.m_MachOHeader->magic != MH_MAGIC_64) {
throw ARL::AssertionError(__FILE__, __LINE__, "X64ImageInterpreter: bad MachO file: header magic check failure.");
}
auto cmd_p = ARL::AddressOffsetWithCast<const load_command*>(Interpreter.m_MachOHeader, sizeof(mach_header_64));
for (decltype(mach_header_64::ncmds) i = 0; i < Interpreter.m_MachOHeader->ncmds; ++i) {
switch (cmd_p->cmd) {
case LC_SEGMENT_64: {
auto segcmd_p = reinterpret_cast<const segment_command_64*>(cmd_p);
auto section_p = ARL::AddressOffsetWithCast<const section_64*>(segcmd_p, sizeof(segment_command_64));
Interpreter.m_Segments.emplace_back(segcmd_p);
for (decltype(segment_command_64::nsects) j = 0; j < segcmd_p->nsects; ++j) {
Interpreter.m_Sections.emplace_back(&section_p[j]);
Interpreter.m_SectionsAddressMap[section_p[j].addr] = &section_p[j];
Interpreter.m_SectionsOffsetMap[section_p[j].offset] = &section_p[j];
}
break;
}
case LC_DYSYMTAB: {
Interpreter.m_SpecialLoadCommands.dysymtab = reinterpret_cast<const dysymtab_command*>(cmd_p);
break;
}
case LC_SYMTAB: {
Interpreter.m_SpecialLoadCommands.symtab = reinterpret_cast<const symtab_command*>(cmd_p);
break;
}
case LC_DYLD_INFO_ONLY: {
Interpreter.m_SpecialLoadCommands.dyld_info = reinterpret_cast<const dyld_info_command*>(cmd_p);
break;
}
default:
break;
}
cmd_p = ARL::AddressOffset(cmd_p, cmd_p->cmdsize);
}
return Interpreter;
}
[[nodiscard]]
size_t X64ImageInterpreter::NumberOfSegments() const noexcept {
return m_Segments.size();
}
[[nodiscard]]
size_t X64ImageInterpreter::NumberOfSections() const noexcept {
return m_Sections.size();
}
[[nodiscard]]
const segment_command_64* X64ImageInterpreter::ImageSegment(size_t Index) const {
if (Index < m_Segments.size()) {
return m_Segments[Index];
} else {
throw ARL::IndexError(__FILE__, __LINE__, "X64ImageInterpreter: Index is out of range.");
}
}
[[nodiscard]]
const segment_command_64* X64ImageInterpreter::ImageSegment(const char* SegmentName) const {
for (const auto& segment : m_Segments) {
if (strncmp(SegmentName, segment->segname, sizeof(segment->segname)) == 0) {
return segment;
}
}
throw ARL::KeyError(__FILE__, __LINE__, "X64ImageInterpreter: segment is not found.");
}
[[nodiscard]]
const section_64* X64ImageInterpreter::ImageSection(size_t Index) const {
if (Index < m_Sections.size()) {
return m_Sections[Index];
} else {
throw ARL::IndexError(__FILE__, __LINE__, "X64ImageInterpreter: Index is out of range.");
}
}
[[nodiscard]]
const section_64* X64ImageInterpreter::ImageSection(const char* SegmentName, const char* SectionName) const {
for (const auto& segment : m_Segments) {
if (strncmp(SegmentName, segment->segname, sizeof(segment->segname)) == 0) {
auto section = reinterpret_cast<const section_64*>(segment + 1);
for (uint32_t i = 0; i < segment->nsects; ++i) {
if (strncmp(SectionName, section[i].sectname, sizeof(section[i].sectname)) == 0) {
return &section[i];
}
}
break;
}
}
throw ARL::KeyError(__FILE__, __LINE__, "X64ImageInterpreter: section is not found.");
}
[[nodiscard]]
const section_64* X64ImageInterpreter::ImageSectionFromOffset(X64ImageOffset Offset) const {
auto it = m_SectionsOffsetMap.upper_bound(Offset);
if (it != m_SectionsOffsetMap.begin() && (--it, it->first <= Offset && Offset < it->first + it->second->size)) {
return it->second;
} else {
throw ARL::KeyError(__FILE__, __LINE__, "X64ImageInterpreter: section is not found.");
}
}
[[nodiscard]]
const section_64* X64ImageInterpreter::ImageSectionFromRva(X64ImageAddress Rva) const {
auto it = m_SectionsAddressMap.upper_bound(Rva);
if (it != m_SectionsAddressMap.begin() && (--it, it->first <= Rva && Rva < it->first + it->second->size)) {
return it->second;
} else {
throw ARL::KeyError(__FILE__, __LINE__, "X64ImageInterpreter: section is not found.");
}
}
[[nodiscard]]
X64ImageAddress X64ImageInterpreter::ConvertOffsetToRva(X64ImageOffset Offset) const {
auto section = ImageSectionFromOffset(Offset);
return section->addr + static_cast<X64ImageAddress>(Offset - section->offset);
}
[[nodiscard]]
X64ImageOffset X64ImageInterpreter::ConvertRvaToOffset(X64ImageAddress Rva) const {
auto section = ImageSectionFromRva(Rva);
return section->offset + static_cast<X64ImageOffset>(Rva - section->addr);
}
}

View File

@ -0,0 +1,229 @@
#pragma once
#include <mach-o/loader.h>
#include <mach-o/nlist.h>
#include <string.h>
#include <vector>
#include <map>
#include "Exception.hpp"
#include "ExceptionGeneric.hpp"
#include "MemoryAccess.hpp"
namespace nkg {
using X64ImageAddress = decltype(section_64::addr);
using X64ImageOffset = decltype(section_64::offset);
using X64ImageSize = decltype(section_64::size);
class X64ImageInterpreter {
private:
size_t m_MachOSize;
const mach_header_64* m_MachOHeader;
std::vector<const segment_command_64*> m_Segments;
std::vector<const section_64*> m_Sections;
std::map<X64ImageAddress, const section_64*> m_SectionsAddressMap;
std::map<X64ImageOffset, const section_64*> m_SectionsOffsetMap;
struct {
const dysymtab_command* dysymtab;
const symtab_command* symtab;
const dyld_info_command* dyld_info;
} m_SpecialLoadCommands;
X64ImageInterpreter() :
m_MachOSize(0),
m_MachOHeader(nullptr),
m_SpecialLoadCommands{} {}
public:
[[nodiscard]]
static X64ImageInterpreter Parse(const void* lpImage, size_t cbImage);
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageBase() const noexcept {
static_assert(std::is_pointer_v<__ReturnType>);
return reinterpret_cast<__ReturnType>(
const_cast<mach_header_64*>(m_MachOHeader)
);
}
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageOffset(size_t Offset) const {
if (Offset < m_MachOSize) {
return ARL::AddressOffsetWithCast<__ReturnType>(m_MachOHeader, Offset);
} else {
throw ARL::OverflowError(__FILE__, __LINE__, "X64ImageInterpreter: out of range.");
}
}
[[nodiscard]]
size_t ImageSize() const noexcept {
return m_MachOSize;
}
[[nodiscard]]
size_t NumberOfSegments() const noexcept;
[[nodiscard]]
size_t NumberOfSections() const noexcept;
[[nodiscard]]
const segment_command_64* ImageSegment(size_t Index) const;
[[nodiscard]]
const segment_command_64* ImageSegment(const char* SegmentName) const;
[[nodiscard]]
const section_64* ImageSection(size_t Index) const;
[[nodiscard]]
const section_64* ImageSection(const char* SegmentName, const char* SectionName) const;
[[nodiscard]]
const section_64* ImageSectionFromOffset(X64ImageOffset Offset) const;
[[nodiscard]]
const section_64* ImageSectionFromRva(X64ImageAddress Rva) const;
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageSectionView(const section_64* Section) const noexcept {
return ImageOffset<__ReturnType>(Section->offset);
}
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageSectionView(size_t Index) const {
return ImageSectionView<__ReturnType>(ImageSection(Index));
}
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ImageSectionView(const char* SegmentName, const char* SectionName) const {
return ImageSectionView<__ReturnType>(ImageSection(SegmentName, SectionName));
}
template<unsigned __CommandMacro>
[[nodiscard]]
auto SpecialLoadCommand() const noexcept {
if constexpr (__CommandMacro == LC_DYSYMTAB) {
return m_SpecialLoadCommands.dysymtab;
} else if constexpr (__CommandMacro == LC_SYMTAB) {
return m_SpecialLoadCommands.symtab;
} else if constexpr (__CommandMacro == LC_DYLD_INFO_ONLY) {
return m_SpecialLoadCommands.dyld_info;
} else {
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wtautological-compare"
constexpr bool always_false = __CommandMacro != __CommandMacro;
#pragma clang diagnostic pop
static_assert(always_false);
}
}
template<typename __ReturnType = void*, typename __HintType>
[[nodiscard]]
__ReturnType SearchSection(const section_64* Section, __HintType&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto base = ImageSectionView<const uint8_t*>(Section);
for (decltype(section_64::size) i = 0; i < Section->size; ++i) {
if (Hint(base, i, Section->size) == true) {
return ARL::AddressOffsetWithCast<__ReturnType>(base, i);
}
}
return nullptr;
}
template<typename __ReturnType = void*, typename __HintType>
[[nodiscard]]
__ReturnType SearchSection(const section_64* Section, size_t Offset, __HintType&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto base = ImageSectionView<const uint8_t*>(Section);
for (decltype(section_64::size) i = Offset; i < Section->size; ++i) {
if (Hint(base, i, Section->size) == true) {
return ARL::AddressOffsetWithCast<__ReturnType>(base, i);
}
}
return nullptr;
}
template<typename __ReturnType = void*, typename __HintType>
[[nodiscard]]
__ReturnType SearchSection(size_t Index, __HintType&& Hint) const {
return SearchSection<__ReturnType>(ImageSection(Index), std::forward<__HintType>(Hint));
}
template<typename __ReturnType = void*, typename __HintType>
[[nodiscard]]
__ReturnType SearchSection(size_t Index, size_t Offset, __HintType&& Hint) const {
return SearchSection<__ReturnType>(ImageSection(Index), Offset, std::forward<__HintType>(Hint));
}
template<typename __ReturnType = void*, typename __HintType>
[[nodiscard]]
__ReturnType SearchSection(const char* SegmentName, const char* SectionName, __HintType&& Hint) const {
return SearchSection<__ReturnType>(ImageSection(SegmentName, SectionName), std::forward<__HintType>(Hint));
}
template<typename __ReturnType = void*, typename __HintType>
[[nodiscard]]
__ReturnType SearchSection(const char* SegmentName, const char* SectionName, size_t Offset, __HintType&& Hint) const {
return SearchSection<__ReturnType>(ImageSection(SegmentName, SectionName), Offset, std::forward<__HintType>(Hint));
}
[[nodiscard]]
X64ImageAddress ConvertOffsetToRva(X64ImageOffset Offset) const;
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ConvertOffsetToPtr(X64ImageOffset Offset) const {
return ImageOffset<__ReturnType>(Offset);
}
[[nodiscard]]
X64ImageOffset ConvertRvaToOffset(X64ImageAddress Address) const;
template<typename __ReturnType = void*>
[[nodiscard]]
__ReturnType ConvertRvaToPtr(X64ImageAddress Rva) const {
return ConvertOffsetToPtr<__ReturnType>(ConvertRvaToOffset(Rva));
}
template<typename __PtrType>
[[nodiscard]]
X64ImageAddress ConvertPtrToRva(__PtrType Ptr) const {
auto offset = ARL::AddressDelta(Ptr, m_MachOHeader);
if (offset < m_MachOSize) {
return ConvertOffsetToRva(offset);
} else {
throw ARL::OverflowError(__FILE__, __LINE__, "X64ImageInterpreter: out of range.");
}
}
template<typename __PtrType>
[[nodiscard]]
X64ImageAddress ConvertPtrToOffset(__PtrType Ptr) const {
auto offset = ARL::AddressDelta(Ptr, m_MachOHeader);
if (offset < m_MachOSize) {
return offset;
} else {
throw ARL::OverflowError(__FILE__, __LINE__, "X64ImageInterpreter: out of range.");
}
}
};
}

View File

@ -1,200 +0,0 @@
#define _CRT_SECURE_NO_WARNINGS
#include "amd64_emulator.hpp"
#include "exceptions/key_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\amd64_emulator.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
void amd64_emulator::_unicorn_hookcode_cb_stub(uc_engine* uc, uint64_t address, uint32_t size, void* user_data) {
auto hook_stub_ctx = reinterpret_cast<hook_stub_context_t*>(user_data);
hook_stub_ctx->self->m_unicorn_hook_cbs_hookcode[hook_stub_ctx->unicorn_hook_handle](address, size);
}
void amd64_emulator::_unicorn_hookmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data) {
auto hook_stub_ctx = reinterpret_cast<hook_stub_context_t*>(user_data);
hook_stub_ctx->self->m_unicorn_hook_cbs_hookmem[hook_stub_ctx->unicorn_hook_handle](type, address, static_cast<unsigned int>(size), value);
}
bool amd64_emulator::_unicorn_eventmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data) {
auto hook_stub_ctx = reinterpret_cast<hook_stub_context_t*>(user_data);
return hook_stub_ctx->self->m_unicorn_hook_cbs_eventmem[hook_stub_ctx->unicorn_hook_handle](type, address, static_cast<unsigned int>(size), value);
}
amd64_emulator::amd64_emulator() {
auto err = uc_open(UC_ARCH_X86, UC_MODE_64, m_unicorn_engine.unsafe_addressof());
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_open failed.");
}
}
void amd64_emulator::reg_read(int regid, void* value) {
auto err = uc_reg_read(m_unicorn_engine.get(), regid, value);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_reg_read failed.");
}
}
void amd64_emulator::reg_write(int regid, const void* value) {
auto err = uc_reg_write(m_unicorn_engine.get(), regid, value);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_reg_write failed.");
}
}
uint64_t amd64_emulator::msr_read(uint32_t rid) {
uc_x86_msr msr;
msr.rid = rid;
auto err = uc_reg_read(m_unicorn_engine.get(), UC_X86_REG_MSR, &msr);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_reg_write failed.");
}
return msr.value;
}
void amd64_emulator::msr_write(uint32_t rid, uint64_t value) {
uc_x86_msr msr;
msr.rid = rid;
msr.value = value;
auto err = uc_reg_write(m_unicorn_engine.get(), UC_X86_REG_MSR, &msr);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_reg_write failed.");
}
}
void amd64_emulator::mem_map(uint64_t address, size_t size, uint32_t perms) {
auto err = uc_mem_map(m_unicorn_engine.get(), address, size, perms);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_map failed.");
}
}
void amd64_emulator::mem_unmap(uint64_t address, size_t size) {
auto err = uc_mem_unmap(m_unicorn_engine.get(), address, size);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_unmap failed.");
}
}
void amd64_emulator::mem_read(uint64_t address, void* buf, size_t size) {
auto err = uc_mem_read(m_unicorn_engine.get(), address, buf, size);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_read failed.");
}
}
std::vector<uint8_t> amd64_emulator::mem_read(uint64_t address, size_t size) {
std::vector<uint8_t> ret_buf(size);
auto err = uc_mem_read(m_unicorn_engine.get(), address, ret_buf.data(), ret_buf.size());
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_read failed.");
}
return ret_buf;
}
void amd64_emulator::mem_write(uint64_t address, const void* buf, size_t size) {
auto err = uc_mem_write(m_unicorn_engine.get(), address, buf, size);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_write failed.");
}
}
void amd64_emulator::mem_write(uint64_t address, const std::vector<uint8_t>& buf) {
mem_write(address, buf.data(), buf.size());
}
void amd64_emulator::hook_del(uc_hook hook_handle) {
auto iter_of_hook_stub_ctxs = m_unicorn_hook_stub_ctxs.find(hook_handle);
if (iter_of_hook_stub_ctxs == m_unicorn_hook_stub_ctxs.end()) {
throw exceptions::key_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Target hook is not found.");
}
auto iter_of_hook_cbs_hookcode = m_unicorn_hook_cbs_hookcode.find(hook_handle);
if (iter_of_hook_cbs_hookcode != m_unicorn_hook_cbs_hookcode.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_cbs_hookcode.erase(iter_of_hook_cbs_hookcode);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
auto iter_of_hook_cbs_hookmem = m_unicorn_hook_cbs_hookmem.find(hook_handle);
if (iter_of_hook_cbs_hookmem != m_unicorn_hook_cbs_hookmem.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_cbs_hookmem.erase(iter_of_hook_cbs_hookmem);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
auto iter_of_hook_cbs_eventmem = m_unicorn_hook_cbs_eventmem.find(hook_handle);
if (iter_of_hook_cbs_eventmem != m_unicorn_hook_cbs_eventmem.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_cbs_eventmem.erase(iter_of_hook_cbs_eventmem);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
__assume(false);
}
void amd64_emulator::emu_start(uint64_t begin_address, uint64_t end_address, uint64_t timeout, size_t count) {
auto err = uc_emu_start(m_unicorn_engine.get(), begin_address, end_address, timeout, count);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"emu_start failed.");
}
}
void amd64_emulator::emu_stop() {
auto err = uc_emu_stop(m_unicorn_engine.get());
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_emu_stop failed.");
}
}
//void amd64_emulator::create_gdt_entry(uint64_t gdt_entry_address, uint32_t base, uint32_t limit, uint8_t access_byte, uint8_t flags) {
// struct {
// uint16_t limit0;
// uint16_t base0;
// uint8_t base1;
// uint8_t access_byte;
// uint8_t limit1 : 4;
// uint8_t flags : 4;
// uint8_t base2;
// } segment_descriptor;
// static_assert(sizeof(segment_descriptor) == 8);
// segment_descriptor.limit0 = limit & 0xffff;
// segment_descriptor.base0 = base & 0xffff;
// segment_descriptor.base1 = (base >> 16) & 0xff;
// segment_descriptor.access_byte = access_byte;
// segment_descriptor.limit1 = (limit >> 16) & 0xf;
// segment_descriptor.flags = flags & 0xf;
// segment_descriptor.base2 = (base >> 24) & 0xff;
// auto err = uc_mem_write(m_unicorn_engine.get(), gdt_entry_address, &segment_descriptor, sizeof(segment_descriptor));
// if (err != UC_ERR_OK) {
// throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_write failed.");
// }
//}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,159 +0,0 @@
#pragma once
#include <winsock2.h>
#include <windows.h>
#include <unicorn/unicorn.h>
#include <any>
#include <memory>
#include <string>
#include <unordered_map>
#include <functional>
#include "resource_wrapper.hpp"
#include "resource_traits/unicorn/unicorn_handle.hpp"
#include "exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\amd64_emulator.hpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
class amd64_emulator {
public:
class backend_error : public ::nkg::exception {
public:
using error_code_t = uc_err;
private:
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, error_code_t unicorn_err, std::string_view message) noexcept :
::nkg::exception(file, line, message), m_error_code(unicorn_err), m_error_string(uc_strerror(unicorn_err)) {}
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return true;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
return m_error_code;
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
return m_error_string;
}
};
using hookcode_cb_t = void(uint64_t address, size_t size);
using hookmem_cb_t = void(uc_mem_type type, uint64_t address, size_t size, int64_t value);
using eventmem_cb_t = bool(uc_mem_type type, uint64_t address, size_t size, int64_t value);
private:
struct hook_stub_context_t {
amd64_emulator* self;
uc_hook unicorn_hook_handle;
};
resource_wrapper<resource_traits::unicorn::unicorn_handle> m_unicorn_engine;
std::unordered_map<std::string, std::any> m_unicorn_user_ctx;
std::unordered_map<uc_hook, std::unique_ptr<hook_stub_context_t>> m_unicorn_hook_stub_ctxs;
std::unordered_map<uc_hook, std::function<hookcode_cb_t>> m_unicorn_hook_cbs_hookcode;
std::unordered_map<uc_hook, std::function<hookmem_cb_t>> m_unicorn_hook_cbs_hookmem;
std::unordered_map<uc_hook, std::function<eventmem_cb_t>> m_unicorn_hook_cbs_eventmem;
static void _unicorn_hookcode_cb_stub(uc_engine* uc, uint64_t address, uint32_t size, void* user_data);
static void _unicorn_hookmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data);
static bool _unicorn_eventmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data);
public:
amd64_emulator();
void reg_read(int regid, void* buf);
void reg_write(int regid, const void* buf);
uint64_t msr_read(uint32_t rid);
void msr_write(uint32_t rid, uint64_t value);
void mem_map(uint64_t address, size_t size, uint32_t perms);
void mem_unmap(uint64_t address, size_t size);
void mem_read(uint64_t address, void* buf, size_t size);
std::vector<uint8_t> mem_read(uint64_t address, size_t size);
void mem_write(uint64_t address, const void* buf, size_t size);
void mem_write(uint64_t address, const std::vector<uint8_t>& buf);
template<int hook_type, typename callable_t>
uc_hook hook_add(callable_t&& hook_callback, uint64_t begin_address = 1, uint64_t end_address = 0) {
uc_err err;
auto hook_stub_ctx = std::make_unique<hook_stub_context_t>();
hook_stub_ctx->self = this;
hook_stub_ctx->unicorn_hook_handle = 0;
if constexpr (hook_type == UC_HOOK_CODE) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_hookcode_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_cbs_hookcode.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::forward<callable_t>(hook_callback)));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_VALID) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_hookmem_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_cbs_hookmem.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::forward<callable_t>(hook_callback)));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_eventmem_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_cbs_eventmem.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::forward<callable_t>(hook_callback)));
} else {
static_assert(
hook_type == UC_HOOK_CODE ||
(hook_type & ~UC_HOOK_MEM_VALID) == 0 ||
(hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0, "Unsupported hook type.");
}
return m_unicorn_hook_stub_ctxs.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::move(hook_stub_ctx))).first->first;
}
void hook_del(uc_hook hook_handle);
void emu_start(uint64_t begin_address, uint64_t end_address = 0, uint64_t timeout = 0, size_t count = 0);
void emu_stop();
// void create_gdt_entry(uint64_t gdt_entry_address, uint32_t base, uint32_t limit, uint8_t access_byte, uint8_t flags);
template<typename val_t>
void context_set(const std::string& name, val_t&& value) {
m_unicorn_user_ctx[name] = std::forward<val_t>(value);
}
template<typename val_t>
val_t context_get(const std::string& name) {
return std::any_cast<val_t>(m_unicorn_user_ctx[name]);
}
};
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,160 +0,0 @@
#define _CRT_SECURE_NO_WARNINGS
#include "i386_emulator.hpp"
#include "exceptions/key_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\i386_emulator.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
void i386_emulator::_unicorn_hookcode_cb_stub(uc_engine* uc, uint64_t address, uint32_t size, void* user_data) {
auto hook_stub_ctx =
reinterpret_cast<hook_stub_context_t*>(user_data);
auto& hook_callback =
std::any_cast<std::function<hookcode_cb_t>&>(hook_stub_ctx->self->m_unicorn_hook_callbacks[hook_stub_ctx->unicorn_hook_handle]);
hook_callback(static_cast<uint32_t>(address), size);
}
void i386_emulator::_unicorn_hookmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data) {
auto hook_stub_ctx =
reinterpret_cast<hook_stub_context_t*>(user_data);
auto& hook_callback =
std::any_cast<std::function<hookmem_cb_t>&>(hook_stub_ctx->self->m_unicorn_hook_callbacks[hook_stub_ctx->unicorn_hook_handle]);
hook_callback(type, static_cast<uint32_t>(address), static_cast<unsigned int>(size), static_cast<int32_t>(value));
}
bool i386_emulator::_unicorn_eventmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data) {
auto hook_stub_ctx =
reinterpret_cast<hook_stub_context_t*>(user_data);
auto& hook_callback =
std::any_cast<std::function<eventmem_cb_t>&>(hook_stub_ctx->self->m_unicorn_hook_callbacks[hook_stub_ctx->unicorn_hook_handle]);
return hook_callback(type, static_cast<uint32_t>(address), static_cast<unsigned int>(size), static_cast<int32_t>(value));
}
i386_emulator::i386_emulator() {
auto err = uc_open(UC_ARCH_X86, UC_MODE_32, m_unicorn_engine.unsafe_addressof());
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_open failed.");
}
}
void i386_emulator::reg_read(int regid, void* value) {
auto err = uc_reg_read(m_unicorn_engine.get(), regid, value);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_reg_read failed.");
}
}
void i386_emulator::reg_write(int regid, const void* value) {
auto err = uc_reg_write(m_unicorn_engine.get(), regid, value);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_reg_write failed.");
}
}
void i386_emulator::mem_map(uint32_t address, size_t size, uint32_t perms) {
auto err = uc_mem_map(m_unicorn_engine.get(), address, size, perms);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_map failed.");
}
}
void i386_emulator::mem_unmap(uint32_t address, size_t size) {
auto err = uc_mem_unmap(m_unicorn_engine.get(), address, size);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_unmap failed.");
}
}
void i386_emulator::mem_read(uint32_t address, void* buf, size_t size) {
auto err = uc_mem_read(m_unicorn_engine.get(), address, buf, size);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_read failed.");
}
}
std::vector<uint8_t> i386_emulator::mem_read(uint32_t address, size_t size) {
std::vector<uint8_t> ret_buf(size);
auto err = uc_mem_read(m_unicorn_engine.get(), address, ret_buf.data(), ret_buf.size());
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_read failed.");
}
return ret_buf;
}
void i386_emulator::mem_write(uint32_t address, const void* buf, size_t size) {
auto err = uc_mem_write(m_unicorn_engine.get(), address, buf, size);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_write failed.");
}
}
void i386_emulator::mem_write(uint32_t address, const std::vector<uint8_t>& buf) {
mem_write(address, buf.data(), buf.size());
}
void i386_emulator::hook_del(uc_hook hook_handle) {
auto iter_of_hook_stub_ctxs = m_unicorn_hook_stub_ctxs.find(hook_handle);
if (iter_of_hook_stub_ctxs == m_unicorn_hook_stub_ctxs.end()) {
throw exceptions::key_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Target hook is not found.");
}
auto iter_of_hook_callbacks = m_unicorn_hook_callbacks.find(hook_handle);
if (iter_of_hook_callbacks != m_unicorn_hook_callbacks.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_callbacks.erase(iter_of_hook_callbacks);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
__assume(false);
}
void i386_emulator::create_gdt_entry(uint32_t gdt_entry_address, uint32_t base, uint32_t limit, uint8_t access_byte, uint8_t flags) {
struct {
uint64_t limit0 : 16;
uint64_t base0 : 24;
uint64_t access_byte : 8;
uint64_t limit1 : 4;
uint64_t flags : 4;
uint64_t base1 : 8;
} gdt_entry;
gdt_entry.limit0 = limit & 0xffff;
gdt_entry.base0 = base & 0xffffff;
gdt_entry.access_byte = access_byte;
gdt_entry.flags = flags & 0xf;
gdt_entry.base1 = (base & 0xff000000) >> 24;
mem_write(gdt_entry_address, &gdt_entry, sizeof(gdt_entry));
}
void i386_emulator::emu_start(uint32_t begin_address, uint32_t end_address, uint64_t timeout, size_t count) {
auto err = uc_emu_start(m_unicorn_engine.get(), begin_address, end_address, timeout, count);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"emu_start failed.");
}
}
void i386_emulator::emu_stop() {
auto err = uc_emu_stop(m_unicorn_engine.get());
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_emu_stop failed.");
}
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,152 +0,0 @@
#pragma once
#include <winsock2.h>
#include <windows.h>
#include <unicorn/unicorn.h>
#include <any>
#include <memory>
#include <string>
#include <unordered_map>
#include <functional>
#include "resource_wrapper.hpp"
#include "resource_traits/unicorn/unicorn_handle.hpp"
#include "exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\i386_emulator.hpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
class i386_emulator {
public:
class backend_error : public ::nkg::exception {
public:
using error_code_t = uc_err;
private:
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, error_code_t unicorn_err, std::string_view message) noexcept :
::nkg::exception(file, line, message), m_error_code(unicorn_err), m_error_string(uc_strerror(unicorn_err)) {}
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return true;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
return m_error_code;
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
return m_error_string;
}
};
using hookcode_cb_t = void(uint32_t address, size_t size);
using hookmem_cb_t = void(uc_mem_type type, uint32_t address, size_t size, int32_t value);
using eventmem_cb_t = bool(uc_mem_type type, uint32_t address, size_t size, int32_t value);
private:
struct hook_stub_context_t {
i386_emulator* self;
uc_hook unicorn_hook_handle;
};
resource_wrapper<resource_traits::unicorn::unicorn_handle> m_unicorn_engine;
std::unordered_map<std::string, std::any> m_unicorn_user_ctx;
std::unordered_map<uc_hook, std::unique_ptr<hook_stub_context_t>> m_unicorn_hook_stub_ctxs;
std::unordered_map<uc_hook, std::any> m_unicorn_hook_callbacks;
static void _unicorn_hookcode_cb_stub(uc_engine* uc, uint64_t address, uint32_t size, void* user_data);
static void _unicorn_hookmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data);
static bool _unicorn_eventmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data);
public:
i386_emulator();
void reg_read(int regid, void* value);
void reg_write(int regid, const void* value);
void mem_map(uint32_t address, size_t size, uint32_t perms);
void mem_unmap(uint32_t address, size_t size);
void mem_read(uint32_t address, void* buf, size_t size);
std::vector<uint8_t> mem_read(uint32_t address, size_t size);
void mem_write(uint32_t address, const void* buf, size_t size);
void mem_write(uint32_t address, const std::vector<uint8_t>& buf);
template<int hook_type, typename callable_t>
uc_hook hook_add(callable_t&& hook_callback, uint32_t begin_address = 1, uint32_t end_address = 0) {
uc_err err;
auto hook_stub_ctx = std::make_unique<hook_stub_context_t>();
hook_stub_ctx->self = this;
hook_stub_ctx->unicorn_hook_handle = 0;
if constexpr (hook_type == UC_HOOK_CODE) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_hookcode_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_callbacks.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::function<hookcode_cb_t>{ std::forward<callable_t>(hook_callback) }));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_VALID) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_hookmem_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_callbacks.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::function<hookmem_cb_t>{ std::forward<callable_t>(hook_callback) }));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_eventmem_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_callbacks.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::function<eventmem_cb_t>{ std::forward<callable_t>(hook_callback) }));
} else {
static_assert(
hook_type == UC_HOOK_CODE ||
(hook_type & ~UC_HOOK_MEM_VALID) == 0 ||
(hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0, "Unsupported hook type.");
}
return m_unicorn_hook_stub_ctxs.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::move(hook_stub_ctx))).first->first;
}
void hook_del(uc_hook hook_handle);
void create_gdt_entry(uint32_t gdt_entry_address, uint32_t base, uint32_t limit, uint8_t access_byte, uint8_t flags);
void emu_start(uint32_t begin_address, uint32_t end_address = 0, uint64_t timeout = 0, size_t count = 0);
void emu_stop();
template<typename val_t>
void context_set(const std::string& name, val_t&& value) {
m_unicorn_user_ctx[name] = std::forward<val_t>(value);
}
template<typename val_t>
val_t context_get(const std::string& name) {
return std::any_cast<val_t>(m_unicorn_user_ctx[name]);
}
};
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,302 +0,0 @@
#include "image_interpreter.hpp"
#include <fmt/format.h>
#include "exceptions/index_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\image_interpreter.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
image_interpreter::image_interpreter() :
m_dos_header(nullptr),
m_nt_headers(nullptr),
m_section_header_table(nullptr),
m_vs_fixed_file_info(nullptr) {}
[[nodiscard]]
image_interpreter image_interpreter::parse(void* image_base, bool parse_relocation) {
image_interpreter new_image;
new_image.m_dos_header = reinterpret_cast<PIMAGE_DOS_HEADER>(image_base);
if (new_image.m_dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid image: DOS signature check failure")
.push_hint(u8"Are you sure you DO provide a valid WinPE file?");
}
new_image.m_nt_headers = reinterpret_cast<PIMAGE_NT_HEADERS>(reinterpret_cast<uint8_t*>(image_base) + new_image.m_dos_header->e_lfanew);
if (new_image.m_nt_headers->Signature != IMAGE_NT_SIGNATURE) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid image: NT signature check failure")
.push_hint(u8"Are you sure you DO provide a valid WinPE file?");
}
#if defined(_M_AMD64)
if (new_image.m_nt_headers->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid image: optional header magic check failure")
.push_hint(u8"Are you sure you DO provide a valid 64-bits WinPE file?");
}
if (new_image.m_nt_headers->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid image: machine check failure")
.push_hint(u8"Are you sure you DO provide a valid 64-bits WinPE file?");
}
#elif defined(_M_IX86)
if (new_image.m_nt_headers->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid Image. (Optional header magic check failure)")
.push_hint(u8"Are you sure you DO provide a valid 32-bits WinPE file?");
}
if (new_image.m_nt_headers->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Invalid Image. (Machine check failure)")
.push_hint(u8"Are you sure you DO provide a valid 32-bits WinPE file?");
}
#else
#error "image_interpreter.cpp: unsupported architecture."
#endif
new_image.m_section_header_table =
reinterpret_cast<PIMAGE_SECTION_HEADER>(reinterpret_cast<char*>(&new_image.m_nt_headers->OptionalHeader) + new_image.m_nt_headers->FileHeader.SizeOfOptionalHeader);
for (WORD i = 0; i < new_image.m_nt_headers->FileHeader.NumberOfSections; ++i) {
auto section_name = make_section_name(new_image.m_section_header_table[i].Name);
if (new_image.m_section_header_name_lookup_table.find(section_name) == new_image.m_section_header_name_lookup_table.end()) {
new_image.m_section_header_name_lookup_table[section_name] = &new_image.m_section_header_table[i];
}
new_image.m_section_header_rva_lookup_table[new_image.m_section_header_table[i].VirtualAddress] = &new_image.m_section_header_table[i];
new_image.m_section_header_fo_lookup_table[new_image.m_section_header_table[i].PointerToRawData] = &new_image.m_section_header_table[i];
}
if (parse_relocation && new_image.m_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress != 0) {
auto relocation_table =
new_image.convert_rva_to_ptr<PIMAGE_BASE_RELOCATION>(new_image.m_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress);
while (relocation_table->VirtualAddress != 0) {
rva_t rva = relocation_table->VirtualAddress;
auto reloc_items = reinterpret_cast<WORD*>(relocation_table + 1);
auto reloc_items_count = (relocation_table->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
for (DWORD i = 0; i < reloc_items_count; ++i) {
auto reloc_type = reloc_items[i] >> 12;
switch (reloc_type) {
case IMAGE_REL_BASED_ABSOLUTE:
break;
case IMAGE_REL_BASED_HIGH:
case IMAGE_REL_BASED_LOW:
case IMAGE_REL_BASED_HIGHADJ:
new_image.m_relocation_rva_lookup_table[rva + (reloc_items[i] & 0x0fff)] = 2;
break;
case IMAGE_REL_BASED_HIGHLOW:
new_image.m_relocation_rva_lookup_table[rva + (reloc_items[i] & 0x0fff)] = 4;
break;
#if defined(IMAGE_REL_BASED_DIR64)
case IMAGE_REL_BASED_DIR64:
new_image.m_relocation_rva_lookup_table[rva + (reloc_items[i] & 0x0fff)] = 8;
break;
#endif
default:
break;
}
}
relocation_table = reinterpret_cast<PIMAGE_BASE_RELOCATION>(&reloc_items[reloc_items_count]);
}
}
if (new_image.m_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress) {
rva_t import_rva = new_image.m_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
auto import_descriptors = new_image.convert_rva_to_ptr<PIMAGE_IMPORT_DESCRIPTOR>(import_rva);
for (size_t i = 0; import_descriptors[i].OriginalFirstThunk != 0; ++i) {
auto import_lookup_table = new_image.convert_rva_to_ptr<PIMAGE_THUNK_DATA>(import_descriptors[i].OriginalFirstThunk);
rva_t import_address_table_rva = import_descriptors[i].FirstThunk;
for (size_t j = 0; import_lookup_table[j].u1.Ordinal != 0; ++j) {
new_image.m_iat_rva_lookup_table[import_address_table_rva + j * sizeof(IMAGE_THUNK_DATA)] = std::make_pair(&import_descriptors[i], &import_lookup_table[j]);
}
}
}
if (new_image.m_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress) {
rva_t resource_rva = new_image.m_nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
auto res_type_directory = new_image.convert_rva_to_ptr<PIMAGE_RESOURCE_DIRECTORY>(resource_rva);
auto res_type_name_entries = reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(res_type_directory + 1);
auto res_type_id_entries = res_type_name_entries + res_type_directory->NumberOfNamedEntries;
for (WORD i = 0; i < res_type_directory->NumberOfIdEntries && new_image.m_vs_fixed_file_info == nullptr; ++i) {
if (res_type_id_entries[i].Id == reinterpret_cast<uintptr_t>(RT_VERSION) && res_type_id_entries[i].DataIsDirectory) {
auto res_name_directory = new_image.convert_rva_to_ptr<PIMAGE_RESOURCE_DIRECTORY>(resource_rva + res_type_id_entries[i].OffsetToDirectory);
auto res_name_name_entries = reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(res_name_directory + 1);
auto res_name_id_entries = res_name_name_entries + res_name_directory->NumberOfNamedEntries;
for (WORD j = 0; j < res_name_directory->NumberOfIdEntries && new_image.m_vs_fixed_file_info == nullptr; ++j) {
if (res_name_id_entries[j].Id == VS_VERSION_INFO && res_name_id_entries[j].DataIsDirectory) {
auto res_lang_directory = new_image.convert_rva_to_ptr<PIMAGE_RESOURCE_DIRECTORY>(resource_rva + res_name_id_entries[j].OffsetToDirectory);
auto res_lang_name_entries = reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(res_lang_directory + 1);
auto res_lang_id_entries = res_lang_name_entries + res_lang_directory->NumberOfNamedEntries;
for (WORD k = 0; k < res_lang_directory->NumberOfIdEntries && new_image.m_vs_fixed_file_info == nullptr; ++k) {
constexpr WORD neutral_lang_id = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
constexpr WORD english_lang_id = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
if ((res_lang_id_entries[k].Id == neutral_lang_id || res_lang_id_entries[k].Id == english_lang_id) && !res_lang_id_entries[k].DataIsDirectory) {
auto res_data_entry = new_image.convert_rva_to_ptr<PIMAGE_RESOURCE_DATA_ENTRY>(resource_rva + res_lang_id_entries[k].OffsetToData);
auto vs_version_info = new_image.convert_rva_to_ptr<PBYTE>(res_data_entry->OffsetToData);
auto vs_version_info_key = reinterpret_cast<PWSTR>(vs_version_info + 6); // vs_version_info->szKey
if (_wcsicmp(vs_version_info_key, L"VS_VERSION_INFO") == 0) {
auto p = reinterpret_cast<PBYTE>(vs_version_info_key + _countof(L"VS_VERSION_INFO"));
while (new_image.convert_ptr_to_rva(p) % sizeof(DWORD)) {
++p;
}
auto vs_fixed_file_info = reinterpret_cast<VS_FIXEDFILEINFO*>(p);
if (vs_fixed_file_info->dwSignature == VS_FFI_SIGNATURE) {
new_image.m_vs_fixed_file_info = vs_fixed_file_info;
}
}
}
}
}
}
}
}
}
return new_image;
}
[[nodiscard]]
PIMAGE_DOS_HEADER image_interpreter::image_dos_header() const noexcept {
return m_dos_header;
}
[[nodiscard]]
PIMAGE_NT_HEADERS image_interpreter::image_nt_headers() const noexcept {
return m_nt_headers;
}
[[nodiscard]]
PIMAGE_SECTION_HEADER image_interpreter::image_section_header_table() const noexcept {
return m_section_header_table;
}
[[nodiscard]]
PIMAGE_SECTION_HEADER image_interpreter::image_section_header(size_t n) const {
if (n < m_nt_headers->FileHeader.NumberOfSections) {
return m_section_header_table + n;
} else {
throw exceptions::index_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Section index is out of range.");
}
}
[[nodiscard]]
PIMAGE_SECTION_HEADER image_interpreter::image_section_header(std::string_view section_name) const {
if (section_name.length() <= 8) {
std::array<BYTE, 8> name{};
std::copy(section_name.begin(), section_name.end(), name.begin());
auto it = m_section_header_name_lookup_table.find(name);
if (it != m_section_header_name_lookup_table.end()) {
return it->second;
} else {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format(u8"Target section header is not found: section_name = {}", section_name));
}
} else {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Target section header is not found: section_name is too long.");
}
}
[[nodiscard]]
PIMAGE_SECTION_HEADER image_interpreter::image_section_header_from_rva(rva_t rva) const {
auto it = m_section_header_rva_lookup_table.upper_bound(rva);
if (it != m_section_header_rva_lookup_table.begin()) {
--it;
}
rva_t section_rva_begin = it->second->VirtualAddress;
rva_t section_rva_end = section_rva_begin + it->second->Misc.VirtualSize;
if (section_rva_begin <= rva && rva < section_rva_end) {
return it->second;
} else {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Target section header is not found.")
.push_hint(fmt::format("rva = 0x{:x}", rva));
}
}
[[nodiscard]]
PIMAGE_SECTION_HEADER image_interpreter::image_section_header_from_va(va_t va) const {
return image_section_header_from_rva(static_cast<rva_t>(va - m_nt_headers->OptionalHeader.ImageBase));
}
[[nodiscard]]
PIMAGE_SECTION_HEADER image_interpreter::image_section_header_from_fo(fo_t file_offset) const {
auto it = m_section_header_fo_lookup_table.upper_bound(file_offset);
if (it != m_section_header_fo_lookup_table.begin()) {
--it;
}
uintptr_t section_fo_begin = it->second->PointerToRawData;
uintptr_t section_fo_end = section_fo_begin + it->second->SizeOfRawData;
if (section_fo_begin <= file_offset && file_offset < section_fo_end) {
return it->second;
} else {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Target section header is not found.")
.push_hint(fmt::format(u8"file_offset = 0x{:x}", file_offset));
}
}
[[nodiscard]]
image_interpreter::va_t image_interpreter::convert_rva_to_va(rva_t rva) const noexcept {
return rva + m_nt_headers->OptionalHeader.ImageBase;
}
[[nodiscard]]
image_interpreter::fo_t image_interpreter::convert_rva_to_fo(rva_t rva) const {
auto section_header = image_section_header_from_rva(rva);
return section_header->PointerToRawData + (rva - static_cast<uintptr_t>(section_header->VirtualAddress));
}
[[nodiscard]]
image_interpreter::rva_t image_interpreter::convert_fo_to_rva(fo_t file_offset) const {
auto section_header = image_section_header_from_fo(file_offset);
return section_header->VirtualAddress + (file_offset - section_header->PointerToRawData);
}
[[nodiscard]]
image_interpreter::va_t image_interpreter::convert_fo_to_va(fo_t file_offset) const {
return convert_fo_to_rva(file_offset) + m_nt_headers->OptionalHeader.ImageBase;
}
[[nodiscard]]
image_interpreter::rva_t image_interpreter::convert_va_to_rva(va_t va) const noexcept {
return va - m_nt_headers->OptionalHeader.ImageBase;
}
[[nodiscard]]
image_interpreter::fo_t image_interpreter::convert_va_to_fo(va_t va) const {
return image_section_header_from_va(va)->PointerToRawData;
}
[[nodiscard]]
size_t image_interpreter::number_of_sections() const noexcept {
return m_nt_headers->FileHeader.NumberOfSections;
}
PIMAGE_IMPORT_DESCRIPTOR image_interpreter::import_descriptor_from_rva(rva_t rva) {
auto it = m_iat_rva_lookup_table.find(rva);
return it != m_iat_rva_lookup_table.end() ? it->second.first : nullptr;
}
PIMAGE_THUNK_DATA image_interpreter::import_lookup_entry_from_rva(rva_t rva) {
auto it = m_iat_rva_lookup_table.find(rva);
return it != m_iat_rva_lookup_table.end() ? it->second.second : nullptr;
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,202 +0,0 @@
#pragma once
#include <type_traits>
#include <array>
#include <map>
#include <windows.h>
#include "exception.hpp"
namespace nkg {
class image_interpreter {
public:
using va_t = uintptr_t;
using rva_t = uintptr_t;
using fo_t = uintptr_t;
private:
PIMAGE_DOS_HEADER m_dos_header;
PIMAGE_NT_HEADERS m_nt_headers;
PIMAGE_SECTION_HEADER m_section_header_table;
std::map<std::array<BYTE, 8>, PIMAGE_SECTION_HEADER> m_section_header_name_lookup_table;
std::map<rva_t, PIMAGE_SECTION_HEADER> m_section_header_rva_lookup_table;
std::map<fo_t, PIMAGE_SECTION_HEADER> m_section_header_fo_lookup_table;
std::map<rva_t, size_t> m_relocation_rva_lookup_table;
std::map<rva_t, std::pair<PIMAGE_IMPORT_DESCRIPTOR, PIMAGE_THUNK_DATA>> m_iat_rva_lookup_table;
VS_FIXEDFILEINFO* m_vs_fixed_file_info;
image_interpreter();
static std::array<BYTE, 8> make_section_name(const BYTE (&name)[8]) {
std::array<BYTE, 8> retval;
std::copy(std::begin(name), std::end(name), retval.begin());
return retval;
}
public:
class parse_error : public ::nkg::exception {
public:
parse_error(std::string_view file, int line, std::string_view message) noexcept :
::nkg::exception(file, line, message) {}
};
[[nodiscard]]
static image_interpreter parse(void* image_base, bool parse_relocation);
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t image_base() const noexcept {
static_assert(std::is_pointer_v<ptr_t>);
return reinterpret_cast<ptr_t>(m_dos_header);
}
[[nodiscard]]
PIMAGE_DOS_HEADER image_dos_header() const noexcept;
[[nodiscard]]
PIMAGE_NT_HEADERS image_nt_headers() const noexcept;
[[nodiscard]]
PIMAGE_SECTION_HEADER image_section_header_table() const noexcept;
[[nodiscard]]
PIMAGE_SECTION_HEADER image_section_header(size_t n) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER image_section_header(std::string_view name) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER image_section_header_from_rva(rva_t rva) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER image_section_header_from_va(va_t va) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER image_section_header_from_fo(fo_t file_offset) const;
[[nodiscard]]
va_t convert_rva_to_va(rva_t rva) const noexcept;
[[nodiscard]]
fo_t convert_rva_to_fo(rva_t rva) const;
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t convert_rva_to_ptr(rva_t rva) const {
static_assert(std::is_pointer_v<ptr_t>);
return convert_fo_to_ptr<ptr_t>(convert_rva_to_fo(rva));
}
[[nodiscard]]
rva_t convert_fo_to_rva(fo_t file_offset) const;
[[nodiscard]]
va_t convert_fo_to_va(fo_t file_offset) const;
template<typename ptr_t>
[[nodiscard]]
ptr_t convert_fo_to_ptr(fo_t file_offset) const noexcept {
static_assert(std::is_pointer_v<ptr_t>);
return reinterpret_cast<ptr_t>(image_base<char*>() + file_offset);
}
[[nodiscard]]
rva_t convert_va_to_rva(va_t va) const noexcept;
[[nodiscard]]
fo_t convert_va_to_fo(va_t va) const;
template<typename ptr_t>
[[nodiscard]]
ptr_t convert_va_to_ptr(va_t va) const noexcept {
return convert_rva_to_ptr<ptr_t>(convert_va_to_rva(va));
}
template<typename ptr_t>
[[nodiscard]]
fo_t convert_ptr_to_fo(ptr_t ptr) const noexcept {
static_assert(std::is_pointer_v<ptr_t>);
return reinterpret_cast<const volatile char*>(ptr) - image_base<const volatile char*>();
}
template<typename ptr_t>
[[nodiscard]]
rva_t convert_ptr_to_rva(ptr_t ptr) const {
return convert_fo_to_rva(convert_ptr_to_fo(ptr));
}
template<typename ptr_t>
[[nodiscard]]
va_t convert_ptr_to_va(ptr_t ptr) const {
return convert_fo_to_va(convert_ptr_to_fo(ptr));
}
[[nodiscard]]
size_t number_of_sections() const noexcept;
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t image_section_view(size_t n, size_t offset = 0) const {
static_assert(std::is_pointer_v<ptr_t>);
return reinterpret_cast<ptr_t>(image_base<char*>() + image_section_header(n)->PointerToRawData + offset);
}
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t image_section_view(std::string_view section_name, size_t offset = 0) const {
static_assert(std::is_pointer_v<ptr_t>);
return reinterpret_cast<ptr_t>(image_base<char*>() + image_section_header(section_name)->PointerToRawData + offset);
}
template<typename ptr_t, typename pred_func_t>
[[nodiscard]]
ptr_t search_section(size_t n, pred_func_t&& pred_func) const {
static_assert(std::is_pointer_v<ptr_t>);
auto section_header = image_section_header(n);
auto begin = image_base<const uint8_t*>() + section_header->PointerToRawData;
auto end = begin + section_header->Misc.VirtualSize;
for (; begin < end; ++begin) {
if (pred_func(begin, end - begin)) {
return reinterpret_cast<ptr_t>(const_cast<uint8_t*>(begin));
}
}
return nullptr;
}
template<typename ptr_t, typename pred_func_t>
[[nodiscard]]
ptr_t search_section(std::string_view section_name, pred_func_t&& pred_func) const {
static_assert(std::is_pointer_v<ptr_t>);
auto section_header = image_section_header(section_name);
auto begin = image_base<const uint8_t*>() + section_header->PointerToRawData;
auto end = begin + section_header->Misc.VirtualSize;
for (; begin < end; ++begin) {
if (pred_func(begin, end - begin)) {
return reinterpret_cast<ptr_t>(const_cast<uint8_t*>(begin));
}
}
return nullptr;
}
PIMAGE_IMPORT_DESCRIPTOR import_descriptor_from_rva(rva_t rva);
PIMAGE_THUNK_DATA import_lookup_entry_from_rva(rva_t rva);
auto& relocation_distribute() {
return m_relocation_rva_lookup_table;
}
};
}

View File

@ -1,38 +0,0 @@
#include "keystone_assembler.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\keystone_assembler.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
keystone_assembler::keystone_assembler(ks_arch architecture, ks_mode mode) {
auto err = ks_open(architecture, mode, m_keystone_engine.unsafe_addressof());
if (err != KS_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"ks_open failed.");
}
}
void keystone_assembler::option(ks_opt_type option_type, size_t option_value) {
auto err = ks_option(m_keystone_engine.get(), option_type, option_value);
if (err != KS_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"ks_option failed.");
}
}
std::vector<uint8_t> keystone_assembler::assemble(std::string_view asm_string, uint64_t asm_address) const {
resource_wrapper machine_code{ resource_traits::keystone::keystone_alloc{} };
size_t machine_code_size = 0;
size_t stat_count = 0;
if (ks_asm(m_keystone_engine.get(), asm_string.data(), asm_address, machine_code.unsafe_addressof(), &machine_code_size, &stat_count) < 0) {
auto err = ks_errno(m_keystone_engine.get());
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"ks_option failed.");
}
return std::vector<uint8_t>(machine_code.get(), machine_code.get() + machine_code_size);
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,54 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <keystone/keystone.h>
#include "resource_wrapper.hpp"
#include "resource_traits/keystone/keystone_handle.hpp"
#include "exception.hpp"
namespace nkg {
class keystone_assembler {
public:
class backend_error : public ::nkg::exception {
public:
using error_code_t = ks_err;
private:
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, error_code_t keystone_err, std::string_view message) noexcept :
::nkg::exception(file, line, message), m_error_code(keystone_err), m_error_string(ks_strerror(keystone_err)) {}
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return true;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
return m_error_code;
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
return m_error_string;
}
};
private:
resource_wrapper<resource_traits::keystone::keystone_handle> m_keystone_engine;
public:
keystone_assembler(ks_arch architecture, ks_mode mode);
void option(ks_opt_type option_type, size_t option_value);
std::vector<uint8_t> assemble(std::string_view asm_string, uint64_t asm_address = 0) const;
};
}

450
navicat-patcher/main.cpp Normal file
View File

@ -0,0 +1,450 @@
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <plist/plist++.h>
#include <string>
#include "ExceptionSystem.hpp"
#include "ResourceWrapper.hpp"
#include "ResourceTraitsUnix.hpp"
#include "PatchSolutions.hpp"
#include "Misc.hpp"
static void Welcome(bool bWait) {
puts("**********************************************************");
puts("* Navicat Patcher (macOS) by @DoubleLabyrinth *");
puts("* Version: 5.0 *");
puts("**********************************************************");
puts("");
if (bWait) {
puts("Press Enter to continue or Ctrl + C to abort.");
getchar();
}
}
static void Help() {
puts("Usage:");
puts(" navicat-patcher [--dry-run] <Navicat installation path> [RSA-2048 Private Key File]");
puts("");
puts(" [--dry-run] Run patcher without applying any patches.");
puts(" This parameter is optional.");
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 bool ParseCommandLine(int argc, char* argv[], bool& bDryrun, std::string& szInstallPath, std::string& szKeyFilePath) {
if (argc == 2) {
bDryrun = false;
szInstallPath = argv[1];
szKeyFilePath.clear();
return true;
} else if (argc == 3) {
if (strcasecmp(argv[1], "--dry-run") == 0) {
bDryrun = true;
szInstallPath = argv[2];
szKeyFilePath.clear();
return true;
} else {
bDryrun = false;
szInstallPath = argv[1];
szKeyFilePath = argv[2];
return true;
}
} else if (argc == 4) {
if (strcasecmp(argv[1], "--dry-run") == 0) {
bDryrun = true;
szInstallPath = argv[2];
szKeyFilePath = argv[3];
return true;
} else {
return false;
}
} else {
return false;
}
}
static std::string GetNavicatVersion(std::string_view AppPath) {
ARL::ResourceWrapper hInfoPlist{ ARL::ResourceTraits::FileDescriptor{} };
ARL::ResourceWrapper lpInfoPlist{ ARL::ResourceTraits::CppObject<PList::Dictionary>{} };
hInfoPlist.TakeOver(open((std::string(AppPath) + "/Contents/Info.plist").c_str(), O_RDONLY));
if (hInfoPlist.IsValid() == false) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "Failed to open Contents/Info.plist.");
}
struct stat statInfoPlist = {};
if (fstat(hInfoPlist, &statInfoPlist) != 0) {
throw ARL::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()) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "Failed to read Contents/Info.plist.");
}
lpInfoPlist.TakeOver(dynamic_cast<PList::Dictionary*>(PList::Structure::FromXml(contentInfoPlist)));
if (lpInfoPlist.IsValid() == false) {
throw ARL::Exception(__FILE__, __LINE__, "Failed to parse Contents/Info.plist.");
}
auto key_value = lpInfoPlist->Find("CFBundleShortVersionString");
if (key_value == lpInfoPlist->End()) {
throw ARL::Exception(__FILE__, __LINE__, "Cannot find CFBundleShortVersionString in Contents/Info.plist.");
}
if (key_value->second->GetType() == PLIST_STRING) {
return dynamic_cast<PList::String*>(key_value->second)->GetValue();
} else {
throw ARL::Exception(__FILE__, __LINE__, "Type check failed for CFBundleShortVersionString.");
}
}
static void LoadKey(nkg::RSACipher& Cipher, std::string_view szKeyFileName,
nkg::PatchSolution* lpSolution0,
nkg::PatchSolution* lpSolution1,
nkg::PatchSolution* lpSolution2,
nkg::PatchSolution* lpSolution3) {
if (szKeyFileName.empty() == false) {
printf("[*] Import RSA-2048 key from %s\n", szKeyFileName.data());
Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(szKeyFileName);
if ((lpSolution0 && lpSolution0->CheckKey(Cipher) == false) ||
(lpSolution1 && lpSolution1->CheckKey(Cipher) == false) ||
(lpSolution2 && lpSolution2->CheckKey(Cipher) == false) ||
(lpSolution3 && lpSolution3->CheckKey(Cipher) == false))
{
throw ARL::Exception(__FILE__, __LINE__, "The RSA private key you provide cannot be used.");
}
} else {
puts("[*] Generating new RSA private key, it may take a long time...");
do {
Cipher.GenerateKey(2048);
} while ((lpSolution0 && lpSolution0->CheckKey(Cipher) == false) ||
(lpSolution1 && lpSolution1->CheckKey(Cipher) == false) ||
(lpSolution2 && lpSolution2->CheckKey(Cipher) == false) ||
(lpSolution3 && lpSolution3->CheckKey(Cipher) == false)); // re-generate RSA key if CheckKey return false
}
printf("[*] Your RSA private key:\n");
printf(" %s\n",
[&Cipher]() -> std::string {
auto szPrivateKey = Cipher.ExportKeyString<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>();
for (size_t pos = 0; (pos = szPrivateKey.find('\n', pos)) != std::string::npos; pos += strlen("\n ")) {
szPrivateKey.replace(pos, 1, "\n ");
}
return szPrivateKey;
}().c_str()
);
printf("[*] Your RSA public key:\n");
printf(" %s\n",
[&Cipher]() -> std::string {
auto szPublicKey = Cipher.ExportKeyString<nkg::RSAKeyType::PublicKey, nkg::RSAKeyFormat::PEM>();
for (size_t pos = 0; (pos = szPublicKey.find('\n', pos)) != std::string::npos; pos += strlen("\n ")) {
szPublicKey.replace(pos, 1, "\n ");
}
return szPublicKey;
}().c_str()
);
printf("\n");
}
int main(int argc, char* argv[]) {
bool bDryrun;
std::string szInstallPath;
std::string szKeyFilePath;
if (ParseCommandLine(argc, argv, bDryrun, szInstallPath, szKeyFilePath) == false) {
Welcome(false);
Help();
return -1;
} else {
Welcome(true);
try {
if (nkg::Misc::FsIsDirectory(szInstallPath) == false) {
throw ARL::Exception(__FILE__, __LINE__, "Navicat installation path doesn't point to a directory.")
.PushHint("Are you sure the path you specified is correct?")
.PushFormatHint("The path you specified: %s", szInstallPath.c_str());
}
if (szKeyFilePath.empty() == false && nkg::Misc::FsIsFile(szKeyFilePath) == false) {
throw ARL::Exception(__FILE__, __LINE__, "RSA key file path doesn't point to a file.")
.PushHint("Are you sure the path you specified is correct?")
.PushFormatHint("The path you specified: %s", szKeyFilePath.c_str());
}
while (szInstallPath.back() == '/') {
szInstallPath.pop_back();
}
nkg::RSACipher Cipher;
ARL::ResourceWrapper lpSolution0{ ARL::ResourceTraits::CppObject<nkg::PatchSolution>{} };
ARL::ResourceWrapper lpSolution1{ ARL::ResourceTraits::CppObject<nkg::PatchSolution>{} };
ARL::ResourceWrapper lpSolution2{ ARL::ResourceTraits::CppObject<nkg::PatchSolution>{} };
ARL::ResourceWrapper lpSolution3{ ARL::ResourceTraits::CppObject<nkg::PatchSolution>{} };
std::string main_path;
ARL::ResourceWrapper main_fd{ ARL::ResourceTraits::FileDescriptor{} };
ARL::ResourceWrapper main_stat{ ARL::ResourceTraits::CppObject<struct stat>{} };
ARL::ResourceWrapperEx main_mmap{ ARL::ResourceTraits::MapView{}, [&main_stat](void* p) {
if (munmap(p, main_stat->st_size) < 0) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "munmap failed.");
}
} };
ARL::ResourceWrapper main_interpreter{ ARL::ResourceTraits::CppObject<nkg::X64ImageInterpreter>{} };
std::string libcc_path;
ARL::ResourceWrapper libcc_fd{ ARL::ResourceTraits::FileDescriptor{} };
ARL::ResourceWrapper libcc_stat{ ARL::ResourceTraits::CppObject<struct stat>{} };
ARL::ResourceWrapperEx libcc_mmap{ ARL::ResourceTraits::MapView{}, [&libcc_stat](void* p) {
if (munmap(p, libcc_stat->st_size) < 0) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "munmap failed.");
}
} };
ARL::ResourceWrapper libcc_interpreter{ ARL::ResourceTraits::CppObject<nkg::X64ImageInterpreter>{} };
//
// try open "Contents/MacOS/Navicat Premium"
// try open "Contents/Frameworks/libcc-premium.dylib"
//
main_path = szInstallPath + "/Contents/MacOS/Navicat Premium";
main_fd.TakeOver(open(main_path.c_str(), O_RDWR));
if (main_fd.IsValid()) {
printf("[+] Try to open \"%s\" ... Ok!\n", "Contents/MacOS/Navicat Premium");
} else {
if (errno == ENOENT) {
printf("[-] Try to open \"%s\" ... Not found!\n", "Contents/MacOS/Navicat Premium");
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "open failed.");
}
}
libcc_path = szInstallPath + "/Contents/Frameworks/libcc-premium.dylib";
libcc_fd.TakeOver(open(libcc_path.c_str(), O_RDWR));
if (libcc_fd.IsValid()) {
printf("[+] Try to open \"%s\" ... Ok!\n", "Contents/Frameworks/libcc-premium.dylib");
} else {
if (errno == ENOENT) {
printf("[-] Try to open \"%s\" ... Not found!\n", "Contents/Frameworks/libcc-premium.dylib");
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "open failed.");
}
}
//
// try map "Contents/MacOS/Navicat Premium"
// try map "Contents/Frameworks/libcc-premium.dylib"
//
if (main_fd.IsValid()) {
main_stat.TakeOver(new struct stat());
if (fstat(main_fd, main_stat) != 0) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "fstat failed.");
}
main_mmap.TakeOver(mmap(nullptr, main_stat->st_size, PROT_READ | PROT_WRITE, MAP_SHARED, main_fd, 0));
if (main_mmap.IsValid() == false) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "mmap failed.");
}
main_interpreter.TakeOver(
new nkg::X64ImageInterpreter(nkg::X64ImageInterpreter::Parse(main_mmap, main_stat->st_size))
);
lpSolution0.TakeOver(
new nkg::PatchSolution0(*main_interpreter.Get())
);
lpSolution1.TakeOver(
new nkg::PatchSolution1(*main_interpreter.Get())
);
lpSolution2.TakeOver(
new nkg::PatchSolution2(*main_interpreter.Get())
);
}
if (libcc_fd.IsValid()) {
libcc_stat.TakeOver(new struct stat());
if (fstat(libcc_fd, libcc_stat) != 0) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "fstat failed.");
}
libcc_mmap.TakeOver(mmap(nullptr, libcc_stat->st_size, PROT_READ | PROT_WRITE, MAP_SHARED, libcc_fd, 0));
if (libcc_mmap.IsValid() == false) {
throw ARL::SystemError(__FILE__, __LINE__, errno, "mmap failed.");
}
libcc_interpreter.TakeOver(
new nkg::X64ImageInterpreter(nkg::X64ImageInterpreter::Parse(libcc_mmap, libcc_stat->st_size))
);
lpSolution3.TakeOver(
new nkg::PatchSolution3(*libcc_interpreter.Get())
);
}
puts("");
if (lpSolution0.IsValid() && 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 (int Ver0, Ver1, Ver2; sscanf(GetNavicatVersion(szInstallPath).c_str(), "%d.%d.%d", &Ver0, &Ver1, &Ver2) == 3) {
printf("\n");
printf("[*] Your Navicat version: %d.%d.%d\n", Ver0, Ver1, Ver2);
printf("\n");
//
// Begin strategies by different Navicat versions
//
if (Ver0 < 12) { // ver < 12.0.0
throw ARL::SystemError(__FILE__, __LINE__, errno, "Unsupported version of Navicat.");
} else if (Ver0 == 12 && Ver1 == 0 && Ver2 < 24) { // ver < 12.0.24
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", szInstallPath.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 (lpSolution0.IsValid() == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched/modified 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 ((lpSolution0.IsValid() && lpSolution1.IsValid()) == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched/modified before?");
return -1;
}
} else if (Ver0 == 12) { // ver == 12.x.x
// In this case, Solution0 and Solution2 must be applied
if ((lpSolution0.IsValid() && lpSolution2.IsValid()) == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched/modified before?");
return -1;
}
} else { // ver == 15.x.x
// In this case, Solution3 must be applied
if (lpSolution3.IsValid() == false) {
puts("[-] Patch abort. None of PatchSolutions will be applied.");
puts(" Are you sure your Navicat has not been patched/modified before?");
return -1;
}
}
//
// End strategies by different Navicat versions
//
} else {
throw ARL::SystemError(__FILE__, __LINE__, errno, "Failed to get version of Navicat.");
}
//
// Make sure that there is one patch solution at least existing.
//
if (lpSolution0.IsValid() == false && lpSolution1.IsValid() == false && lpSolution2.IsValid() == false && lpSolution3.IsValid() == false) {
throw ARL::Exception(__FILE__, __LINE__, "No patch applied. Patch abort!")
.PushHint("Are you sure your Navicat has not been patched/modified before?");
}
LoadKey(Cipher, szKeyFilePath, lpSolution0, lpSolution1, lpSolution2, lpSolution3);
if (bDryrun == false) {
//
// Save private key if not given
//
if (szKeyFilePath.empty()) {
Cipher.ExportKeyToFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>("RegPrivateKey.pem");
}
//
// 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 (lpSolution0.IsValid()) {
puts("[+] PatchSolution0 has been applied.");
}
if (lpSolution1.IsValid()) {
puts("[+] PatchSolution1 has been applied.");
}
if (lpSolution2.IsValid()) {
puts("[+] PatchSolution2 has been applied.");
}
if (lpSolution3.IsValid()) {
puts("[+] PatchSolution3 has been applied.");
}
if (szKeyFilePath.empty()) {
printf("[*] New RSA-2048 private key has been saved to\n");
printf(" %s/RegPrivateKey.pem\n", nkg::Misc::FsCurrentWorkingDirectory().c_str());
printf("\n");
}
puts("");
puts("**************************************************************");
puts("* Patch has been done successfully. Have fun and enjoy~~ *");
puts("* DO NOT FORGET TO SIGN NAVICAT BY YOUR CERTIFICATE!!! *");
puts("**************************************************************");
} else {
puts("**************************************************************");
puts("* DRY-RUN MODE ENABLE! *");
puts("* NO PATCH WILL BE APPLIED! *");
puts("**************************************************************");
}
return 0;
} catch (ARL::Exception& e) {
printf("[-] %s:%zu ->\n", e.ExceptionFile(), e.ExceptionLine());
printf(" %s\n", e.ExceptionMessage());
if (e.HasErrorCode()) {
printf(" %s (0x%zx)\n", e.ErrorString(), e.ErrorCode());
}
for (const auto& Hint : e.Hints()) {
printf(" Hints: %s\n", Hint.c_str());
}
return -1;
} catch (std::exception& e) {
printf("[-] %s\n", e.what());
return -1;
}
}
}

View File

@ -1,210 +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>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{1b6920eb-e6ed-465f-9600-b5f816752375}</ProjectGuid>
<RootNamespace>navicatpatcher</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</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\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<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="i386_emulator.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="image_interpreter.cpp" />
<ClCompile Include="keystone_assembler.cpp" />
<ClCompile Include="patch_solution_since_16.0.7.0.amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="amd64_emulator.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.generic.cpp" />
<ClCompile Include="patch_solution_since_16.0.7.0.i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="wmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="i386_emulator.hpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="keystone_assembler.hpp" />
<ClInclude Include="patch_solution.hpp" />
<ClInclude Include="image_interpreter.hpp" />
<ClInclude Include="patch_solution_since.hpp" />
<ClInclude Include="patch_solution_since_16.0.7.0.hpp" />
<ClInclude Include="amd64_emulator.hpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClInclude>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,66 +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;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;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="wmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="image_interpreter.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="amd64_emulator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="keystone_assembler.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="i386_emulator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="patch_solution.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution_since_16.0.7.0.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution_since.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="image_interpreter.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="amd64_emulator.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="keystone_assembler.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="i386_emulator.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More