Compare commits
No commits in common. "linux-archived" and "windows" have entirely different histories.
linux-arch
...
windows
68
.github/workflows/build.yml
vendored
Normal file
68
.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,68 @@
|
||||
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
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@ -1,8 +1,4 @@
|
||||
*/.DS_Store
|
||||
.vscode/*
|
||||
bin/*
|
||||
navicat-patcher/Elf64Crafter.hpp
|
||||
navicat-patcher/Elf64Crafter.cpp
|
||||
navicat-patcher/Elf64InterpreterAmd64.hpp
|
||||
navicat-patcher/Elf64InterpreterAmd64.cpp
|
||||
RegPrivateKey.pem
|
||||
.vs/
|
||||
.vscode/
|
||||
bin/
|
||||
obj/
|
||||
|
||||
100
Makefile
100
Makefile
@ -1,100 +0,0 @@
|
||||
CC = g++
|
||||
UNAME = $(shell uname)
|
||||
|
||||
ifeq ($(UNAME),Darwin)
|
||||
OPENSSL_INCLUDE_PATH = /usr/local/opt/openssl@1.1/include
|
||||
OPENSSL_LIB_PATH = /usr/local/opt/openssl@1.1/lib
|
||||
else
|
||||
OPENSSL_INCLUDE_PATH =
|
||||
OPENSSL_LIB_PATH =
|
||||
endif
|
||||
CAPSTONE_INCLUDE_PATH =
|
||||
CAPSTONE_LIB_PATH =
|
||||
KEYSTONE_INCLUDE_PATH =
|
||||
KEYSTONE_LIB_PATH =
|
||||
RAPIDJSON_INCLUDE_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)CapstoneDisassembler.hpp \
|
||||
$(PATCHER_DIR)KeystoneAssembler.hpp \
|
||||
$(PATCHER_DIR)Elf64Interpreter.hpp \
|
||||
$(PATCHER_DIR)ExceptionCapstone.hpp \
|
||||
$(PATCHER_DIR)ExceptionKeystone.hpp \
|
||||
$(PATCHER_DIR)MemoryAccess.hpp \
|
||||
$(PATCHER_DIR)Misc.hpp \
|
||||
$(PATCHER_DIR)PatchSolutions.hpp \
|
||||
$(PATCHER_DIR)ResourceTraitsCapstone.hpp \
|
||||
$(PATCHER_DIR)ResourceTraitsKeystone.hpp \
|
||||
$(PATCHER_DIR)ResourceTraitsUnix.hpp
|
||||
|
||||
PATCHER_SOURCE = \
|
||||
$(PATCHER_DIR)CapstoneDisassembler.cpp \
|
||||
$(PATCHER_DIR)KeystoneAssembler.cpp \
|
||||
$(PATCHER_DIR)Elf64Interpreter.cpp \
|
||||
$(PATCHER_DIR)Misc.cpp \
|
||||
$(PATCHER_DIR)PatchSolution.cpp \
|
||||
$(PATCHER_DIR)PatchSolution0.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) \
|
||||
$(if $(OPENSSL_INCLUDE_PATH),-I$(OPENSSL_INCLUDE_PATH),) $(if $(OPENSSL_LIB_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),) \
|
||||
$(PATCHER_SOURCE) -o $(PATCHER_BINARY) -lcrypto -lcapstone -lkeystone \
|
||||
-lstdc++fs
|
||||
@echo
|
||||
|
||||
keygen: $(KEYGEM_HEADER) $(KEYGEN_SOURCE)
|
||||
@if [ ! -d $(OUTPUT_DIR) ]; then mkdir -p $(OUTPUT_DIR); fi
|
||||
$(CC) -std=c++17 -O2 \
|
||||
-I$(COMMON_DIR) \
|
||||
$(if $(OPENSSL_INCLUDE_PATH),-I$(OPENSSL_INCLUDE_PATH),) $(if $(OPENSSL_LIB_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
|
||||
|
||||
283
README.md
283
README.md
@ -1,276 +1,35 @@
|
||||
# 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 :-(
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```console
|
||||
$ git clone -b windows --single-branch https://notabug.org/doublesine/navicat-keygen.git
|
||||
```
|
||||
|
||||
## 1. How does it work?
|
||||
|
||||
see [here](doc/how-does-it-work.md).
|
||||
see [here](doc/how-does-it-work.md). (WATING TO BE UPDATED)
|
||||
|
||||
## 2. How to build
|
||||
## 2. How to build?
|
||||
|
||||
see [here](doc/how-to-build.md).
|
||||
|
||||
## 3. How to Use
|
||||
## 3. How to use?
|
||||
|
||||
1. Download navicat from official website.
|
||||
see [here](doc/how-to-use.md).
|
||||
|
||||
And you will get a AppImage file. For example, `navicat15-premium-en.AppImage`.
|
||||
## 4. Contributor
|
||||
|
||||
I assume that the AppImage file is in `~/Desktop` folder.
|
||||
* Deltafox79
|
||||
|
||||
2. Extract all files in the AppImage to a directory. For example:
|
||||
|
||||
```console
|
||||
$ mkdir ~/Desktop/navicat15-premium-en
|
||||
$ sudo mount -o loop ~/Desktop/navicat15-premium-en.AppImage ~/Desktop/navicat15-premium-en
|
||||
$ cp -r ~/Desktop/navicat15-premium-en ~/Desktop/navicat15-premium-en-patched
|
||||
$ sudo umount ~/Desktop/navicat15-premium-en
|
||||
$ rm -rf ~/Desktop/navicat15-premium-en
|
||||
```
|
||||
|
||||
3. [Build keygen and patcher.](doc/how-to-build.md)
|
||||
|
||||
4. Use `navicat-patcher` to replace the official 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 a directory where Navicat locates
|
||||
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
|
||||
$ ./bin/navicat-patcher ~/Desktop/navicat15-premium-en-patched
|
||||
```
|
||||
|
||||
It has been tested on __Navicat Premium 15.0.3 English For Linux__ version.
|
||||
|
||||
The following is an example of output:
|
||||
|
||||
```console
|
||||
**********************************************************
|
||||
* Navicat Patcher (Linux) by @DoubleLabyrinth *
|
||||
* Version: 1.0 *
|
||||
**********************************************************
|
||||
|
||||
Press ENTER to continue or Ctrl + C to abort.
|
||||
|
||||
[+] Try to open libcc.so ... Ok!
|
||||
|
||||
[+] PatchSolution0 ...... Ready to apply
|
||||
RefSegment = 1
|
||||
MachineCodeRva = 0x0000000001413e10
|
||||
PatchMarkOffset = +0x00000000029ecf40
|
||||
|
||||
[*] Generating new RSA private key, it may take a long time...
|
||||
[*] Your RSA private key:
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEArRsg1+6JZxZNMhGyuM8d+Ue/ky9LSv/XyKh+wppQMS5wx7QE
|
||||
XFcdDgaByNZeLMenh8sgungahWbPo/5jmkDuuHHrVMU748q2JLL1E3nFraPZqoRD
|
||||
...
|
||||
...
|
||||
B1Z5AoGBAK8cWMvNYf1pfQ9w6nD4gc3NgRVYLctxFLmkGylqrzs8faoLLBkFq3iI
|
||||
s2vdYwF//wuN2aq8JHldGriyb6xkDjdqiEk+0c98LmyKNmEVt8XghjrZuUrn8dA0
|
||||
0hfInLdRpaB7b+UeIQavw9yLH0ilijAcMkGzzom7vdqDPizoLpXQ
|
||||
-----END RSA PRIVATE KEY-----
|
||||
[*] Your RSA public key:
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArRsg1+6JZxZNMhGyuM8d
|
||||
+Ue/ky9LSv/XyKh+wppQMS5wx7QEXFcdDgaByNZeLMenh8sgungahWbPo/5jmkDu
|
||||
...
|
||||
...
|
||||
GrVJ3o8aDm35EzGymp4ON+A0fdAkweqKV6FqxEJqLWIDRYh+Z01JXUZIrKmnCkgf
|
||||
QQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
|
||||
*******************************************************
|
||||
* PatchSolution0 *
|
||||
*******************************************************
|
||||
[*] Previous:
|
||||
+0x0000000000000070 01 00 00 00 05 00 00 00 ........
|
||||
+0x0000000000000080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x0000000000000090 00 00 00 00 00 00 00 00 40 cf 9e 02 00 00 00 00 ........@.......
|
||||
+0x00000000000000a0 40 cf 9e 02 00 00 00 00 00 10 00 00 00 00 00 00 @...............
|
||||
[*] After:
|
||||
+0x0000000000000070 01 00 00 00 05 00 00 00 ........
|
||||
+0x0000000000000080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x0000000000000090 00 00 00 00 00 00 00 00 d0 d0 9e 02 00 00 00 00 ................
|
||||
+0x00000000000000a0 d0 d0 9e 02 00 00 00 00 00 10 00 00 00 00 00 00 ................
|
||||
|
||||
[*] Previous:
|
||||
+0x00000000029ecf40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x00000000029ecf50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x00000000029ecf60 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
...
|
||||
...
|
||||
+0x00000000029ed0c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
[*] After:
|
||||
+0x00000000029ecf40 ef be ad de 4d 49 49 42 49 6a 41 4e 42 67 6b 71 ....MIIBIjANBgkq
|
||||
+0x00000000029ecf50 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 hkiG9w0BAQEFAAOC
|
||||
+0x00000000029ecf60 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41 AQ8AMIIBCgKCAQEA
|
||||
...
|
||||
...
|
||||
...
|
||||
+0x00000000029ed0c0 43 6b 67 66 51 51 49 44 41 51 41 42 ad de ef be CkgfQQIDAQAB....
|
||||
|
||||
[*] Previous:
|
||||
+0x0000000001413e10 44 0f b6 24 18 48 8b 44 24 28 8b 50 f8 85 d2 79 D..$.H.D$(.P...y
|
||||
+0x0000000001413e20 6f o
|
||||
[*] After:
|
||||
+0x0000000001413e10 45 31 e4 48 8d 05 2a 91 5d 01 90 90 90 90 90 90 E1.H..*.].......
|
||||
+0x0000000001413e20 90 .
|
||||
|
||||
[*] New RSA-2048 private key has been saved to
|
||||
/home/doublesine/github.com/navicat-keygen/RegPrivateKey.pem
|
||||
|
||||
*******************************************************
|
||||
* PATCH HAS BEEN DONE SUCCESSFULLY! *
|
||||
* HAVE FUN AND ENJOY~ *
|
||||
*******************************************************
|
||||
```
|
||||
|
||||
5. Repack files into a new AppImage:
|
||||
|
||||
__Example:__
|
||||
|
||||
```console
|
||||
$ wget 'https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage'
|
||||
$ chmod +x appimagetool-x86_64.AppImage
|
||||
$ ./appimagetool-x86_64.AppImage ~/Desktop/navicat15-premium-en-patched ~/Desktop/navicat15-premium-en-patched.AppImage
|
||||
```
|
||||
|
||||
6. Run the newly-generated AppImage:
|
||||
|
||||
```console
|
||||
$ chmod +x ~/Desktop/navicat15-premium-en-patched.AppImage
|
||||
$ ~/Desktop/navicat15-premium-en-patched.AppImage
|
||||
```
|
||||
|
||||
7. Use `navicat-keygen` to generate __snKey__ and __Activation Code__.
|
||||
|
||||
```
|
||||
Usage:
|
||||
navicat-keygen <--bin|--text> [--adv] <RSA-2048 Private Key File>
|
||||
|
||||
<--bin|--text> Specify "-bin" to generate "license_file" used by Navicat 11.
|
||||
Specify "-text" to generate base64-encoded activation code.
|
||||
This parameter must be specified.
|
||||
|
||||
[--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:__
|
||||
|
||||
```console
|
||||
$ ./bin/navicat-keygen --text ./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
|
||||
$ ./bin/navicat-keygen --text ./RegPrivateKey.pem
|
||||
**********************************************************
|
||||
* Navicat Keygen (Linux) by @DoubleLabyrinth *
|
||||
* Version: 1.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: 0 ~ 15, default: 12)> 15
|
||||
|
||||
[*] Serial number:
|
||||
NAVM-RTVJ-EO42-IODD
|
||||
|
||||
[*] 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__.
|
||||
|
||||
8. __Disconnect your network__. Find and click `Registration`.
|
||||
|
||||
Fill license key by __Serial number__ that the keygen gave and click `Activate`.
|
||||
|
||||
9. Generally online activation will fail and Navicat will ask you do `Manual Activation`, just choose it.
|
||||
|
||||
10. 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)
|
||||
OaGPC3MNjJ/pINbajFzLRkrV2OaSXYLr2tNLDW0fIthPOJQFXr84OOroCY1XN8R2xl2j7epZ182PL6q+BRaSC6hnHev/cZwhq/4LFNcLu0T0D/QUhEEBJl4QzFr8TlFSYI1qhWGLIxkGZggA8vMLMb/sLHYn9QebBigvleP9dNCS4sO82bilFrKFUtq3ch8r7V3mbcbXJCfLhXgrHRvT2FV/s1BFuZzuWZUujxlp37U6Y2PFD8fQgsgBUwrxYbF0XxnXKbCmvtgh2yaB3w9YnQLoDiipKp7io1IxEFMYHCpjmfTGk4WU01mSbdi2OS/wm9pq2Y62xvwawsq1WQJoMg==
|
||||
|
||||
[*] Request Info:
|
||||
{"K":"NAVMRTVJEO42IODD", "DI":"4A12F84C6A088104D23E", "P":"linux"}
|
||||
|
||||
[*] Response Info:
|
||||
{"K":"NAVMRTVJEO42IODD","DI":"4A12F84C6A088104D23E","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1575543648}
|
||||
|
||||
[*] Activation Code:
|
||||
i45HIr7T1g69Cm9g3bN1DBpM/Zio8idBw3LOFGXFQjXj0nPfy9yRGuxaUBQkWXSOWa5EAv7S9Z1sljlkZP6cKdfDGYsBb/4N1W5Oj1qogzNtRo5LGwKe9Re3zPY3SO8RXACfpNaKjdjpoOQa9GjQ/igDVH8r1k+Oc7nEnRPZBm0w9aJIM9kS42lbjynVuOJMZIotZbk1NloCodNyRQw3vEEP7kq6bRZsQFp2qF/mr+hIPH8lo/WF3hh+2NivdrzmrKKhPnoqSgSsEttL9a6ueGOP7Io3j2lAFqb9hEj1uC3tPRpYcBpTZX7GAloAENSasFwMdBIdszifDrRW42wzXw==
|
||||
```
|
||||
|
||||
11. 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.
|
||||
|
||||
12. Clean up:
|
||||
|
||||
```console
|
||||
$ rm ~/Desktop/navicat15-premium-en.AppImage
|
||||
$ rm -rf ~/Desktop/navicat15-premium-en-patched
|
||||
$ mv ~/Desktop/navicat15-premium-en-patched.AppImage ~/Desktop/navicat15-premium-en.AppImage
|
||||
```
|
||||
* dragonflylee
|
||||
|
||||
* zenuo
|
||||
|
||||
282
README.zh-CN.md
282
README.zh-CN.md
@ -1,272 +1,34 @@
|
||||
# Navicat Keygen
|
||||
# navicat-keygen for windows
|
||||
|
||||
## 1. 它是怎么工作的?
|
||||
这份repo将会告诉你Navicat是怎么完成离线激活的。
|
||||
|
||||
见[这里](doc/how-does-it-work.zh-CN.md).
|
||||
第一次归档的代码位于 [`windows-archived`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived) 分支。归档原因:包含第三方二进制库,项目过大。
|
||||
|
||||
第二次归档的代码位于 [`windows-archived2`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived2) 分支。归档原因:Navicat进入16.x.x版本,本项目打算进行重构。
|
||||
|
||||
当你clone该仓库的时候,请使用 `--single-branch` 选项,以此避免clone到已被归档的分支、以及节省你的时间和磁盘空间。
|
||||
|
||||
```console
|
||||
$ git clone -b windows --single-branch https://notabug.org/doublesine/navicat-keygen.git
|
||||
```
|
||||
|
||||
## 1. 注册机是怎么工作的?
|
||||
|
||||
见[这里](doc/how-does-it-work.zh-CN.md)。
|
||||
|
||||
## 2. 如何编译?
|
||||
|
||||
见[这里](doc/how-to-build.zh-CN.md).
|
||||
见[这里](doc/how-to-build.zh-CN.md)。
|
||||
|
||||
## 3. 如何使用?
|
||||
## 3. 如何使用这个注册机?
|
||||
|
||||
1. 从官方网站下载navicat。
|
||||
见[这里](doc/how-to-use.zh-CN.md)。
|
||||
|
||||
你会得到一个AppImage文件。例如 `navicat15-premium-en.AppImage`。
|
||||
## 4. 贡献者
|
||||
|
||||
我假定这个AppImage文件在 `~/Desktop` 文件夹下。
|
||||
* Deltafox79
|
||||
|
||||
2. 提取AppImage文件里的所有文件到一个文件夹。例如:
|
||||
* dragonflylee
|
||||
|
||||
```console
|
||||
$ mkdir ~/Desktop/navicat15-premium-en
|
||||
$ sudo mount -o loop ~/Desktop/navicat15-premium-en.AppImage ~/Desktop/navicat15-premium-en
|
||||
$ cp -r ~/Desktop/navicat15-premium-en ~/Desktop/navicat15-premium-en-patched
|
||||
$ sudo umount ~/Desktop/navicat15-premium-en
|
||||
$ rm -rf ~/Desktop/navicat15-premium-en
|
||||
```
|
||||
|
||||
3. [编译patcher和keygen。](doc/how-to-build.zh-CN.md)
|
||||
|
||||
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 a directory where Navicat locates
|
||||
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
|
||||
$ ./bin/navicat-patcher ~/Desktop/navicat15-premium-en-patched
|
||||
```
|
||||
|
||||
__Navicat Premium 15.0.3 Linux 英文版__ 已经通过测试。
|
||||
|
||||
下面是一份样例输出:
|
||||
|
||||
```console
|
||||
**********************************************************
|
||||
* Navicat Patcher (Linux) by @DoubleLabyrinth *
|
||||
* Version: 1.0 *
|
||||
**********************************************************
|
||||
|
||||
Press ENTER to continue or Ctrl + C to abort.
|
||||
|
||||
[+] Try to open libcc.so ... Ok!
|
||||
|
||||
[+] PatchSolution0 ...... Ready to apply
|
||||
RefSegment = 1
|
||||
MachineCodeRva = 0x0000000001413e10
|
||||
PatchMarkOffset = +0x00000000029ecf40
|
||||
|
||||
[*] Generating new RSA private key, it may take a long time...
|
||||
[*] Your RSA private key:
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEArRsg1+6JZxZNMhGyuM8d+Ue/ky9LSv/XyKh+wppQMS5wx7QE
|
||||
XFcdDgaByNZeLMenh8sgungahWbPo/5jmkDuuHHrVMU748q2JLL1E3nFraPZqoRD
|
||||
...
|
||||
...
|
||||
B1Z5AoGBAK8cWMvNYf1pfQ9w6nD4gc3NgRVYLctxFLmkGylqrzs8faoLLBkFq3iI
|
||||
s2vdYwF//wuN2aq8JHldGriyb6xkDjdqiEk+0c98LmyKNmEVt8XghjrZuUrn8dA0
|
||||
0hfInLdRpaB7b+UeIQavw9yLH0ilijAcMkGzzom7vdqDPizoLpXQ
|
||||
-----END RSA PRIVATE KEY-----
|
||||
[*] Your RSA public key:
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArRsg1+6JZxZNMhGyuM8d
|
||||
+Ue/ky9LSv/XyKh+wppQMS5wx7QEXFcdDgaByNZeLMenh8sgungahWbPo/5jmkDu
|
||||
...
|
||||
...
|
||||
GrVJ3o8aDm35EzGymp4ON+A0fdAkweqKV6FqxEJqLWIDRYh+Z01JXUZIrKmnCkgf
|
||||
QQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
|
||||
*******************************************************
|
||||
* PatchSolution0 *
|
||||
*******************************************************
|
||||
[*] Previous:
|
||||
+0x0000000000000070 01 00 00 00 05 00 00 00 ........
|
||||
+0x0000000000000080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x0000000000000090 00 00 00 00 00 00 00 00 40 cf 9e 02 00 00 00 00 ........@.......
|
||||
+0x00000000000000a0 40 cf 9e 02 00 00 00 00 00 10 00 00 00 00 00 00 @...............
|
||||
[*] After:
|
||||
+0x0000000000000070 01 00 00 00 05 00 00 00 ........
|
||||
+0x0000000000000080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x0000000000000090 00 00 00 00 00 00 00 00 d0 d0 9e 02 00 00 00 00 ................
|
||||
+0x00000000000000a0 d0 d0 9e 02 00 00 00 00 00 10 00 00 00 00 00 00 ................
|
||||
|
||||
[*] Previous:
|
||||
+0x00000000029ecf40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x00000000029ecf50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
+0x00000000029ecf60 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
...
|
||||
...
|
||||
+0x00000000029ed0c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
|
||||
[*] After:
|
||||
+0x00000000029ecf40 ef be ad de 4d 49 49 42 49 6a 41 4e 42 67 6b 71 ....MIIBIjANBgkq
|
||||
+0x00000000029ecf50 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 hkiG9w0BAQEFAAOC
|
||||
+0x00000000029ecf60 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41 AQ8AMIIBCgKCAQEA
|
||||
...
|
||||
...
|
||||
...
|
||||
+0x00000000029ed0c0 43 6b 67 66 51 51 49 44 41 51 41 42 ad de ef be CkgfQQIDAQAB....
|
||||
|
||||
[*] Previous:
|
||||
+0x0000000001413e10 44 0f b6 24 18 48 8b 44 24 28 8b 50 f8 85 d2 79 D..$.H.D$(.P...y
|
||||
+0x0000000001413e20 6f o
|
||||
[*] After:
|
||||
+0x0000000001413e10 45 31 e4 48 8d 05 2a 91 5d 01 90 90 90 90 90 90 E1.H..*.].......
|
||||
+0x0000000001413e20 90 .
|
||||
|
||||
[*] New RSA-2048 private key has been saved to
|
||||
/home/doublesine/github.com/navicat-keygen/RegPrivateKey.pem
|
||||
|
||||
*******************************************************
|
||||
* PATCH HAS BEEN DONE SUCCESSFULLY! *
|
||||
* HAVE FUN AND ENJOY~ *
|
||||
*******************************************************
|
||||
```
|
||||
|
||||
5. 将文件重新打包成AppImage:
|
||||
|
||||
__例如:__
|
||||
|
||||
```console
|
||||
$ wget 'https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage'
|
||||
$ chmod +x appimagetool-x86_64.AppImage
|
||||
$ ./appimagetool-x86_64.AppImage ~/Desktop/navicat15-premium-en-patched ~/Desktop/navicat15-premium-en-patched.AppImage
|
||||
```
|
||||
|
||||
6. 运行刚生成的AppImage:
|
||||
|
||||
```console
|
||||
$ chmod +x ~/Desktop/navicat15-premium-en-patched.AppImage
|
||||
$ ~/Desktop/navicat15-premium-en-patched.AppImage
|
||||
```
|
||||
|
||||
7. 使用 `navicat-keygen` 来生成 __序列号__ 和 __激活码__。
|
||||
|
||||
```
|
||||
Usage:
|
||||
navicat-keygen <--bin|--text> [--adv] <RSA-2048 Private Key File>
|
||||
|
||||
<--bin|--text> Specify "--bin" to generate "license_file" used by Navicat 11.
|
||||
Specify "--text" to generate base64-encoded activation code.
|
||||
This parameter must be specified.
|
||||
|
||||
[--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.
|
||||
```
|
||||
|
||||
__例如:__
|
||||
|
||||
```console
|
||||
$ ./bin/navicat-keygen --text ./RegPrivateKey.pem
|
||||
```
|
||||
|
||||
你会被要求选择Navicat产品类别、Navicat语言版本和填写主版本号。之后一个随机生成的 __序列号__ 将会给出。
|
||||
|
||||
```console
|
||||
$ ./bin/navicat-keygen --text ./RegPrivateKey.pem
|
||||
**********************************************************
|
||||
* Navicat Keygen (Linux) by @DoubleLabyrinth *
|
||||
* Version: 1.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: 0 ~ 15, default: 12)> 15
|
||||
|
||||
[*] Serial number:
|
||||
NAVM-RTVJ-EO42-IODD
|
||||
|
||||
[*] Your name:
|
||||
```
|
||||
|
||||
你可以使用这个 __序列号__ 来暂时激活Navicat。
|
||||
|
||||
之后你会被要求填写 __用户名__ 和 __组织名__。你可以随意填写,但别太长。
|
||||
|
||||
```console
|
||||
[*] Your name: DoubleLabyrinth
|
||||
[*] Your organization: DoubleLabyrinth
|
||||
|
||||
[*] Input request code in Base64: (Double press ENTER to end)
|
||||
```
|
||||
|
||||
之后你会被要求填写请求码。__注意不要关闭keygen。__
|
||||
|
||||
8. __断开网络__. 找到注册窗口,填写keygen给你的 __序列号__,然后点击 `激活`。
|
||||
|
||||
9. 通常在线激活会失败,所以在弹出的提示中选择 `手动激活`。
|
||||
|
||||
10. 复制 __请求码__ 到keygen,连按两次回车结束。
|
||||
|
||||
```console
|
||||
[*] Input request code in Base64: (Double press ENTER to end)
|
||||
OaGPC3MNjJ/pINbajFzLRkrV2OaSXYLr2tNLDW0fIthPOJQFXr84OOroCY1XN8R2xl2j7epZ182PL6q+BRaSC6hnHev/cZwhq/4LFNcLu0T0D/QUhEEBJl4QzFr8TlFSYI1qhWGLIxkGZggA8vMLMb/sLHYn9QebBigvleP9dNCS4sO82bilFrKFUtq3ch8r7V3mbcbXJCfLhXgrHRvT2FV/s1BFuZzuWZUujxlp37U6Y2PFD8fQgsgBUwrxYbF0XxnXKbCmvtgh2yaB3w9YnQLoDiipKp7io1IxEFMYHCpjmfTGk4WU01mSbdi2OS/wm9pq2Y62xvwawsq1WQJoMg==
|
||||
|
||||
[*] Request Info:
|
||||
{"K":"NAVMRTVJEO42IODD", "DI":"4A12F84C6A088104D23E", "P":"linux"}
|
||||
|
||||
[*] Response Info:
|
||||
{"K":"NAVMRTVJEO42IODD","DI":"4A12F84C6A088104D23E","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1575543648}
|
||||
|
||||
[*] Activation Code:
|
||||
i45HIr7T1g69Cm9g3bN1DBpM/Zio8idBw3LOFGXFQjXj0nPfy9yRGuxaUBQkWXSOWa5EAv7S9Z1sljlkZP6cKdfDGYsBb/4N1W5Oj1qogzNtRo5LGwKe9Re3zPY3SO8RXACfpNaKjdjpoOQa9GjQ/igDVH8r1k+Oc7nEnRPZBm0w9aJIM9kS42lbjynVuOJMZIotZbk1NloCodNyRQw3vEEP7kq6bRZsQFp2qF/mr+hIPH8lo/WF3hh+2NivdrzmrKKhPnoqSgSsEttL9a6ueGOP7Io3j2lAFqb9hEj1uC3tPRpYcBpTZX7GAloAENSasFwMdBIdszifDrRW42wzXw==
|
||||
```
|
||||
|
||||
11. 最终你会得到一个base64编码的 __激活码__。
|
||||
|
||||
将之复制到 `手动激活` 的窗口,然后点击 `激活`。
|
||||
|
||||
如果没有什么意外,应该可以成功激活。
|
||||
|
||||
12. 最后的清理:
|
||||
|
||||
```console
|
||||
$ rm ~/Desktop/navicat15-premium-en.AppImage
|
||||
$ rm -rf ~/Desktop/navicat15-premium-en-patched
|
||||
$ mv ~/Desktop/navicat15-premium-en-patched.AppImage ~/Desktop/navicat15-premium-en.AppImage
|
||||
```
|
||||
* zenuo
|
||||
|
||||
|
||||
@ -1,124 +0,0 @@
|
||||
#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();
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,29 +0,0 @@
|
||||
#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")
|
||||
|
||||
}
|
||||
|
||||
@ -1,45 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -1,38 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
@ -1,274 +0,0 @@
|
||||
#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(__BASE_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(__BASE_FILE__, __LINE__, "PEM_write_bio_RSA_PUBKEY failed.");
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (__Format == RSAKeyFormat::PKCS1) {
|
||||
if (PEM_write_bio_RSAPublicKey(lpBIO, lpRSA) == 0) {
|
||||
throw ARL::Exception(__BASE_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(__BASE_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(__BASE_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(__BASE_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(__BASE_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(__BASE_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 "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(__BASE_FILE__, __LINE__, ERR_get_error(), "BN_new failed.");
|
||||
}
|
||||
|
||||
if (!BN_set_word(bn_e, e)) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "BN_set_word failed.");
|
||||
}
|
||||
|
||||
if (!RSA_generate_key_ex(Get(), bits, bn_e, nullptr)) {
|
||||
throw ARL::OpensslError(__BASE_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(__BASE_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(__BASE_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(__BASE_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(__BASE_FILE__, __LINE__, "BIO_new failed.");
|
||||
}
|
||||
|
||||
if (BIO_puts(TempMemory.Get(), KeyString.data()) <= 0) {
|
||||
throw ARL::Exception(__BASE_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(__BASE_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(__BASE_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(__BASE_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(__BASE_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(__BASE_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(__BASE_FILE__, __LINE__, ERR_get_error(), "RSA_public_decrypt failed.")
|
||||
.PushHint("Are your sure you DO provide a correct public key?");
|
||||
}
|
||||
}
|
||||
|
||||
return BytesWritten;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,68 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,375 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
49
common/common.vcxitems
Normal file
49
common/common.vcxitems
Normal file
@ -0,0 +1,49 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Label="Globals">
|
||||
<MSBuildAllProjects Condition="'$(MSBuildVersion)' == '' Or '$(MSBuildVersion)' < '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>
|
||||
6
common/common.vcxitems.user
Normal file
6
common/common.vcxitems.user
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ShowAllFiles>true</ShowAllFiles>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
79
common/cp_converter.hpp
Normal file
79
common/cp_converter.hpp
Normal file
@ -0,0 +1,79 @@
|
||||
#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
|
||||
86
common/exception.hpp
Normal file
86
common/exception.hpp
Normal file
@ -0,0 +1,86 @@
|
||||
#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;
|
||||
};
|
||||
|
||||
}
|
||||
10
common/exceptions/index_exception.hpp
Normal file
10
common/exceptions/index_exception.hpp
Normal file
@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include "../exception.hpp"
|
||||
|
||||
namespace nkg::exceptions {
|
||||
|
||||
class index_exception : public ::nkg::exception {
|
||||
using ::nkg::exception::exception;
|
||||
};
|
||||
|
||||
}
|
||||
10
common/exceptions/key_exception.hpp
Normal file
10
common/exceptions/key_exception.hpp
Normal file
@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include "../exception.hpp"
|
||||
|
||||
namespace nkg::exceptions {
|
||||
|
||||
class key_exception : public ::nkg::exception {
|
||||
using ::nkg::exception::exception;
|
||||
};
|
||||
|
||||
}
|
||||
10
common/exceptions/not_implemented_exception.hpp
Normal file
10
common/exceptions/not_implemented_exception.hpp
Normal file
@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include "../exception.hpp"
|
||||
|
||||
namespace nkg::exceptions {
|
||||
|
||||
class not_implemented_exception : public ::nkg::exception {
|
||||
using ::nkg::exception::exception;
|
||||
};
|
||||
|
||||
}
|
||||
10
common/exceptions/operation_canceled_exception.hpp
Normal file
10
common/exceptions/operation_canceled_exception.hpp
Normal file
@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include "../exception.hpp"
|
||||
|
||||
namespace nkg::exceptions {
|
||||
|
||||
class operation_canceled_exception : public ::nkg::exception {
|
||||
using ::nkg::exception::exception;
|
||||
};
|
||||
|
||||
}
|
||||
10
common/exceptions/overflow_exception.hpp
Normal file
10
common/exceptions/overflow_exception.hpp
Normal file
@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include "../exception.hpp"
|
||||
|
||||
namespace nkg::exceptions {
|
||||
|
||||
class overflow_exception : public ::nkg::exception {
|
||||
using ::nkg::exception::exception;
|
||||
};
|
||||
|
||||
}
|
||||
30
common/exceptions/win32_exception.cpp
Normal file
30
common/exceptions/win32_exception.cpp
Normal file
@ -0,0 +1,30 @@
|
||||
#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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
35
common/exceptions/win32_exception.hpp
Normal file
35
common/exceptions/win32_exception.hpp
Normal file
@ -0,0 +1,35 @@
|
||||
#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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/cxx_dynamic_array_traits.hpp
Normal file
21
common/resource_traits/cxx_dynamic_array_traits.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/cxx_object_traits.hpp
Normal file
21
common/resource_traits/cxx_object_traits.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
35
common/resource_traits/keystone/keystone_handle.hpp
Normal file
35
common/resource_traits/keystone/keystone_handle.hpp
Normal file
@ -0,0 +1,35 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
}
|
||||
21
common/resource_traits/openssl/bignum.hpp
Normal file
21
common/resource_traits/openssl/bignum.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/bio.hpp
Normal file
21
common/resource_traits/openssl/bio.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/bio_chain.hpp
Normal file
21
common/resource_traits/openssl/bio_chain.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/decoder_ctx.hpp
Normal file
21
common/resource_traits/openssl/decoder_ctx.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/encoder_ctx.hpp
Normal file
21
common/resource_traits/openssl/encoder_ctx.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/evp_cipher_ctx.hpp
Normal file
21
common/resource_traits/openssl/evp_cipher_ctx.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/evp_pkey.hpp
Normal file
21
common/resource_traits/openssl/evp_pkey.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/evp_pkey_ctx.hpp
Normal file
21
common/resource_traits/openssl/evp_pkey_ctx.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/openssl/rsa.hpp
Normal file
21
common/resource_traits/openssl/rsa.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/unicorn/unicorn_handle.hpp
Normal file
21
common/resource_traits/unicorn/unicorn_handle.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/win32/file_handle.hpp
Normal file
21
common/resource_traits/win32/file_handle.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/win32/generic_handle.hpp
Normal file
21
common/resource_traits/win32/generic_handle.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/win32/local_alloc.hpp
Normal file
21
common/resource_traits/win32/local_alloc.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
21
common/resource_traits/win32/map_view_ptr.hpp
Normal file
21
common/resource_traits/win32/map_view_ptr.hpp
Normal file
@ -0,0 +1,21 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
245
common/resource_wrapper.hpp
Normal file
245
common/resource_wrapper.hpp
Normal file
@ -0,0 +1,245 @@
|
||||
#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>>;
|
||||
|
||||
}
|
||||
625
common/rsa_cipher.cpp
Normal file
625
common/rsa_cipher.cpp
Normal file
@ -0,0 +1,625 @@
|
||||
#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
|
||||
161
common/rsa_cipher.hpp
Normal file
161
common/rsa_cipher.hpp
Normal file
@ -0,0 +1,161 @@
|
||||
#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
|
||||
@ -281,3 +281,4 @@
|
||||
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.
|
||||
|
||||
|
||||
@ -279,3 +279,4 @@
|
||||
4. 用Base64编码这256字节的密文,就可以得到 __激活码__。
|
||||
|
||||
5. 在Navicat软件中填入 __激活码__ 即可完成离线激活。
|
||||
|
||||
|
||||
@ -1,47 +1,60 @@
|
||||
# Navicat Keygen - How to build?
|
||||
# navicat-keygen for windows - How to build?
|
||||
|
||||
[中文版](how-to-build.zh-CN.md)
|
||||
|
||||
## 1. Prerequisites
|
||||
|
||||
1. Please make sure you have installed following libraries:
|
||||
1. Please make sure that you have __Visual Studio 2022__ or the higher. Because this is a VS2022 project.
|
||||
|
||||
* `capstone`
|
||||
* `keystone`
|
||||
* `rapidjson`
|
||||
* `openssl`
|
||||
2. Please make sure you have installed `vcpkg` and the following libraries:
|
||||
|
||||
If you use Ubuntu, you can install them by:
|
||||
* `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
|
||||
# install capstone
|
||||
$ sudo apt-get install libcapstone-dev
|
||||
|
||||
# install keystone
|
||||
$ sudo apt-get install cmake
|
||||
$ git clone https://github.com/keystone-engine/keystone.git
|
||||
$ cd keystone
|
||||
$ mkdir build
|
||||
$ cd build
|
||||
$ ../make-share.sh
|
||||
$ sudo make install
|
||||
$ sudo ldconfig
|
||||
|
||||
# install rapidjson
|
||||
$ sudo apt-get install rapidjson-dev
|
||||
|
||||
# install openssl
|
||||
$ sudo apt-get install libssl-dev
|
||||
$ 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
|
||||
```
|
||||
|
||||
2. Your gcc supports C++17 feature.
|
||||
3. Your `vcpkg` has been integrated into your __Visual Studio__, which means you have run
|
||||
|
||||
```console
|
||||
$ vcpkg integrate install
|
||||
```
|
||||
|
||||
successfully.
|
||||
|
||||
## 2. Build
|
||||
|
||||
```console
|
||||
$ git clone -b linux --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
|
||||
$ cd navicat-keygen
|
||||
$ make all
|
||||
```
|
||||
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.
|
||||
|
||||
|
||||
@ -1,45 +1,54 @@
|
||||
# Navicat Keygen - 如何编译?
|
||||
# navicat-keygen for windows - 如何编译?
|
||||
|
||||
## 1. 前提条件
|
||||
|
||||
1. 请确保你安装了下面几个库:
|
||||
1. 请确保你有 __Visual Studio 2022__ 或者更高版本。因为这是一个VS2022项目。
|
||||
|
||||
* `capstone`
|
||||
* `keystone`
|
||||
* `rapidjson`
|
||||
* `openssl`
|
||||
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
|
||||
# install capstone
|
||||
$ sudo apt-get install libcapstone-dev
|
||||
|
||||
# install keystone
|
||||
$ sudo apt-get install cmake
|
||||
$ git clone https://github.com/keystone-engine/keystone.git
|
||||
$ cd keystone
|
||||
$ mkdir build
|
||||
$ cd build
|
||||
$ ../make-share.sh
|
||||
$ sudo make install
|
||||
$ sudo ldconfig
|
||||
|
||||
# install rapidjson
|
||||
$ sudo apt-get install rapidjson-dev
|
||||
|
||||
# install openssl
|
||||
$ sudo apt-get install libssl-dev
|
||||
$ 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
|
||||
```
|
||||
|
||||
2. 你的gcc支持C++17特性。
|
||||
3. 你的 `vcpkg` 已经和你的 __Visual Studio__ 集成了,即你曾成功运行了:
|
||||
|
||||
```console
|
||||
$ vcpkg integrate install
|
||||
```
|
||||
|
||||
## 2. 编译
|
||||
|
||||
```console
|
||||
$ git clone -b linux --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
|
||||
$ cd navicat-keygen
|
||||
$ make all
|
||||
```
|
||||
1. 在 __Visual Studio__ 打开这个项目。
|
||||
|
||||
2. 选择 `Release` 配置。
|
||||
|
||||
3. 选择 `Win32` 来生成供32位Navicat使用的keygen/patcher。
|
||||
|
||||
或者选择 `x64` 来生成供64位Navicat使用的keygen/patcher。
|
||||
|
||||
4. 选择 __生成 > 生成解决方案__。
|
||||
|
||||
生成完成后,你会在 `bin/` 文件夹下看到编译后的keygen/patcher。
|
||||
|
||||
|
||||
196
doc/how-to-use.md
Normal file
196
doc/how-to-use.md
Normal file
@ -0,0 +1,196 @@
|
||||
# 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.
|
||||
|
||||
194
doc/how-to-use.zh-CN.md
Normal file
194
doc/how-to-use.zh-CN.md
Normal file
@ -0,0 +1,194 @@
|
||||
# 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的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。
|
||||
|
||||
48
navicat-keygen.sln
Normal file
48
navicat-keygen.sln
Normal file
@ -0,0 +1,48 @@
|
||||
|
||||
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
|
||||
@ -1,134 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
@ -1,134 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
@ -1,17 +1,20 @@
|
||||
#include "SerialNumberGenerator.hpp"
|
||||
#include "ExceptionGeneric.hpp"
|
||||
#include "navicat_serial_generator.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 ReadInt(int MinVal, int MaxVal, const char* lpszPrompt, const char* lpszErrorMessage) {
|
||||
static int read_int(int min_val, int max_val, std::wstring_view prompt, std::wstring_view error_msg) {
|
||||
int val;
|
||||
std::string s;
|
||||
while (true) {
|
||||
std::cout << lpszPrompt;
|
||||
if (!std::getline(std::cin, s)) {
|
||||
throw ARL::EOFError(__BASE_FILE__, __LINE__, "Abort.");
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
if (s.empty())
|
||||
@ -19,119 +22,112 @@ namespace nkg {
|
||||
|
||||
try {
|
||||
val = std::stoi(s, nullptr, 0);
|
||||
if (MinVal <= val && val <= MaxVal) {
|
||||
if (min_val <= val && val <= max_val) {
|
||||
return val;
|
||||
} else {
|
||||
throw std::invalid_argument("Out of range.");
|
||||
throw std::invalid_argument(u8"");
|
||||
}
|
||||
} catch (std::invalid_argument&) {
|
||||
std::cout << lpszErrorMessage << std::endl;
|
||||
std::wcout << error_msg << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
static int ReadInt(int MinVal, int MaxVal, int DefaultVal, const char* lpszPrompt, const char* lpszErrorMessage) {
|
||||
static int read_int(int min_val, int max_val, int default_val, std::wstring_view prompt, std::wstring_view error_msg) {
|
||||
int val;
|
||||
std::string s;
|
||||
while (true) {
|
||||
std::cout << lpszPrompt;
|
||||
if (!std::getline(std::cin, s)) {
|
||||
throw ARL::EOFError(__BASE_FILE__, __LINE__, "Abort.");
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
if (s.empty()) {
|
||||
return DefaultVal;
|
||||
return default_val;
|
||||
}
|
||||
|
||||
try {
|
||||
val = std::stoi(s, nullptr, 0);
|
||||
if (MinVal <= val && val <= MaxVal) {
|
||||
if (min_val <= val && val <= max_val) {
|
||||
return val;
|
||||
} else {
|
||||
throw std::invalid_argument("Out of range.");
|
||||
throw std::invalid_argument(u8"");
|
||||
}
|
||||
} catch (std::invalid_argument&) {
|
||||
std::cout << lpszErrorMessage << std::endl;
|
||||
std::wcout << error_msg << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
SerialNumberGenerator CollectInformationNormal() {
|
||||
SerialNumberGenerator Generator;
|
||||
navicat_serial_generator CollectInformationNormal() {
|
||||
navicat_serial_generator sn_generator;
|
||||
|
||||
std::cout << "[*] Select Navicat product:" << std::endl;
|
||||
std::cout << " 0. DataModeler" << std::endl;
|
||||
std::cout << " 1. Premium" << std::endl;
|
||||
std::cout << " 2. MySQL" << std::endl;
|
||||
std::cout << " 3. PostgreSQL" << std::endl;
|
||||
std::cout << " 4. Oracle" << std::endl;
|
||||
std::cout << " 5. SQLServer" << std::endl;
|
||||
std::cout << " 6. SQLite" << std::endl;
|
||||
std::cout << " 7. MariaDB" << std::endl;
|
||||
std::cout << " 8. MongoDB" << std::endl;
|
||||
std::cout << " 9. ReportViewer" << std::endl;
|
||||
std::cout << std::endl;
|
||||
Generator.SetProductSignature(
|
||||
static_cast<NavicatProductType>(ReadInt(0, 9, "(Input index)> ", "Invalid index."))
|
||||
);
|
||||
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;
|
||||
|
||||
std::cout << std::endl;
|
||||
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, 12, "(range: 0 ~ 15, default: 12)> ", "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;
|
||||
|
||||
std::cout << std::endl;
|
||||
return Generator;
|
||||
return sn_generator;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
SerialNumberGenerator CollectInformationAdvanced() {
|
||||
SerialNumberGenerator Generator;
|
||||
navicat_serial_generator CollectInformationAdvanced() {
|
||||
navicat_serial_generator sn_generator;
|
||||
|
||||
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 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 << 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 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 1:" << std::endl;
|
||||
auto s2 = static_cast<uint8_t>(ReadInt(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number."));
|
||||
|
||||
Generator.SetLanguageSignature(s1, s2);
|
||||
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 << "[*] Input major version number:" << std::endl;
|
||||
Generator.SetVersion(
|
||||
static_cast<uint8_t>(ReadInt(0, 15, 12, "(range: 0 ~ 15, default: 12)> ", "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;
|
||||
|
||||
std::cout << std::endl;
|
||||
return Generator;
|
||||
return sn_generator;
|
||||
}
|
||||
}
|
||||
|
||||
#undef NKG_CURRENT_SOURCE_FILE
|
||||
#undef NKG_CURRENT_SOURCE_LINE
|
||||
|
||||
@ -1,70 +1,84 @@
|
||||
#include "Exception.hpp"
|
||||
#include "ExceptionGeneric.hpp"
|
||||
#include "ResourceWrapper.hpp"
|
||||
#include "ResourceTraitsOpenssl.hpp"
|
||||
#include "RSACipher.hpp"
|
||||
#include "Base64.hpp"
|
||||
#include "SerialNumberGenerator.hpp"
|
||||
#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 <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 RSACipher& Cipher, const SerialNumberGenerator& Generator) {
|
||||
std::string utf8username;
|
||||
std::string utf8organization;
|
||||
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;
|
||||
|
||||
std::string b64RequestCode;
|
||||
std::vector<uint8_t> RequestCode;
|
||||
std::string utf8RequestInfo;
|
||||
std::string utf8ResponseInfo;
|
||||
std::vector<uint8_t> ResponseCode;
|
||||
std::string b64ResponseCode;
|
||||
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::cout << "[*] Your name: ";
|
||||
if (!std::getline(std::cin, utf8username)) {
|
||||
throw ARL::EOFError(__BASE_FILE__, __LINE__, "Abort.");
|
||||
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 organization: ";
|
||||
if (!std::getline(std::cin, utf8organization)) {
|
||||
throw ARL::EOFError(__BASE_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 << std::endl;
|
||||
|
||||
std::cout << "[*] Input request code in Base64: (Double press ENTER to end)" << std::endl;
|
||||
std::wcout << std::endl;
|
||||
std::wcout << L"[*] Input request code in Base64: (Input empty line to end)" << std::endl;
|
||||
while (true) {
|
||||
std::string temp;
|
||||
if (!std::getline(std::cin, temp)) {
|
||||
throw ARL::EOFError(__BASE_FILE__, __LINE__, "Abort.");
|
||||
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.");
|
||||
}
|
||||
|
||||
if (temp.empty()) {
|
||||
if (s.empty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
b64RequestCode.append(temp);
|
||||
b64_request_code.append(s);
|
||||
}
|
||||
|
||||
RequestCode = base64_decode(b64RequestCode);
|
||||
if (RequestCode.size() != 256) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Broken request code. %zu", RequestCode.size());
|
||||
if (b64_request_code.empty()) {
|
||||
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Nothing inputs, abort!");
|
||||
}
|
||||
|
||||
utf8RequestInfo.resize((Cipher.Bits() + 7) / 8);
|
||||
Cipher.Decrypt(RequestCode.data(), RequestCode.size(), utf8RequestInfo.data(), RSA_PKCS1_PADDING);
|
||||
while (utf8RequestInfo.back() == '\x00') {
|
||||
utf8RequestInfo.pop_back();
|
||||
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();
|
||||
}
|
||||
|
||||
std::cout << "[*] Request Info:" << std::endl;
|
||||
std::cout << utf8RequestInfo << std::endl;
|
||||
std::cout << std::endl;
|
||||
std::wcout << L"[*] Request Info:" << std::endl;
|
||||
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_request_info) << std::endl;
|
||||
std::wcout << std::endl;
|
||||
|
||||
rapidjson::Document json;
|
||||
rapidjson::Value N_Key;
|
||||
@ -77,78 +91,89 @@ namespace nkg {
|
||||
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
|
||||
|
||||
//
|
||||
// Begin to parse
|
||||
// begin to parse
|
||||
//
|
||||
json.Parse(utf8RequestInfo.c_str());
|
||||
json.Parse(u8_request_info.c_str());
|
||||
|
||||
//
|
||||
// Remove "Platform" info
|
||||
// remove "Platform" info
|
||||
//
|
||||
json.RemoveMember("P");
|
||||
json.RemoveMember(u8"P");
|
||||
|
||||
//
|
||||
// Set "Name" info
|
||||
// set "Name" info
|
||||
//
|
||||
N_Key.SetString("N", 1);
|
||||
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
|
||||
N_Key.SetString(u8"N", 1);
|
||||
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
|
||||
|
||||
//
|
||||
// Set "Organization" info
|
||||
// set "Organization" info
|
||||
//
|
||||
O_Key.SetString("O", 1);
|
||||
O_Value.SetString(utf8organization.c_str(), static_cast<rapidjson::SizeType>(utf8organization.length()));
|
||||
O_Key.SetString(u8"O", 1);
|
||||
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
|
||||
|
||||
//
|
||||
// Set "Time" info
|
||||
// set "Time" info
|
||||
//
|
||||
T_Key.SetString("T", 1);
|
||||
T_Key.SetString(u8"T", 1);
|
||||
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
|
||||
|
||||
//
|
||||
// Add "Name", "Organization" and "Time"
|
||||
// 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 ARL::Exception(__BASE_FILE__, __LINE__, "Response info is too long.");
|
||||
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
|
||||
}
|
||||
|
||||
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
|
||||
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
|
||||
|
||||
std::cout << "[*] Response Info:" << std::endl;
|
||||
std::cout << utf8ResponseInfo << std::endl;
|
||||
std::cout << std::endl;
|
||||
std::wcout << L"[*] Response Info:" << std::endl;
|
||||
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
|
||||
std::wcout << std::endl;
|
||||
|
||||
ResponseCode.resize((Cipher.Bits() + 7) / 8);
|
||||
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
|
||||
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));
|
||||
|
||||
b64ResponseCode = base64_encode(ResponseCode);
|
||||
|
||||
std::cout << "[*] Activation Code:" << std::endl;
|
||||
std::cout << b64ResponseCode << std::endl;
|
||||
std::cout << std::endl;
|
||||
std::wcout << L"[*] Activation Code:" << std::endl;
|
||||
std::wcout << b64_response_code << std::endl;
|
||||
std::wcout << std::endl;
|
||||
}
|
||||
|
||||
void GenerateLicenseBinary(const RSACipher& Cipher, const SerialNumberGenerator& Generator) {
|
||||
ARL::ResourceWrapper LicenseFile{ ARL::ResourceTraits::OpensslBIO{} };
|
||||
void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
|
||||
std::string utf8SerialNumber = sn_generator.serial_number();
|
||||
|
||||
std::string utf8SerialNumber = Generator.GetSerialNumberShort();
|
||||
std::string utf8username;
|
||||
std::string utf8organization;
|
||||
std::wstring username;
|
||||
std::wstring organization;
|
||||
std::string u8_username;
|
||||
std::string u8_organization;
|
||||
|
||||
std::string utf8ResponseInfo;
|
||||
std::vector<uint8_t> ResponseCode;
|
||||
std::string u8_response_info;
|
||||
std::vector<std::uint8_t> response_code;
|
||||
|
||||
std::cout << "[*] Your name: ";
|
||||
if (!std::getline(std::cin, utf8username)) {
|
||||
throw ARL::EOFError(__BASE_FILE__, __LINE__, "Abort.");
|
||||
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 organization: ";
|
||||
if (!std::getline(std::cin, utf8organization)) {
|
||||
throw ARL::EOFError(__BASE_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 << std::endl;
|
||||
|
||||
rapidjson::Document json;
|
||||
rapidjson::Value N_Key;
|
||||
rapidjson::Value N_Value;
|
||||
@ -165,9 +190,9 @@ namespace nkg {
|
||||
K_Key.SetString("K", 1);
|
||||
K_Value.SetString(utf8SerialNumber.c_str(), static_cast<rapidjson::SizeType>(utf8SerialNumber.length()));
|
||||
N_Key.SetString("N", 1);
|
||||
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
|
||||
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
|
||||
O_Key.SetString("O", 1);
|
||||
O_Value.SetString(utf8organization.c_str(), static_cast<rapidjson::SizeType>(utf8organization.length()));
|
||||
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
|
||||
T_Key.SetString("T", 1);
|
||||
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
|
||||
|
||||
@ -176,30 +201,37 @@ namespace nkg {
|
||||
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 ARL::Exception(__BASE_FILE__, __LINE__, "Response info is too long.");
|
||||
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
|
||||
}
|
||||
|
||||
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
|
||||
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;
|
||||
|
||||
std::cout << "[*] Response Info:" << std::endl;
|
||||
std::cout << utf8ResponseInfo << std::endl;
|
||||
std::cout << 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));
|
||||
|
||||
ResponseCode.resize((Cipher.Bits() + 7) / 8);
|
||||
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
|
||||
|
||||
LicenseFile.TakeOver(BIO_new_file("license_file", "w"));
|
||||
if (LicenseFile.IsValid() == false) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "BIO_new_file failed.");
|
||||
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.");
|
||||
}
|
||||
|
||||
if (BIO_write(LicenseFile, ResponseCode.data(), ResponseCode.size()) != ResponseCode.size()) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "BIO_write failed.");
|
||||
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.");
|
||||
}
|
||||
|
||||
std::cout << "[+] license_file has been generated." << std::endl;
|
||||
std::wcout << L"[+] license_file has been generated." << std::endl;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#undef NKG_CURRENT_SOURCE_FILE
|
||||
#undef NKG_CURRENT_SOURCE_LINE
|
||||
|
||||
@ -1,183 +0,0 @@
|
||||
#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(__BASE_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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
#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;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
120
navicat-keygen/base32_rfc4648.cpp
Normal file
120
navicat-keygen/base32_rfc4648.cpp
Normal file
@ -0,0 +1,120 @@
|
||||
#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
|
||||
39
navicat-keygen/base32_rfc4648.hpp
Normal file
39
navicat-keygen/base32_rfc4648.hpp
Normal file
@ -0,0 +1,39 @@
|
||||
#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
|
||||
103
navicat-keygen/base64_rfc4648.cpp
Normal file
103
navicat-keygen/base64_rfc4648.cpp
Normal file
@ -0,0 +1,103 @@
|
||||
#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
|
||||
20
navicat-keygen/base64_rfc4648.hpp
Normal file
20
navicat-keygen/base64_rfc4648.hpp
Normal file
@ -0,0 +1,20 @@
|
||||
#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);
|
||||
};
|
||||
|
||||
}
|
||||
@ -1,112 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "Exception.hpp"
|
||||
#include "ExceptionGeneric.hpp"
|
||||
#include "RSACipher.hpp"
|
||||
#include "SerialNumberGenerator.hpp"
|
||||
|
||||
namespace nkg {
|
||||
using fnCollectInformation = SerialNumberGenerator();
|
||||
using fnGenerateLicense = void(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
|
||||
|
||||
SerialNumberGenerator CollectInformationNormal();
|
||||
SerialNumberGenerator CollectInformationAdvanced();
|
||||
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
|
||||
void GenerateLicenseBinary(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
|
||||
}
|
||||
|
||||
static void Welcome() {
|
||||
puts("**********************************************************");
|
||||
puts("* Navicat Keygen (Linux) by @DoubleLabyrinth *");
|
||||
puts("* Version: 1.0 *");
|
||||
puts("**********************************************************");
|
||||
puts("");
|
||||
}
|
||||
|
||||
static void Help() {
|
||||
puts("Usage:");
|
||||
puts(" navicat-keygen <--bin|--text> [--adv] <RSA-2048 Private Key File>");
|
||||
puts("");
|
||||
puts(" <--bin|--text> Specify \"--bin\" to generate \"license_file\" used by Navicat 11.");
|
||||
puts(" Specify \"--text\" to generate base64-encoded activation code.");
|
||||
puts(" This parameter must be specified.");
|
||||
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 --text ./RegPrivateKey.pem");
|
||||
}
|
||||
|
||||
int main(int argc, const char* argv[]) {
|
||||
Welcome();
|
||||
|
||||
if (argc == 3 || argc == 4) {
|
||||
nkg::fnCollectInformation* lpfnCollectInformation = nullptr;
|
||||
nkg::fnGenerateLicense* lpfnGenerateLicense = nullptr;
|
||||
|
||||
if (strcasecmp(argv[1], "--bin") == 0) {
|
||||
lpfnGenerateLicense = nkg::GenerateLicenseBinary;
|
||||
} else if (strcasecmp(argv[1], "--text") == 0) {
|
||||
lpfnGenerateLicense = nkg::GenerateLicenseText;
|
||||
} else {
|
||||
Help();
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (argc == 4) {
|
||||
if (strcasecmp(argv[2], "--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(__BASE_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();
|
||||
|
||||
lpfnGenerateLicense(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;
|
||||
}
|
||||
}
|
||||
|
||||
187
navicat-keygen/navicat-keygen.vcxproj
Normal file
187
navicat-keygen/navicat-keygen.vcxproj
Normal file
@ -0,0 +1,187 @@
|
||||
<?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>
|
||||
48
navicat-keygen/navicat-keygen.vcxproj.filters
Normal file
48
navicat-keygen/navicat-keygen.vcxproj.filters
Normal file
@ -0,0 +1,48 @@
|
||||
<?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>
|
||||
6
navicat-keygen/navicat-keygen.vcxproj.user
Normal file
6
navicat-keygen/navicat-keygen.vcxproj.user
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ShowAllFiles>true</ShowAllFiles>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
196
navicat-keygen/navicat_serial_generator.cpp
Normal file
196
navicat-keygen/navicat_serial_generator.cpp
Normal file
@ -0,0 +1,196 @@
|
||||
#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
|
||||
82
navicat-keygen/navicat_serial_generator.hpp
Normal file
82
navicat-keygen/navicat_serial_generator.hpp
Normal file
@ -0,0 +1,82 @@
|
||||
#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;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
121
navicat-keygen/wmain.cpp
Normal file
121
navicat-keygen/wmain.cpp
Normal file
@ -0,0 +1,121 @@
|
||||
#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
|
||||
@ -1,95 +0,0 @@
|
||||
#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(__BASE_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(__BASE_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(__BASE_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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,64 +0,0 @@
|
||||
#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;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,406 +0,0 @@
|
||||
#include "Elf64Interpreter.hpp"
|
||||
#include "Exception.hpp"
|
||||
#include "ExceptionGeneric.hpp"
|
||||
#include <memory.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace nkg {
|
||||
|
||||
[[nodiscard]]
|
||||
Elf64Interpreter Elf64Interpreter::Parse(const void* lpImage, size_t cbImage) {
|
||||
Elf64Interpreter Interpreter;
|
||||
|
||||
//
|
||||
// Checking ELF header
|
||||
//
|
||||
|
||||
Interpreter.m_ElfSize = cbImage;
|
||||
Interpreter.m_lpElfHdr = reinterpret_cast<const Elf64_Ehdr*>(lpImage);
|
||||
if (ARL::AddressIsInRangeEx(Interpreter.m_lpElfHdr, sizeof(Elf64_Ehdr), lpImage, cbImage) == false) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Bad ELF file: image is corrupted.");
|
||||
}
|
||||
|
||||
if (memcmp(Interpreter.m_lpElfHdr->e_ident, ELFMAG, SELFMAG) != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: header magic check failure.");
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_ident[EI_CLASS] != ELFCLASS64) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Unsupported ELF file: not ELF64 image.");
|
||||
}
|
||||
|
||||
switch (Interpreter.m_lpElfHdr->e_ident[EI_DATA]) {
|
||||
case ELFDATA2LSB:
|
||||
if (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__) {
|
||||
throw ARL::NotImplementedError(__BASE_FILE__, __LINE__, "Unsupported ELF file: unsupported endian.");
|
||||
}
|
||||
break;
|
||||
case ELFDATA2MSB:
|
||||
if (__BYTE_ORDER__ != __ORDER_BIG_ENDIAN__) {
|
||||
throw ARL::NotImplementedError(__BASE_FILE__, __LINE__, "Unsupported ELF file: unsupported endian.");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Bad ELF file: unknown endian.");
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_ident[EI_VERSION] != EV_CURRENT) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_ident[EI_VERSION] check failure.");
|
||||
}
|
||||
|
||||
// Interpreter.m_lpElfHdr->e_ident[EI_OSABI]
|
||||
// Interpreter.m_lpElfHdr->e_ident[EI_ABIVERSION]
|
||||
|
||||
for (int i = EI_PAD; i < sizeof(Interpreter.m_lpElfHdr->e_ident); ++i) {
|
||||
if (Interpreter.m_lpElfHdr->e_ident[i] != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_ident padding contains non-zero byte(s).");
|
||||
}
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_version != EV_CURRENT) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_version check failure.");
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_ehsize != sizeof(Elf64_Ehdr)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_ehsize check failure.");
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_phoff && Interpreter.m_lpElfHdr->e_phentsize && Interpreter.m_lpElfHdr->e_phnum) {
|
||||
if (Interpreter.m_lpElfHdr->e_phentsize != sizeof(Elf64_Phdr)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_phentsize check failure.");
|
||||
}
|
||||
|
||||
Interpreter.m_lpElfProgramHdr =
|
||||
ARL::AddressOffsetWithCast<Elf64_Phdr*>(lpImage, Interpreter.m_lpElfHdr->e_phoff);
|
||||
|
||||
auto a1 = Interpreter.m_lpElfProgramHdr;
|
||||
auto a2 = Interpreter.m_lpElfProgramHdr + Interpreter.m_lpElfHdr->e_phnum;
|
||||
if (a1 < a2) {
|
||||
if (ARL::AddressIsInRangeEx(a1, a2, lpImage, cbImage) == false) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: image is corrupted.");
|
||||
}
|
||||
} else {
|
||||
throw ARL::OverflowError(__BASE_FILE__, __LINE__, "Bad ELF file: program header table overflowed.");
|
||||
}
|
||||
} else if (Interpreter.m_lpElfHdr->e_phoff == 0 && Interpreter.m_lpElfHdr->e_phentsize == 0 && Interpreter.m_lpElfHdr->e_phnum == 0) {
|
||||
Interpreter.m_lpElfProgramHdr = nullptr;
|
||||
} else {
|
||||
throw ARL::ValueError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_ph* check failure.");
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_shoff && Interpreter.m_lpElfHdr->e_shentsize && Interpreter.m_lpElfHdr->e_shnum) {
|
||||
if (Interpreter.m_lpElfHdr->e_shentsize != sizeof(Elf64_Shdr)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_shentsize check failure.");
|
||||
}
|
||||
|
||||
Interpreter.m_lpElfSectionHdr =
|
||||
ARL::AddressOffsetWithCast<Elf64_Shdr*>(lpImage, Interpreter.m_lpElfHdr->e_shoff);
|
||||
|
||||
auto b1 = Interpreter.m_lpElfSectionHdr;
|
||||
auto b2 = Interpreter.m_lpElfSectionHdr + Interpreter.m_lpElfHdr->e_shnum;
|
||||
if (b1 < b2) {
|
||||
if (ARL::AddressIsInRangeEx(b1, b2, lpImage, cbImage) == false) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: image is corrupted.");
|
||||
}
|
||||
} else {
|
||||
throw ARL::OverflowError(__BASE_FILE__, __LINE__, "Bad ELF file: section header table overflowed.");
|
||||
}
|
||||
} else if (Interpreter.m_lpElfHdr->e_shoff == 0 && Interpreter.m_lpElfHdr->e_shentsize == 0 && Interpreter.m_lpElfHdr->e_shnum == 0) {
|
||||
Interpreter.m_lpElfSectionHdr = nullptr;
|
||||
} else {
|
||||
throw ARL::ValueError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_sh* check failure.");
|
||||
}
|
||||
|
||||
if (Interpreter.m_lpElfHdr->e_shstrndx != SHN_UNDEF) {
|
||||
if (Interpreter.m_lpElfHdr->e_shstrndx >= Interpreter.m_lpElfHdr->e_shnum) {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Ehdr::e_shstrndx is out of range.");
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Checking program header table and section header table
|
||||
//
|
||||
|
||||
if (Interpreter.m_lpElfProgramHdr && Interpreter.m_lpElfSectionHdr) {
|
||||
auto a1 = Interpreter.m_lpElfProgramHdr;
|
||||
auto a2 = Interpreter.m_lpElfProgramHdr + Interpreter.m_lpElfHdr->e_phnum;
|
||||
auto b1 = Interpreter.m_lpElfSectionHdr;
|
||||
auto b2 = Interpreter.m_lpElfSectionHdr + Interpreter.m_lpElfHdr->e_shnum;
|
||||
bool NotOverlapped =
|
||||
(ARL::AddressDelta(a1, b1) < 0 && ARL::AddressDelta(a2, b1) <= 0) ||
|
||||
(ARL::AddressDelta(b1, a1) < 0 && ARL::AddressDelta(b2, a1) <= 0);
|
||||
if (NotOverlapped == false) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: program header table and section header table overlap.");
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Parsing program header
|
||||
//
|
||||
{
|
||||
for (decltype(Elf64_Ehdr::e_phnum) i = 0; i < Interpreter.m_lpElfHdr->e_phnum; ++i) {
|
||||
const auto& proghdr = Interpreter.m_lpElfProgramHdr[i];
|
||||
|
||||
if (ARL::AddressIsInRangeEx(ARL::AddressOffset(lpImage, proghdr.p_offset), proghdr.p_filesz, lpImage, cbImage) == false) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: image is corrupted.");
|
||||
}
|
||||
|
||||
if (auto p_align = proghdr.p_align; p_align) {
|
||||
// align must be a power of 2
|
||||
if ((p_align & (p_align - 1)) != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Phdr[%u]: p_align is not a power of 2.", i);
|
||||
}
|
||||
|
||||
if (proghdr.p_offset % p_align != proghdr.p_vaddr % p_align) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Phdr[%u]: p_offset !== p_vaddr (mod p_align).", i);
|
||||
}
|
||||
}
|
||||
|
||||
// todo
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Parsing section header
|
||||
//
|
||||
{
|
||||
const Elf64_Shdr* sechdr_shstrtab;
|
||||
const char* secview_shstrtab;
|
||||
if (Interpreter.m_lpElfHdr->e_shstrndx != SHN_UNDEF) {
|
||||
sechdr_shstrtab = &Interpreter.m_lpElfSectionHdr[Interpreter.m_lpElfHdr->e_shstrndx];
|
||||
secview_shstrtab = ARL::AddressOffsetWithCast<const char*>(lpImage, sechdr_shstrtab->sh_offset);
|
||||
|
||||
if (sechdr_shstrtab->sh_type != SHT_STRTAB) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: sechdr_shstrtab->sh_type != SHT_STRTAB.");
|
||||
}
|
||||
|
||||
if (ARL::AddressIsInRangeEx(secview_shstrtab, sechdr_shstrtab->sh_size, lpImage, cbImage) == false) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: image is corrupted.");
|
||||
}
|
||||
} else {
|
||||
sechdr_shstrtab = nullptr;
|
||||
secview_shstrtab = nullptr;
|
||||
}
|
||||
|
||||
for (decltype(Elf64_Ehdr::e_shnum) i = 0; i < Interpreter.m_lpElfHdr->e_shnum; ++i) {
|
||||
auto& sechdr = Interpreter.m_lpElfSectionHdr[i];
|
||||
|
||||
//
|
||||
// checking sh_type
|
||||
//
|
||||
switch (sechdr.sh_type) {
|
||||
case SHT_SYMTAB:
|
||||
if (sechdr.sh_entsize != sizeof(Elf64_Sym)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_entsize != sizeof(Elf64_Dyn).", i);
|
||||
}
|
||||
break;
|
||||
case SHT_RELA:
|
||||
if (sechdr.sh_entsize != sizeof(Elf64_Rela)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_entsize != sizeof(Elf64_Rela).", i);
|
||||
}
|
||||
break;
|
||||
case SHT_DYNAMIC:
|
||||
if (sechdr.sh_entsize != sizeof(Elf64_Dyn)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_entsize != sizeof(Elf64_Dyn).", i);
|
||||
}
|
||||
break;
|
||||
case SHT_REL:
|
||||
if (sechdr.sh_entsize != sizeof(Elf64_Rel)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_entsize != sizeof(Elf64_Rel).", i);
|
||||
}
|
||||
break;
|
||||
case SHT_DYNSYM:
|
||||
if (sechdr.sh_entsize != sizeof(Elf64_Sym)) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_entsize != sizeof(Elf64_Dyn).", i);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
//
|
||||
// checking sh_link and sh_info
|
||||
//
|
||||
switch (sechdr.sh_type) {
|
||||
case SHT_DYNAMIC:
|
||||
if (sechdr.sh_link == SHN_UNDEF) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link == SHN_UNDEF.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_link < Interpreter.m_lpElfHdr->e_shnum) {
|
||||
if (Interpreter.m_lpElfSectionHdr[sechdr.sh_link].sh_type != SHT_STRTAB) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: incorrect value of sh_link.", i);
|
||||
}
|
||||
} else {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link is out of range.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_info != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_info != 0.", i);
|
||||
}
|
||||
break;
|
||||
case SHT_HASH:
|
||||
if (sechdr.sh_link == SHN_UNDEF) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link == SHN_UNDEF.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_link < Interpreter.m_lpElfHdr->e_shnum) {
|
||||
if (Interpreter.m_lpElfSectionHdr[sechdr.sh_link].sh_type != SHT_SYMTAB && Interpreter.m_lpElfSectionHdr[sechdr.sh_link].sh_type != SHT_DYNSYM) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: incorrect value of sh_link.", i);
|
||||
}
|
||||
} else {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link is out of range.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_info != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_info != 0.", i);
|
||||
}
|
||||
break;
|
||||
case SHT_RELA:
|
||||
case SHT_REL:
|
||||
if (sechdr.sh_link == SHN_UNDEF) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link == SHN_UNDEF.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_link < Interpreter.m_lpElfHdr->e_shnum) {
|
||||
if (Interpreter.m_lpElfSectionHdr[sechdr.sh_link].sh_type != SHT_SYMTAB && Interpreter.m_lpElfSectionHdr[sechdr.sh_link].sh_type != SHT_DYNSYM) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: incorrect value of sh_link.", i);
|
||||
}
|
||||
} else {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link is out of range.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_flags & SHF_INFO_LINK) {
|
||||
if (sechdr.sh_info == SHN_UNDEF) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_info == SHN_UNDEF.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_info >= Interpreter.m_lpElfHdr->e_shnum) {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_info is out of range.", i);
|
||||
}
|
||||
} else {
|
||||
if (sechdr.sh_info != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_info != 0.", i);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case SHT_SYMTAB:
|
||||
case SHT_DYNSYM:
|
||||
if (sechdr.sh_link == SHN_UNDEF) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link == SHN_UNDEF.", i);
|
||||
}
|
||||
|
||||
if (sechdr.sh_link < Interpreter.m_lpElfHdr->e_shnum) {
|
||||
if (Interpreter.m_lpElfSectionHdr[sechdr.sh_link].sh_type != SHT_STRTAB) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: incorrect value of sh_link.", i);
|
||||
}
|
||||
} else {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_link is out of range.", i);
|
||||
}
|
||||
|
||||
// todo: check sh_info
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (sechdr.sh_type != SHT_NOBITS) {
|
||||
if (ARL::AddressIsInRangeEx(ARL::AddressOffset(lpImage, sechdr.sh_offset), sechdr.sh_size, lpImage, cbImage) == false) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: image is corrupted.", i);
|
||||
}
|
||||
}
|
||||
|
||||
if (sechdr.sh_addr) {
|
||||
if (sechdr.sh_addralign && sechdr.sh_addr % sechdr.sh_addralign != 0) {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Bad ELF file: Elf64_Shdr[%u]: sh_addr is not aligned to sh_addralign.", i);
|
||||
}
|
||||
|
||||
Interpreter.m_SectionRvaMap.emplace(
|
||||
std::make_pair(
|
||||
sechdr.sh_addr,
|
||||
Interpreter.m_lpElfSectionHdr + i
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (sechdr.sh_type != SHT_NOBITS) {
|
||||
Interpreter.m_SectionOffsetMap.emplace(
|
||||
std::make_pair(
|
||||
sechdr.sh_offset,
|
||||
Interpreter.m_lpElfSectionHdr + i
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (secview_shstrtab) {
|
||||
Interpreter.m_SectionNameMap.emplace(
|
||||
std::make_pair(
|
||||
std::string(ARL::AddressOffset(secview_shstrtab, sechdr.sh_name)),
|
||||
Interpreter.m_lpElfSectionHdr + i
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// todo
|
||||
}
|
||||
}
|
||||
|
||||
return Interpreter;
|
||||
}
|
||||
|
||||
size_t Elf64Interpreter::ElfSize() const noexcept {
|
||||
return m_ElfSize;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Phdr* Elf64Interpreter::ElfProgramHeader(size_t Idx) const {
|
||||
if (Idx < m_lpElfHdr->e_phnum) {
|
||||
return m_lpElfProgramHdr + Idx;
|
||||
} else {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Elf64Interpreter: Idx is out of range.");
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Shdr* Elf64Interpreter::ElfSectionHeader(size_t Idx) const {
|
||||
if (Idx < m_lpElfHdr->e_shnum) {
|
||||
return m_lpElfSectionHdr + Idx;
|
||||
} else {
|
||||
throw ARL::IndexError(__BASE_FILE__, __LINE__, "Elf64Interpreter: Idx is out of range.");
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Shdr* Elf64Interpreter::ElfSectionHeader(std::string_view SectionName) const {
|
||||
auto it = m_SectionNameMap.find(std::string(SectionName));
|
||||
if (it != m_SectionNameMap.end()) {
|
||||
return it->second;
|
||||
} else {
|
||||
throw ARL::KeyError(__BASE_FILE__, __LINE__, "Elf64Interpreter: section %s is not found.", SectionName.data());
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
Elf64_Off Elf64Interpreter::ConvertRvaToOffset(Elf64_Addr Rva) const {
|
||||
auto it = m_SectionRvaMap.upper_bound(Rva);
|
||||
if (it != m_SectionRvaMap.begin()) {
|
||||
--it;
|
||||
if (it->second->sh_addr <= Rva && Rva < it->second->sh_addr + it->second->sh_size) {
|
||||
return it->second->sh_offset + (Rva - it->second->sh_addr);
|
||||
}
|
||||
}
|
||||
throw ARL::KeyError(__BASE_FILE__, __LINE__, "Elf64Interpreter: Invalid RVA.");
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
Elf64_Addr Elf64Interpreter::ConvertOffsetToRva(Elf64_Off Offset) const {
|
||||
auto it = m_SectionOffsetMap.upper_bound(Offset);
|
||||
if (it != m_SectionOffsetMap.begin()) {
|
||||
--it;
|
||||
if (it->second->sh_offset <= Offset && Offset < it->second->sh_offset + it->second->sh_size) {
|
||||
return it->second->sh_addr + (Offset - it->second->sh_offset);
|
||||
}
|
||||
}
|
||||
throw ARL::KeyError(__BASE_FILE__, __LINE__, "Elf64Interpreter: Invalid Offset.");
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,193 +0,0 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#ifdef __APPLE__
|
||||
#include <libelf/libelf.h>
|
||||
#else
|
||||
#include <elf.h>
|
||||
#endif
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include "MemoryAccess.hpp"
|
||||
|
||||
namespace nkg {
|
||||
|
||||
class Elf64Interpreter {
|
||||
private:
|
||||
|
||||
size_t m_ElfSize;
|
||||
const Elf64_Ehdr* m_lpElfHdr;
|
||||
const Elf64_Phdr* m_lpElfProgramHdr;
|
||||
const Elf64_Shdr* m_lpElfSectionHdr;
|
||||
std::map<Elf64_Addr, const Elf64_Shdr*> m_SectionRvaMap;
|
||||
std::map<Elf64_Off, const Elf64_Shdr*> m_SectionOffsetMap;
|
||||
std::map<std::string, const Elf64_Shdr*> m_SectionNameMap;
|
||||
|
||||
protected:
|
||||
|
||||
Elf64Interpreter() :
|
||||
m_ElfSize(0),
|
||||
m_lpElfHdr(nullptr),
|
||||
m_lpElfProgramHdr(nullptr),
|
||||
m_lpElfSectionHdr(nullptr) {}
|
||||
|
||||
public:
|
||||
|
||||
[[nodiscard]]
|
||||
static Elf64Interpreter Parse(const void* lpImage, size_t cbImage);
|
||||
|
||||
size_t ElfSize() const noexcept;
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ElfBase() const noexcept {
|
||||
static_assert(std::is_pointer_v<__ReturnType>);
|
||||
return reinterpret_cast<__ReturnType>(const_cast<Elf64_Ehdr*>(m_lpElfHdr));
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ElfOffset(Elf64_Off Offset) const noexcept {
|
||||
static_assert(std::is_pointer_v<__ReturnType>);
|
||||
return ARL::AddressOffsetWithCast<__ReturnType>(m_lpElfHdr, Offset);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Ehdr* ElfHeader() const noexcept {
|
||||
return m_lpElfHdr;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
size_t NumberOfElfProgramHeaders() const noexcept {
|
||||
return m_lpElfHdr->e_phnum;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Phdr* ElfProgramHeader(size_t Idx) const;
|
||||
|
||||
[[nodiscard]]
|
||||
size_t NumberOfElfSectionHeaders() const noexcept {
|
||||
return m_lpElfHdr->e_shnum;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Shdr* ElfSectionHeader(size_t Idx) const;
|
||||
|
||||
[[nodiscard]]
|
||||
const Elf64_Shdr* ElfSectionHeader(std::string_view SectionName) const;
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ElfSectionView(const Elf64_Shdr* SectionHeader, Elf64_Off Offset = 0) const noexcept {
|
||||
return ElfOffset<__ReturnType>(SectionHeader->sh_offset + Offset);
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ElfSectionView(size_t Idx, Elf64_Off Offset = 0) const noexcept {
|
||||
return ElfOffset<__ReturnType>(ElfSectionHeader(Idx)->sh_offset + Offset);
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ElfSectionView(std::string_view SectionName, Elf64_Off Offset = 0) const noexcept {
|
||||
return ElfOffset<__ReturnType>(ElfSectionHeader(SectionName)->sh_offset + Offset);
|
||||
}
|
||||
|
||||
//
|
||||
// Other
|
||||
//
|
||||
|
||||
template<typename __ReturnType = void*, typename __HintType>
|
||||
__ReturnType SearchElfSectionView(const Elf64_Shdr* SectionHeader, __HintType&& Hint) const noexcept {
|
||||
auto secview = ElfSectionView<const uint8_t*>(SectionHeader);
|
||||
for (decltype(Elf64_Shdr::sh_size) i = 0; i < SectionHeader->sh_size; ++i) {
|
||||
if (Hint(secview, i, SectionHeader->sh_size)) {
|
||||
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(secview + i));
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*, typename __HintType>
|
||||
__ReturnType SearchElfSectionView(const Elf64_Shdr* SectionHeader, Elf64_Off Offset, __HintType&& Hint) const noexcept {
|
||||
auto secview = ElfSectionView<const uint8_t*>(SectionHeader);
|
||||
for (decltype(Elf64_Shdr::sh_size) i = Offset; i < SectionHeader->sh_size; ++i) {
|
||||
if (Hint(secview, i, SectionHeader->sh_size)) {
|
||||
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(secview + i));
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*, typename __HintType>
|
||||
__ReturnType SearchElfSectionView(size_t Idx, __HintType&& Hint) const noexcept {
|
||||
return SearchElfSectionView<__ReturnType>(ElfSectionHeader(Idx), std::forward<__HintType>(Hint));
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*, typename __HintType>
|
||||
__ReturnType SearchElfSectionView(size_t Idx, Elf64_Off Offset, __HintType&& Hint) const noexcept {
|
||||
return SearchElfSectionView<__ReturnType>(ElfSectionHeader(Idx), Offset, std::forward<__HintType>(Hint));
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*, typename __HintType>
|
||||
__ReturnType SearchElfSectionView(std::string_view SectionName, __HintType&& Hint) const noexcept {
|
||||
return SearchElfSectionView<__ReturnType>(ElfSectionHeader(SectionName), std::forward<__HintType>(Hint));
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*, typename __HintType>
|
||||
__ReturnType SearchElfSectionView(std::string_view SectionName, Elf64_Off Offset, __HintType&& Hint) const noexcept {
|
||||
return SearchElfSectionView<__ReturnType>(ElfSectionHeader(SectionName), Offset, std::forward<__HintType>(Hint));
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const auto& ElfSectionRvaMap() const noexcept {
|
||||
return m_SectionRvaMap;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const auto& ElfSectionOffsetMap() const noexcept {
|
||||
return m_SectionOffsetMap;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const auto& ElfSectionNameMap() const noexcept {
|
||||
return m_SectionNameMap;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
Elf64_Off ConvertRvaToOffset(Elf64_Addr Rva) const;
|
||||
|
||||
template<typename __PtrType>
|
||||
[[nodiscard]]
|
||||
Elf64_Off ConvertPtrToOffset(__PtrType Ptr) const {
|
||||
return ARL::AddressDelta(Ptr, m_lpElfHdr);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
Elf64_Addr ConvertOffsetToRva(Elf64_Off Offset) const;
|
||||
|
||||
template<typename __PtrType>
|
||||
[[nodiscard]]
|
||||
Elf64_Addr ConvertPtrToRva(__PtrType Ptr) const {
|
||||
return ConvertOffsetToRva(ConvertPtrToOffset(Ptr));
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ConvertRvaToPtr(Elf64_Addr Rva) const {
|
||||
return ConvertOffsetToPtr<__ReturnType>(ConvertRvaToOffset(Rva));
|
||||
}
|
||||
|
||||
template<typename __ReturnType = void*>
|
||||
[[nodiscard]]
|
||||
__ReturnType ConvertOffsetToPtr(Elf64_Off Offset) const {
|
||||
return ElfOffset<__ReturnType>(Offset);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,39 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,39 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
#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(__BASE_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(__BASE_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(__BASE_FILE__, __LINE__, err, "ks_option failed.");
|
||||
}
|
||||
}
|
||||
|
||||
KeystoneAssembler KeystoneEngine::CreateAssembler() const {
|
||||
return KeystoneAssembler(*this);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
#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;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,151 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,173 +0,0 @@
|
||||
#include "Misc.hpp"
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#include <setjmp.h>
|
||||
#include <filesystem>
|
||||
#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) {
|
||||
std::error_code ec;
|
||||
if (std::filesystem::exists(szPath, ec)) {
|
||||
return true;
|
||||
} else {
|
||||
if (ec) {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, ec.value(), "std::filesystem::exists failed.");
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
bool FsIsFile(std::string_view szPath) {
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_regular_file(szPath, ec)) {
|
||||
return true;
|
||||
} else {
|
||||
if (ec) {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, ec.value(), "std::filesystem::is_regular_file failed.");
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
bool FsIsDirectory(std::string_view szPath) {
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_directory(szPath, ec)) {
|
||||
return true;
|
||||
} else {
|
||||
if (ec) {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, ec.value(), "std::filesystem::is_directory failed.");
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void FsCopyFile(std::string_view szSourcePath, std::string_view szDestinationPath) {
|
||||
std::error_code ec;
|
||||
if (std::filesystem::copy_file(szSourcePath, szDestinationPath, ec) == false) {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, ec.value(), "std::filesystem::copy_file failed.");
|
||||
}
|
||||
}
|
||||
|
||||
void FsDeleteFile(std::string_view szPath) {
|
||||
std::error_code ec;
|
||||
if (std::filesystem::remove(szPath, ec) == false) {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, ec.value(), "std::filesystem::remove failed.");
|
||||
}
|
||||
}
|
||||
|
||||
std::string FsCurrentWorkingDirectory() {
|
||||
std::error_code ec;
|
||||
std::string path = std::filesystem::current_path(ec);
|
||||
if (ec) {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, ec.value(), "std::filesystem::current_path failed.");
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,35 +0,0 @@
|
||||
#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);
|
||||
|
||||
void FsCopyFile(std::string_view szSourcePath, std::string_view szDestinationPath);
|
||||
|
||||
void FsDeleteFile(std::string_view szPath);
|
||||
|
||||
std::string FsCurrentWorkingDirectory();
|
||||
|
||||
}
|
||||
|
||||
@ -1,61 +0,0 @@
|
||||
#include "PatchSolutions.hpp"
|
||||
|
||||
namespace nkg {
|
||||
|
||||
void PatchSolution::SearchFreeSpace(std::map<Elf64_Off, Elf64_Xword>& SpaceMap, const Elf64Interpreter& Image) {
|
||||
static auto lpfnUpdateMap = [](std::map<Elf64_Off, Elf64_Xword>& SpaceMap, Elf64_Off offset, Elf64_Xword size) {
|
||||
auto start = offset;
|
||||
auto end = start + size;
|
||||
while (size) {
|
||||
auto space = SpaceMap.upper_bound(offset);
|
||||
auto space_start = space->first;
|
||||
auto space_end = space_start + space->second;
|
||||
if (space != SpaceMap.end() && space_start < end) { // implicit condition: start < space_start
|
||||
if (space_end <= end) {
|
||||
SpaceMap.erase(space);
|
||||
} else {
|
||||
auto node = SpaceMap.extract(space);
|
||||
node.key() = end;
|
||||
SpaceMap.insert(std::move(node));
|
||||
}
|
||||
} else if (space != SpaceMap.begin()) {
|
||||
--space;
|
||||
space_start = space->first; // space_start <= start
|
||||
space_end = space_start + space->second;
|
||||
if (start < space_end) {
|
||||
space->second = start - space_start;
|
||||
if (space->second == 0) {
|
||||
SpaceMap.erase(space);
|
||||
}
|
||||
if (end < space_end) {
|
||||
SpaceMap.emplace(end, space_end - end);
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
lpfnUpdateMap(SpaceMap, 0, sizeof(Elf64_Ehdr));
|
||||
lpfnUpdateMap(SpaceMap, Image.ElfHeader()->e_phoff, Image.ElfHeader()->e_phentsize * Image.ElfHeader()->e_phnum);
|
||||
lpfnUpdateMap(SpaceMap, Image.ElfHeader()->e_shoff, Image.ElfHeader()->e_shentsize * Image.ElfHeader()->e_shnum);
|
||||
for (size_t i = 0; i < Image.NumberOfElfProgramHeaders(); ++i) {
|
||||
auto seg_hdr = Image.ElfProgramHeader(i);
|
||||
if (seg_hdr->p_type != PT_NULL) {
|
||||
lpfnUpdateMap(SpaceMap, seg_hdr->p_offset, seg_hdr->p_filesz);
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < Image.NumberOfElfSectionHeaders(); ++i) {
|
||||
auto sec_hdr = Image.ElfSectionHeader(i);
|
||||
if (sec_hdr->sh_type != SHT_NULL && sec_hdr->sh_type != SHT_NOBITS) {
|
||||
lpfnUpdateMap(SpaceMap, sec_hdr->sh_offset, sec_hdr->sh_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,263 +0,0 @@
|
||||
#include "PatchSolutions.hpp"
|
||||
#include "ExceptionGeneric.hpp"
|
||||
#include "Misc.hpp"
|
||||
#include <string.h>
|
||||
|
||||
namespace nkg {
|
||||
|
||||
PatchSolution0::PatchSolution0(const Elf64Interpreter& Image) :
|
||||
m_Image(Image),
|
||||
m_DisassemblyEngine(CS_ARCH_X86, CS_MODE_64),
|
||||
m_AssemblyEngine(KS_ARCH_X86, KS_MODE_64),
|
||||
m_RefSegment(nullptr)
|
||||
{
|
||||
m_DisassemblyEngine.Option(CS_OPT_DETAIL, CS_OPT_ON);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
bool PatchSolution0::FindPatchOffset() noexcept {
|
||||
try {
|
||||
const Elf64_Phdr* RefSegment = nullptr;
|
||||
std::optional<Elf64_Off> PatchMarkOffset;
|
||||
std::optional<Elf64_Addr> PatchMarkRva;
|
||||
std::optional<Elf64_Addr> MachineCodeRva;
|
||||
std::optional<size_t> MachineCodeSize;
|
||||
std::vector<uint8_t> MachineCodeNew;
|
||||
|
||||
if (m_Image.ElfHeader()->e_machine != EM_X86_64) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Not amd64 platform.");
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < m_Image.NumberOfElfProgramHeaders(); ++i) {
|
||||
auto seg_hdr = m_Image.ElfProgramHeader(i);
|
||||
if (seg_hdr->p_type != PT_NULL && seg_hdr->p_filesz >= sizeof(PatchMarkType)) {
|
||||
auto lpMark = m_Image.ElfOffset<const PatchMarkType*>(seg_hdr->p_offset + seg_hdr->p_filesz - sizeof(PatchMarkType));
|
||||
if (lpMark->Starter == PatchMarkStarter || lpMark->Terminator == PatchMarkTerminator) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Already patched.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::map<Elf64_Off, Elf64_Xword> SpaceMap{ { 0, m_Image.ElfSize() } };
|
||||
|
||||
SearchFreeSpace(SpaceMap, m_Image);
|
||||
|
||||
for (const auto& space : SpaceMap) {
|
||||
bool found = false;
|
||||
auto offset = space.first;
|
||||
auto size = space.second;
|
||||
|
||||
if (size >= sizeof(PatchMarkType)) {
|
||||
for (size_t i = 0; i < m_Image.NumberOfElfProgramHeaders(); ++i) {
|
||||
auto seg_hdr = m_Image.ElfProgramHeader(i);
|
||||
if (seg_hdr->p_type == PT_LOAD && seg_hdr->p_offset + seg_hdr->p_filesz == offset) {
|
||||
RefSegment = seg_hdr;
|
||||
PatchMarkOffset = offset;
|
||||
PatchMarkRva = m_Image.ConvertOffsetToRva(offset - 1) + 1;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
auto Disassembler = m_DisassemblyEngine.CreateDisassembler();
|
||||
auto Assembler = m_AssemblyEngine.CreateAssembler();
|
||||
|
||||
auto sec_hdr_text = m_Image.ElfSectionHeader(".text");
|
||||
auto sec_view_text = m_Image.ElfSectionView(sec_hdr_text);
|
||||
auto lpMachineCode = m_Image.SearchElfSectionView(sec_hdr_text, [](const void* base, size_t i, size_t size) {
|
||||
auto p = reinterpret_cast<const uint8_t*>(base) + i;
|
||||
return i + 16 <= size &&
|
||||
p[1] == 0x0f && p[2] == 0xb6 && // movzx xxx, yyy
|
||||
p[6] == 0x8b && // mov xxx, yyy
|
||||
p[10] == 0x8b && // mov xxx, yyy
|
||||
p[13] == 0x85 && // test xxx, yyy
|
||||
p[15] == 0x79; // jns xxx
|
||||
}
|
||||
);
|
||||
auto cbMachineCode = static_cast<size_t>(sec_hdr_text->sh_size - ARL::AddressDelta(lpMachineCode, sec_view_text));
|
||||
MachineCodeRva = m_Image.ConvertPtrToRva(lpMachineCode);
|
||||
|
||||
Disassembler.SetContext({ lpMachineCode, cbMachineCode, MachineCodeRva.value() });
|
||||
|
||||
int char_reg;
|
||||
int lpsz_reg;
|
||||
if (Disassembler.Next() && strcasecmp(Disassembler.GetInstruction()->mnemonic, "movzx") == 0) {
|
||||
auto lpInsn = Disassembler.GetInstruction();
|
||||
if (lpInsn->detail->x86.operands[0].type == X86_OP_REG) {
|
||||
char_reg = lpInsn->detail->x86.operands[0].reg;
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
|
||||
if (Disassembler.Next() && strcasecmp(Disassembler.GetInstruction()->mnemonic, "mov") == 0) {
|
||||
auto lpInsn = Disassembler.GetInstruction();
|
||||
if (lpInsn->detail->x86.operands[0].type == X86_OP_REG) {
|
||||
lpsz_reg = lpInsn->detail->x86.operands[0].reg;
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
|
||||
if (Disassembler.Next() && Disassembler.Next() && Disassembler.Next()) {
|
||||
MachineCodeSize = static_cast<size_t>(Disassembler.GetContext().Address - MachineCodeRva.value());
|
||||
MachineCodeNew = Assembler.GenerateMachineCode(
|
||||
[this, char_reg, lpsz_reg, &PatchMarkRva]() -> std::string {
|
||||
const char asm_template[] =
|
||||
"xor %1$s, %1$s;"
|
||||
"lea %2$s, byte ptr [0x%3$.16lx];";
|
||||
std::string asm_string;
|
||||
int l;
|
||||
|
||||
l = snprintf(nullptr, 0,
|
||||
asm_template,
|
||||
this->m_DisassemblyEngine.GetRegisterName(char_reg),
|
||||
this->m_DisassemblyEngine.GetRegisterName(lpsz_reg),
|
||||
PatchMarkRva.value() + offsetof(PatchMarkType, Data)
|
||||
);
|
||||
if (l < 0) {
|
||||
std::terminate();
|
||||
}
|
||||
|
||||
asm_string.resize(l + 1);
|
||||
|
||||
l = snprintf(asm_string.data(), asm_string.length(),
|
||||
asm_template,
|
||||
this->m_DisassemblyEngine.GetRegisterName(char_reg),
|
||||
this->m_DisassemblyEngine.GetRegisterName(lpsz_reg),
|
||||
PatchMarkRva.value() + offsetof(PatchMarkType, Data)
|
||||
);
|
||||
if (l < 0) {
|
||||
std::terminate();
|
||||
}
|
||||
|
||||
while (asm_string.back() == '\x00') {
|
||||
asm_string.pop_back();
|
||||
}
|
||||
|
||||
return asm_string;
|
||||
}().c_str(),
|
||||
MachineCodeRva.value()
|
||||
);
|
||||
|
||||
if (MachineCodeNew.size() <= MachineCodeSize.value()) {
|
||||
MachineCodeNew.insert(MachineCodeNew.end(), MachineCodeSize.value() - MachineCodeNew.size(), '\x90'); // \x90 -> nop
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
}
|
||||
|
||||
if (RefSegment && PatchMarkOffset.has_value() && MachineCodeRva.has_value() && MachineCodeSize.has_value()) {
|
||||
m_RefSegment = RefSegment;
|
||||
m_PatchMarkOffset = PatchMarkOffset;
|
||||
m_MachineCodeRva = MachineCodeRva;
|
||||
m_MachineCodeSize = MachineCodeSize;
|
||||
m_MachineCodeNew = std::move(MachineCodeNew);
|
||||
|
||||
printf("[+] PatchSolution0 ...... Ready to apply\n");
|
||||
printf(" RefSegment = %zu\n", m_RefSegment - m_Image.ElfProgramHeader(0));
|
||||
printf(" MachineCodeRva = 0x%.16lx\n", m_MachineCodeRva.value());
|
||||
printf(" PatchMarkOffset = +0x%.16lx\n", PatchMarkOffset.value());
|
||||
} else {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Not found.");
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (ARL::Exception& e) {
|
||||
printf("[-] PatchSolution0 ...... Omitted\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
bool PatchSolution0::CheckKey(const RSACipher& Cipher) const noexcept {
|
||||
return Cipher.Bits() == 2048;
|
||||
}
|
||||
|
||||
void PatchSolution0::MakePatch(const RSACipher& Cipher) const {
|
||||
if (m_RefSegment && m_PatchMarkOffset.has_value() && m_MachineCodeRva.has_value() && m_MachineCodeSize.has_value()) {
|
||||
if (m_MachineCodeSize.value() == m_MachineCodeNew.size()) {
|
||||
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
|
||||
|
||||
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
|
||||
szPublicKey.erase(pos, strlen("-----BEGIN PUBLIC KEY-----"));
|
||||
}
|
||||
|
||||
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
|
||||
szPublicKey.erase(pos, strlen("-----END PUBLIC KEY-----"));
|
||||
}
|
||||
|
||||
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
|
||||
szPublicKey.erase(pos, strlen("\n"));
|
||||
}
|
||||
|
||||
auto lpMark = m_Image.ElfOffset<PatchMarkType*>(m_PatchMarkOffset.value());
|
||||
|
||||
puts("*******************************************************");
|
||||
puts("* PatchSolution0 *");
|
||||
puts("*******************************************************");
|
||||
|
||||
if (lpMark->Starter != PatchMarkStarter || lpMark->Terminator != PatchMarkTerminator) {
|
||||
auto RefSegment = const_cast<Elf64_Phdr*>(m_RefSegment);
|
||||
|
||||
printf("[*] Previous:\n");
|
||||
Misc::PrintMemory(RefSegment, sizeof(Elf64_Phdr), m_Image.ElfBase());
|
||||
RefSegment->p_filesz += sizeof(PatchMarkType);
|
||||
RefSegment->p_memsz += sizeof(PatchMarkType);
|
||||
printf("[*] After:\n");
|
||||
Misc::PrintMemory(RefSegment, sizeof(Elf64_Phdr), m_Image.ElfBase());
|
||||
printf("\n");
|
||||
|
||||
printf("[*] Previous:\n");
|
||||
Misc::PrintMemory(lpMark, sizeof(PatchMarkType), m_Image.ElfBase());
|
||||
lpMark->Starter = PatchMarkStarter;
|
||||
memcpy(lpMark->Data, szPublicKey.data(), std::min(szPublicKey.size(), sizeof(lpMark->Data)));
|
||||
lpMark->Terminator = PatchMarkTerminator;
|
||||
printf("[*] After:\n");
|
||||
Misc::PrintMemory(lpMark, sizeof(PatchMarkType), m_Image.ElfBase());
|
||||
printf("\n");
|
||||
} else {
|
||||
if (strncmp(reinterpret_cast<char*>(lpMark->Data), szPublicKey.data(), sizeof(lpMark->Data)) != 0) {
|
||||
printf("[*] Previous:\n");
|
||||
Misc::PrintMemory(lpMark, sizeof(PatchMarkType), m_Image.ElfBase());
|
||||
memcpy(lpMark->Data, szPublicKey.data(), std::min(szPublicKey.size(), sizeof(lpMark->Data)));
|
||||
printf("[*] After:\n");
|
||||
Misc::PrintMemory(lpMark, sizeof(PatchMarkType), m_Image.ElfBase());
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
auto lpMachineCode = m_Image.ConvertRvaToPtr(m_MachineCodeRva.value());
|
||||
printf("[*] Previous:\n");
|
||||
Misc::PrintMemory(lpMachineCode, m_MachineCodeSize.value(), m_Image.ElfBase());
|
||||
memcpy(lpMachineCode, m_MachineCodeNew.data(), m_MachineCodeSize.value());
|
||||
printf("[*] After:\n");
|
||||
Misc::PrintMemory(lpMachineCode, m_MachineCodeSize.value(), m_Image.ElfBase());
|
||||
printf("\n");
|
||||
}
|
||||
} else {
|
||||
throw ARL::AssertionError(__BASE_FILE__, __LINE__, "Something unexpected happened.");
|
||||
}
|
||||
} else {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Not ready yet.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,65 +0,0 @@
|
||||
#pragma once
|
||||
#include "RSACipher.hpp"
|
||||
#include "Elf64Interpreter.hpp"
|
||||
#include "CapstoneDisassembler.hpp"
|
||||
#include "KeystoneAssembler.hpp"
|
||||
#include <optional>
|
||||
|
||||
namespace nkg {
|
||||
|
||||
class PatchSolution {
|
||||
protected:
|
||||
|
||||
struct PatchMarkType {
|
||||
uint32_t Starter;
|
||||
uint8_t Data[0x188];
|
||||
uint32_t Terminator;
|
||||
};
|
||||
|
||||
static constexpr uint32_t PatchMarkStarter = 0xdeadbeef;
|
||||
static constexpr uint32_t PatchMarkTerminator = 0xbeefdead;
|
||||
|
||||
void SearchFreeSpace(std::map<Elf64_Off, Elf64_Xword>& SpaceMap, const Elf64Interpreter& Image);
|
||||
|
||||
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:
|
||||
|
||||
const Elf64Interpreter& m_Image;
|
||||
CapstoneEngine m_DisassemblyEngine;
|
||||
KeystoneEngine m_AssemblyEngine;
|
||||
|
||||
const Elf64_Phdr* m_RefSegment;
|
||||
std::optional<Elf64_Off> m_PatchMarkOffset;
|
||||
std::optional<Elf64_Addr> m_MachineCodeRva;
|
||||
std::optional<size_t> m_MachineCodeSize;
|
||||
std::vector<uint8_t> m_MachineCodeNew;
|
||||
|
||||
public:
|
||||
|
||||
PatchSolution0(const Elf64Interpreter& 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;
|
||||
|
||||
virtual void MakePatch(const RSACipher& Cipher) const override;
|
||||
};
|
||||
}
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
#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(__BASE_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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,41 +0,0 @@
|
||||
#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(__BASE_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);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@ -1,38 +0,0 @@
|
||||
#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(__BASE_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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
200
navicat-patcher/amd64_emulator.cpp
Normal file
200
navicat-patcher/amd64_emulator.cpp
Normal file
@ -0,0 +1,200 @@
|
||||
#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
|
||||
159
navicat-patcher/amd64_emulator.hpp
Normal file
159
navicat-patcher/amd64_emulator.hpp
Normal file
@ -0,0 +1,159 @@
|
||||
#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
|
||||
160
navicat-patcher/i386_emulator.cpp
Normal file
160
navicat-patcher/i386_emulator.cpp
Normal file
@ -0,0 +1,160 @@
|
||||
#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
|
||||
152
navicat-patcher/i386_emulator.hpp
Normal file
152
navicat-patcher/i386_emulator.hpp
Normal file
@ -0,0 +1,152 @@
|
||||
#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
|
||||
302
navicat-patcher/image_interpreter.cpp
Normal file
302
navicat-patcher/image_interpreter.cpp
Normal file
@ -0,0 +1,302 @@
|
||||
#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
|
||||
202
navicat-patcher/image_interpreter.hpp
Normal file
202
navicat-patcher/image_interpreter.hpp
Normal file
@ -0,0 +1,202 @@
|
||||
#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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
38
navicat-patcher/keystone_assembler.cpp
Normal file
38
navicat-patcher/keystone_assembler.cpp
Normal file
@ -0,0 +1,38 @@
|
||||
#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
|
||||
54
navicat-patcher/keystone_assembler.hpp
Normal file
54
navicat-patcher/keystone_assembler.hpp
Normal file
@ -0,0 +1,54 @@
|
||||
#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;
|
||||
};
|
||||
|
||||
}
|
||||
@ -1,335 +0,0 @@
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/mman.h>
|
||||
#include <stdio.h>
|
||||
#include "Exception.hpp"
|
||||
#include "ExceptionSystem.hpp"
|
||||
#include "ResourceWrapper.hpp"
|
||||
#include "ResourceTraitsUnix.hpp"
|
||||
#include "Elf64Interpreter.hpp"
|
||||
#include "PatchSolutions.hpp"
|
||||
#include "Misc.hpp"
|
||||
|
||||
static void Welcome(bool bWait) {
|
||||
puts("**********************************************************");
|
||||
puts("* Navicat Patcher (Linux) by @DoubleLabyrinth *");
|
||||
puts("* Version: 1.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 directory where Navicat is installed.");
|
||||
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 void SelectPatchSolutions(ARL::ResourceWrapper<ARL::ResourceTraits::CppObject<nkg::PatchSolution>>& lpSolution0) {
|
||||
// pass
|
||||
}
|
||||
|
||||
static void NavicatBackupDetect(std::string_view szFilePath) {
|
||||
std::string szBackupPath(szFilePath);
|
||||
szBackupPath += ".bak";
|
||||
if (nkg::Misc::FsIsExist(szBackupPath) == true) {
|
||||
while (true) {
|
||||
printf("[?] Previous backup %s is detected. Delete? (y/n)", szBackupPath.c_str());
|
||||
|
||||
auto select = getchar();
|
||||
while (select != '\n' && getchar() != '\n') {}
|
||||
|
||||
if (select == 'Y' || select == 'y') {
|
||||
nkg::Misc::FsDeleteFile(szBackupPath);
|
||||
break;
|
||||
} else if (select == 'N' || select == 'n') {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "Backup file still existed. Patch abort!");
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
static void NavicatBackupMake(std::string_view szFilePath) {
|
||||
std::string szBackupPath(szFilePath);
|
||||
szBackupPath += ".bak";
|
||||
nkg::Misc::FsCopyFile(szFilePath, szBackupPath);
|
||||
}
|
||||
|
||||
static void LoadKey(nkg::RSACipher& Cipher,
|
||||
std::string_view szKeyFileName,
|
||||
nkg::PatchSolution* lpSolution0) {
|
||||
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) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "The RSA private key you provide cannot be used.");
|
||||
}
|
||||
} else {
|
||||
printf("[*] Generating new RSA private key, it may take a long time...\n");
|
||||
|
||||
do {
|
||||
Cipher.GenerateKey(2048);
|
||||
} while (lpSolution0 && lpSolution0->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("%s\n", Cipher.ExportKeyString<nkg::RSAKeyType::PublicKey, nkg::RSAKeyFormat::PEM>().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(__BASE_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(__BASE_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<ARL::ResourceTraits::CppObject<nkg::PatchSolution>> lpSolution0;
|
||||
|
||||
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(__BASE_FILE__, __LINE__, errno, "munmap failed.");
|
||||
}
|
||||
} };
|
||||
ARL::ResourceWrapper libcc_interpreter{ ARL::ResourceTraits::CppObject<nkg::Elf64Interpreter>{} };
|
||||
|
||||
//
|
||||
// try open libcc.so
|
||||
//
|
||||
libcc_path = szInstallPath + "/usr/lib/libcc.so";
|
||||
libcc_fd.TakeOver(open(libcc_path.c_str(), O_RDWR));
|
||||
if (libcc_fd.IsValid()) {
|
||||
printf("[+] Try to open libcc.so ... Ok!\n");
|
||||
} else {
|
||||
if (errno == ENOENT) {
|
||||
printf("[-] Try to open libcc.so ... Not found!\n");
|
||||
} else {
|
||||
throw ARL::SystemError(__BASE_FILE__, __LINE__, errno, "open failed.");
|
||||
}
|
||||
}
|
||||
|
||||
puts("");
|
||||
|
||||
//
|
||||
// try map libcc.so
|
||||
//
|
||||
|
||||
if (libcc_fd.IsValid()) {
|
||||
libcc_stat.TakeOver(new struct stat());
|
||||
if (fstat(libcc_fd, libcc_stat) != 0) {
|
||||
throw ARL::SystemError(__BASE_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(__BASE_FILE__, __LINE__, errno, "mmap failed.");
|
||||
}
|
||||
|
||||
libcc_interpreter.TakeOver(
|
||||
new nkg::Elf64Interpreter(nkg::Elf64Interpreter::Parse(libcc_mmap, libcc_stat->st_size))
|
||||
);
|
||||
|
||||
lpSolution0.TakeOver(
|
||||
new nkg::PatchSolution0(*libcc_interpreter.Get())
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Make sure that there is one patch solution at least existing.
|
||||
//
|
||||
if (lpSolution0.IsValid() == false) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "No patch applied. Patch abort!")
|
||||
.PushHint("Are you sure your Navicat has not been patched/modified before?");
|
||||
}
|
||||
|
||||
//
|
||||
// Finding patch offsets
|
||||
//
|
||||
|
||||
if (lpSolution0.IsValid() && lpSolution0->FindPatchOffset() == false) {
|
||||
lpSolution0.Release();
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
|
||||
//
|
||||
// decide which solutions will be applied
|
||||
//
|
||||
SelectPatchSolutions(lpSolution0);
|
||||
|
||||
//
|
||||
// Make sure that there is one patch solution at least existing.
|
||||
//
|
||||
if (lpSolution0.IsValid() == false) {
|
||||
throw ARL::Exception(__BASE_FILE__, __LINE__, "No patch applied. Patch abort!")
|
||||
.PushHint("Are you sure your Navicat has not been patched/modified before?");
|
||||
}
|
||||
|
||||
//
|
||||
// detecting backups
|
||||
//
|
||||
if (lpSolution0.IsValid()) {
|
||||
NavicatBackupDetect(libcc_path);
|
||||
}
|
||||
|
||||
//
|
||||
//
|
||||
//
|
||||
LoadKey(Cipher, szKeyFilePath, lpSolution0);
|
||||
|
||||
if (bDryrun == false) {
|
||||
//
|
||||
// Save private key if not given
|
||||
//
|
||||
if (szKeyFilePath.empty()) {
|
||||
Cipher.ExportKeyToFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>("RegPrivateKey.pem");
|
||||
}
|
||||
|
||||
//
|
||||
// Making backups
|
||||
//
|
||||
if (lpSolution0.IsValid()) {
|
||||
NavicatBackupMake(libcc_path);
|
||||
}
|
||||
|
||||
//
|
||||
// Making patch. No way to go back here :-)
|
||||
//
|
||||
if (lpSolution0.IsValid()) {
|
||||
lpSolution0->MakePatch(Cipher);
|
||||
}
|
||||
|
||||
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("* PATCH HAS BEEN DONE SUCCESSFULLY! *");
|
||||
puts("* HAVE FUN AND ENJOY~ *");
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
210
navicat-patcher/navicat-patcher.vcxproj
Normal file
210
navicat-patcher/navicat-patcher.vcxproj
Normal file
@ -0,0 +1,210 @@
|
||||
<?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>
|
||||
66
navicat-patcher/navicat-patcher.vcxproj.filters
Normal file
66
navicat-patcher/navicat-patcher.vcxproj.filters
Normal file
@ -0,0 +1,66 @@
|
||||
<?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>
|
||||
6
navicat-patcher/navicat-patcher.vcxproj.user
Normal file
6
navicat-patcher/navicat-patcher.vcxproj.user
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ShowAllFiles>true</ShowAllFiles>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
19
navicat-patcher/patch_solution.hpp
Normal file
19
navicat-patcher/patch_solution.hpp
Normal file
@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include "rsa_cipher.hpp"
|
||||
|
||||
namespace nkg {
|
||||
|
||||
class patch_solution {
|
||||
public:
|
||||
[[nodiscard]]
|
||||
virtual bool find_patch() = 0;
|
||||
|
||||
[[nodiscard]]
|
||||
virtual bool check_rsa_privkey(const rsa_cipher& cipher) = 0;
|
||||
|
||||
virtual void make_patch(const rsa_cipher& cipher) = 0;
|
||||
|
||||
virtual ~patch_solution() = default;
|
||||
};
|
||||
|
||||
}
|
||||
9
navicat-patcher/patch_solution_since.hpp
Normal file
9
navicat-patcher/patch_solution_since.hpp
Normal file
@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include "patch_solution.hpp"
|
||||
|
||||
namespace nkg {
|
||||
|
||||
template<int major_ver0, int major_ver1, int minor_ver0, int minor_ver1>
|
||||
class patch_solution_since;
|
||||
|
||||
}
|
||||
591
navicat-patcher/patch_solution_since_16.0.7.0.amd64.cpp
Normal file
591
navicat-patcher/patch_solution_since_16.0.7.0.amd64.cpp
Normal file
@ -0,0 +1,591 @@
|
||||
#define _CRT_SECURE_NO_WARNINGS
|
||||
#include "amd64_emulator.hpp"
|
||||
#include "keystone_assembler.hpp"
|
||||
#include "patch_solution_since_16.0.7.0.hpp"
|
||||
#include <algorithm>
|
||||
#include <fmt/format.h>
|
||||
|
||||
namespace nkg {
|
||||
|
||||
patch_solution_since<16, 0, 7, 0>::patch_solution_since(image_interpreter& libcc_interpreter) :
|
||||
m_libcc_interpreter(libcc_interpreter),
|
||||
m_va_CSRegistrationInfoFetcher_WIN_vtable(0),
|
||||
m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey(0),
|
||||
m_va_iat_entry_malloc(0) {}
|
||||
|
||||
bool patch_solution_since<16, 0, 7, 0>::find_patch() {
|
||||
auto CSRegistrationInfoFetcher_WIN_type_descriptor_name =
|
||||
m_libcc_interpreter.search_section<const uint8_t*>(
|
||||
".data",
|
||||
[](const uint8_t* p, size_t s) {
|
||||
if (s < sizeof(".?AVCSRegistrationInfoFetcher_WIN@@")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return strcmp(reinterpret_cast<const char*>(p), ".?AVCSRegistrationInfoFetcher_WIN@@") == 0;
|
||||
}
|
||||
);
|
||||
|
||||
if (CSRegistrationInfoFetcher_WIN_type_descriptor_name == nullptr) {
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_WIN is not found. (failure label 0)\n");
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_rtti_type_descriptor = CSRegistrationInfoFetcher_WIN_type_descriptor_name - 0x10;
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_rva = m_libcc_interpreter.convert_ptr_to_rva(CSRegistrationInfoFetcher_WIN_rtti_type_descriptor);
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor =
|
||||
m_libcc_interpreter.search_section<const uint8_t*>(
|
||||
".rdata",
|
||||
[this, CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_rva](const uint8_t* p, size_t s) {
|
||||
if (reinterpret_cast<uintptr_t>(p) % sizeof(uint32_t) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (s < sizeof(uint32_t)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (*reinterpret_cast<const uint32_t*>(p) != CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_rva) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (s < sizeof(uint32_t) * 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto maybe_CSRegistrationInfoFetcher_WIN_rtti_class_hierarchy_descriptor_rva = reinterpret_cast<const uint32_t*>(p)[1];
|
||||
|
||||
try {
|
||||
return memcmp(m_libcc_interpreter.image_section_header_from_rva(maybe_CSRegistrationInfoFetcher_WIN_rtti_class_hierarchy_descriptor_rva)->Name, ".rdata\x00\x00", 8) == 0;
|
||||
} catch (nkg::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor == nullptr) {
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_WIN is not found. (failure label 1)\n");
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator = CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor - 0xC;
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator);
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_vtable_before =
|
||||
m_libcc_interpreter.search_section<const uint8_t*>(
|
||||
".rdata",
|
||||
[CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va](const uint8_t* p, size_t s) {
|
||||
if (reinterpret_cast<uintptr_t>(p) % sizeof(uint64_t) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (s < sizeof(uint64_t)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return *reinterpret_cast<const uint64_t*>(p) == CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va;
|
||||
}
|
||||
);
|
||||
|
||||
if (CSRegistrationInfoFetcher_WIN_vtable_before == nullptr) {
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Vftable for CSRegistrationInfoFetcher_WIN is not found.\n");
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_vtable =
|
||||
reinterpret_cast<const image_interpreter::va_t*>(CSRegistrationInfoFetcher_WIN_vtable_before + sizeof(image_interpreter::va_t));
|
||||
|
||||
m_va_CSRegistrationInfoFetcher_WIN_vtable = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_vtable);
|
||||
m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = CSRegistrationInfoFetcher_WIN_vtable[6];
|
||||
wprintf(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x%016llx\n", m_va_CSRegistrationInfoFetcher_WIN_vtable);
|
||||
wprintf(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x%016llx\n", m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey);
|
||||
|
||||
amd64_emulator x64_emulator;
|
||||
|
||||
x64_emulator.context_set("heap_base", uint64_t{ 0x00007fff00000000 });
|
||||
x64_emulator.context_set("heap_size", size_t{ 0x1000 * 32 });
|
||||
x64_emulator.context_set("heap_records", std::map<uint64_t, uint64_t>{});
|
||||
|
||||
x64_emulator.context_set("stack_base", uint64_t{ 0x00007fffffff0000 });
|
||||
x64_emulator.context_set("stack_size", size_t{ 0x1000 * 32 });
|
||||
x64_emulator.context_set("stack_top", uint64_t{ x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") });
|
||||
|
||||
x64_emulator.context_set("dead_area_base", uint64_t{ 0xfffffffffffff000 });
|
||||
x64_emulator.context_set("dead_area_size", size_t{ 0x1000 });
|
||||
|
||||
x64_emulator.context_set("iat_base", uint64_t{ m_libcc_interpreter.convert_rva_to_va(m_libcc_interpreter.image_nt_headers()->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) });
|
||||
x64_emulator.context_set("iat_size", size_t{ m_libcc_interpreter.image_nt_headers()->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size });
|
||||
|
||||
x64_emulator.context_set("external_api_stub_area_base", uint64_t{ 0xffff800000000000 });
|
||||
x64_emulator.context_set("external_api_stub_area_size", size_t{ (x64_emulator.context_get<size_t>("iat_size") / 8 + 0xfff) / 0x1000 * 0x1000 });
|
||||
|
||||
x64_emulator.context_set("external_api_impl", std::map<std::string, uint64_t>{});
|
||||
x64_emulator.context_set("external_api_impl_area_base", uint64_t{ 0xffff900000000000 });
|
||||
x64_emulator.context_set("external_api_impl_area_size", size_t{ 0 });
|
||||
|
||||
x64_emulator.context_set("gs_base", uint64_t{ 0xffffa00000000000 });
|
||||
x64_emulator.context_set("gs_size", size_t{ 0x1000 });
|
||||
|
||||
x64_emulator.context_set("start_address", static_cast<uint64_t>(m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey));
|
||||
x64_emulator.context_set("dead_address", x64_emulator.context_get<uint64_t>("dead_area_base"));
|
||||
|
||||
// allocate heap
|
||||
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("heap_base"), x64_emulator.context_get<size_t>("heap_size"), UC_PROT_READ | UC_PROT_WRITE);
|
||||
|
||||
// allocate stack
|
||||
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("stack_top"), x64_emulator.context_get<size_t>("stack_size"), UC_PROT_READ | UC_PROT_WRITE);
|
||||
|
||||
// allocate dead area
|
||||
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("dead_area_base"), x64_emulator.context_get<size_t>("dead_area_size"), UC_PROT_READ | UC_PROT_EXEC);
|
||||
|
||||
// allocate and hook read access to IAT
|
||||
{
|
||||
auto iat_base = x64_emulator.context_get<uint64_t>("iat_base");
|
||||
auto iat_size = x64_emulator.context_get<size_t>("iat_size");
|
||||
auto external_api_stub_area_base = x64_emulator.context_get<uint64_t>("external_api_stub_area_base");
|
||||
|
||||
auto iat_page_base = iat_base / 0x1000 * 0x1000;
|
||||
auto iat_page_count = (iat_base - iat_page_base + iat_size + 0xfff) / 0x1000;
|
||||
|
||||
x64_emulator.mem_map(iat_page_base, iat_page_count * 0x1000, UC_PROT_READ);
|
||||
|
||||
x64_emulator.hook_add<UC_HOOK_MEM_READ>(
|
||||
[this, &x64_emulator, iat_base, external_api_stub_area_base](uc_mem_type type, uint64_t address, size_t size, int64_t value) {
|
||||
auto rva = m_libcc_interpreter.convert_va_to_rva(address);
|
||||
auto import_lookup_entry = m_libcc_interpreter.import_lookup_entry_from_rva(rva);
|
||||
|
||||
if (import_lookup_entry && !IMAGE_SNAP_BY_ORDINAL(import_lookup_entry->u1.Ordinal)) {
|
||||
auto import_by_name_entry = m_libcc_interpreter.convert_rva_to_ptr<PIMAGE_IMPORT_BY_NAME>(import_lookup_entry->u1.AddressOfData);
|
||||
if (strcmp(import_by_name_entry->Name, "memcpy") == 0) {
|
||||
uint64_t impl_address = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["memcpy"];
|
||||
x64_emulator.mem_write(address, &impl_address, sizeof(impl_address));
|
||||
} else if (strcmp(import_by_name_entry->Name, "memcmp") == 0) {
|
||||
uint64_t impl_address = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["memcmp"];
|
||||
x64_emulator.mem_write(address, &impl_address, sizeof(impl_address));
|
||||
} else {
|
||||
uint64_t stub_address = external_api_stub_area_base + (address - iat_base) / sizeof(IMAGE_THUNK_DATA);
|
||||
x64_emulator.mem_write(address, &stub_address, sizeof(stub_address));
|
||||
}
|
||||
} else {
|
||||
x64_emulator.emu_stop();
|
||||
}
|
||||
},
|
||||
iat_base,
|
||||
iat_base + iat_size - 1
|
||||
);
|
||||
}
|
||||
|
||||
// allocate and setup external api stub area
|
||||
{
|
||||
auto external_api_stub_area_base = x64_emulator.context_get<uint64_t>("external_api_stub_area_base");
|
||||
auto external_api_stub_area_size = x64_emulator.context_get<size_t>("external_api_stub_area_size");
|
||||
|
||||
x64_emulator.mem_map(external_api_stub_area_base, external_api_stub_area_size, UC_PROT_READ | UC_PROT_EXEC);
|
||||
x64_emulator.mem_write(external_api_stub_area_base, std::vector<uint8_t>(external_api_stub_area_size, 0xc3)); // c3 -> ret
|
||||
|
||||
x64_emulator.hook_add<UC_HOOK_CODE>(
|
||||
[this, &x64_emulator, external_api_stub_area_base](uint64_t address, size_t size) {
|
||||
auto iat_base = x64_emulator.context_get<uint64_t>("iat_base");
|
||||
auto from_va = iat_base + (address - external_api_stub_area_base) * sizeof(IMAGE_THUNK_DATA);
|
||||
auto from_rva = m_libcc_interpreter.convert_va_to_rva(from_va);
|
||||
|
||||
auto import_lookup_entry = m_libcc_interpreter.import_lookup_entry_from_rva(from_rva);
|
||||
if (import_lookup_entry && !IMAGE_SNAP_BY_ORDINAL(import_lookup_entry->u1.Ordinal)) {
|
||||
auto import_by_name_entry = m_libcc_interpreter.convert_rva_to_ptr<PIMAGE_IMPORT_BY_NAME>(import_lookup_entry->u1.AddressOfData);
|
||||
if (strcmp(import_by_name_entry->Name, "malloc") == 0) {
|
||||
m_va_iat_entry_malloc = from_va;
|
||||
|
||||
uint64_t alloc_size;
|
||||
x64_emulator.reg_read(UC_X86_REG_RCX, &alloc_size);
|
||||
|
||||
auto& heap_records = x64_emulator.context_get<std::map<uint64_t, uint64_t>&>("heap_records");
|
||||
|
||||
auto predecessor_chunk =
|
||||
std::adjacent_find(
|
||||
heap_records.begin(),
|
||||
heap_records.end(),
|
||||
[alloc_size](const auto& chunk0, const auto& chunk1) { return chunk1.first - (chunk0.first + chunk0.second) >= alloc_size; }
|
||||
);
|
||||
|
||||
uint64_t alloc_p;
|
||||
if (predecessor_chunk != heap_records.end()) {
|
||||
alloc_p = predecessor_chunk->first + predecessor_chunk->second;
|
||||
} else {
|
||||
auto heap_base = x64_emulator.context_get<uint64_t>("heap_base");
|
||||
auto heap_size = x64_emulator.context_get<uint64_t>("heap_size");
|
||||
|
||||
auto free_space_base = heap_records.size() > 0 ? heap_records.rbegin()->first + heap_records.rbegin()->second : heap_base;
|
||||
auto free_space_size = heap_base + heap_size - free_space_base;
|
||||
|
||||
if (free_space_size < alloc_size) {
|
||||
auto heap_expand_base = heap_base + heap_size;
|
||||
auto heap_expand_size = (alloc_size - free_space_size + 0xfff) / 0x1000 * 0x1000;
|
||||
x64_emulator.mem_map(heap_expand_base, heap_expand_size, UC_PROT_READ | UC_PROT_WRITE);
|
||||
}
|
||||
|
||||
alloc_p = free_space_base;
|
||||
}
|
||||
|
||||
heap_records[alloc_p] = alloc_size;
|
||||
|
||||
x64_emulator.reg_write(UC_X86_REG_RAX, &alloc_p);
|
||||
} else if (strcmp(import_by_name_entry->Name, "free") == 0) {
|
||||
uint64_t alloc_p;
|
||||
x64_emulator.reg_read(UC_X86_REG_RCX, &alloc_p);
|
||||
|
||||
auto& heap_records = x64_emulator.context_get<std::map<uint64_t, uint64_t>&>("heap_records");
|
||||
|
||||
auto chunk = heap_records.find(alloc_p);
|
||||
if (chunk != heap_records.end()) {
|
||||
heap_records.erase(chunk);
|
||||
} else {
|
||||
x64_emulator.emu_stop();
|
||||
}
|
||||
} else {
|
||||
x64_emulator.emu_stop();
|
||||
}
|
||||
} else {
|
||||
x64_emulator.emu_stop();
|
||||
}
|
||||
},
|
||||
external_api_stub_area_base,
|
||||
external_api_stub_area_base + external_api_stub_area_size - 1
|
||||
);
|
||||
}
|
||||
|
||||
// allocate and setup external api impl area
|
||||
{
|
||||
keystone_assembler x64_assembler{ KS_ARCH_X86, KS_MODE_64 };
|
||||
|
||||
std::map<std::string, std::vector<uint8_t>> machine_code_list =
|
||||
{
|
||||
std::make_pair(
|
||||
"memcpy",
|
||||
x64_assembler.assemble(
|
||||
"push rdi;"
|
||||
"push rsi;"
|
||||
"mov rdi, rcx;"
|
||||
"mov rsi, rdx;"
|
||||
"mov rcx, r8;"
|
||||
"rep movs byte ptr [rdi], byte ptr [rsi];"
|
||||
"pop rsi;"
|
||||
"pop rdi;"
|
||||
"ret;"
|
||||
)
|
||||
),
|
||||
std::make_pair(
|
||||
"memcmp",
|
||||
x64_assembler.assemble(
|
||||
" push rdi;"
|
||||
" push rsi;"
|
||||
" mov rsi, rcx;"
|
||||
" mov rdi, rdx;"
|
||||
" mov rcx, r8;"
|
||||
" cmp rcx, rcx;"
|
||||
" repe cmps byte ptr [rsi], byte ptr [rdi];"
|
||||
" jz cmp_eq;"
|
||||
"cmp_not_eq:"
|
||||
" movsx eax, byte ptr [rsi - 1];"
|
||||
" movsx ecx, byte ptr [rdi - 1];"
|
||||
" sub eax, ecx;"
|
||||
" jmp final;"
|
||||
"cmp_eq:"
|
||||
" xor eax, eax;"
|
||||
"final:"
|
||||
" pop rsi;"
|
||||
" pop rdi;"
|
||||
" ret;"
|
||||
)
|
||||
),
|
||||
std::make_pair(
|
||||
"memmove",
|
||||
x64_assembler.assemble(
|
||||
" push rdi;"
|
||||
" push rsi;"
|
||||
" cmp rdx, rcx;"
|
||||
" jb reverse_copy;"
|
||||
"copy:"
|
||||
" mov rdi, rcx;"
|
||||
" mov rsi, rdx;"
|
||||
" mov rcx, r8;"
|
||||
" rep movsb byte ptr[rdi], byte ptr[rsi];"
|
||||
" jmp final;"
|
||||
"reverse_copy:"
|
||||
" std;"
|
||||
" lea rdi, qword ptr[rcx + r8 - 1];"
|
||||
" lea rsi, qword ptr[rdx + r8 - 1];"
|
||||
" mov rcx, r8;"
|
||||
" rep movsb byte ptr[rdi], byte ptr[rsi];"
|
||||
" cld;"
|
||||
"final:"
|
||||
" pop rsi;"
|
||||
" pop rdi;"
|
||||
" ret;"
|
||||
)
|
||||
)
|
||||
};
|
||||
|
||||
auto& external_api_impl = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl");
|
||||
auto& external_api_impl_area_base = x64_emulator.context_get<uint64_t&>("external_api_impl_area_base");
|
||||
auto& external_api_impl_area_size = x64_emulator.context_get<size_t&>("external_api_impl_area_size");
|
||||
|
||||
auto p = external_api_impl_area_base;
|
||||
for (const auto& name_code_pair : machine_code_list) {
|
||||
external_api_impl[name_code_pair.first] = p;
|
||||
p = (p + name_code_pair.second.size() + 0xf) / 0x10 * 0x10;
|
||||
}
|
||||
|
||||
external_api_impl_area_size = (p + 0xfff) / 0x1000 * 0x1000 - external_api_impl_area_base;
|
||||
|
||||
x64_emulator.mem_map(external_api_impl_area_base, external_api_impl_area_size, UC_PROT_READ | UC_PROT_EXEC);
|
||||
for (const auto& name_code_pair : machine_code_list) {
|
||||
x64_emulator.mem_write(external_api_impl[name_code_pair.first], name_code_pair.second);
|
||||
}
|
||||
}
|
||||
|
||||
// allocate and hook access to gs area
|
||||
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("gs_base"), x64_emulator.context_get<size_t>("gs_size"), UC_PROT_READ | UC_PROT_WRITE);
|
||||
x64_emulator.msr_write(0xC0000101, x64_emulator.context_get<uint64_t>("gs_base")); // set gs base address
|
||||
|
||||
x64_emulator.hook_add<UC_HOOK_MEM_READ>(
|
||||
[this, &x64_emulator](uc_mem_type access, uint64_t address, size_t size, int64_t value) {
|
||||
auto gs_base = x64_emulator.context_get<uint64_t>("gs_base");
|
||||
switch (address - gs_base) {
|
||||
case 0x10: // qword ptr gs:[0x10] -> Stack Limit / Ceiling of stack (low address)
|
||||
{
|
||||
uint64_t val = x64_emulator.context_get<uint64_t>("stack_top");
|
||||
x64_emulator.mem_write(address, &val, size);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
x64_emulator.emu_stop();
|
||||
break;
|
||||
}
|
||||
},
|
||||
x64_emulator.context_get<uint64_t>("gs_base"),
|
||||
x64_emulator.context_get<uint64_t>("gs_base") + x64_emulator.context_get<size_t>("gs_size") - 1
|
||||
);
|
||||
|
||||
// x64_emulator.hook_add<UC_HOOK_CODE>([](uint64_t address, size_t size) { wprintf_s(L"code_trace, address = 0x%016zx\n", address); });
|
||||
|
||||
x64_emulator.hook_add<UC_HOOK_MEM_UNMAPPED>(
|
||||
[this, &x64_emulator](uc_mem_type access, uint64_t address, size_t size, int64_t value) -> bool {
|
||||
try {
|
||||
auto fault_section = m_libcc_interpreter.image_section_header_from_va(address);
|
||||
|
||||
auto page_base = address / 0x1000 * 0x1000;
|
||||
auto page_size = 0x1000;
|
||||
uint32_t page_perms = UC_PROT_NONE;
|
||||
|
||||
if (fault_section->Characteristics & IMAGE_SCN_MEM_READ) {
|
||||
page_perms |= UC_PROT_READ;
|
||||
}
|
||||
if (fault_section->Characteristics & IMAGE_SCN_MEM_WRITE) {
|
||||
page_perms |= UC_PROT_WRITE;
|
||||
}
|
||||
if (fault_section->Characteristics & IMAGE_SCN_MEM_EXECUTE) {
|
||||
page_perms |= UC_PROT_EXEC;
|
||||
}
|
||||
|
||||
x64_emulator.mem_map(page_base, page_size, page_perms);
|
||||
x64_emulator.mem_write(page_base, m_libcc_interpreter.convert_va_to_ptr<const void*>(page_base), page_size);
|
||||
|
||||
return true;
|
||||
} catch (::nkg::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// set rbp, rsp
|
||||
uint64_t init_rbp = x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") / 4;
|
||||
uint64_t init_rsp = x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") / 2;
|
||||
|
||||
x64_emulator.reg_write(UC_X86_REG_RBP, &init_rbp);
|
||||
x64_emulator.reg_write(UC_X86_REG_RSP, &init_rsp);
|
||||
|
||||
// set return address
|
||||
auto retaddr = x64_emulator.context_get<uint64_t>("dead_address");
|
||||
x64_emulator.mem_write(init_rsp, &retaddr, sizeof(retaddr));
|
||||
|
||||
// set argument registers
|
||||
uint64_t init_rcx = 0; // `this` pointer of CSRegistrationInfoFetcher_WIN, but we don't need it for now.
|
||||
uint64_t init_rdx = init_rsp + 0x40; // a pointer to stack memory which stores return value
|
||||
x64_emulator.reg_write(UC_X86_REG_RCX, &init_rcx);
|
||||
x64_emulator.reg_write(UC_X86_REG_RDX, &init_rdx);
|
||||
|
||||
//
|
||||
// start emulate
|
||||
//
|
||||
try {
|
||||
x64_emulator.emu_start(x64_emulator.context_get<uint64_t>("start_address"), x64_emulator.context_get<uint64_t>("dead_address"));
|
||||
} catch (nkg::exception&) {
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Code emulation failed.\n");
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
wprintf_s(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x%016llx\n", m_va_iat_entry_malloc);
|
||||
|
||||
//
|
||||
// get result
|
||||
//
|
||||
// on AMD64 platform, `std::string` has follow memory layout:
|
||||
// ------------------------------
|
||||
// | offset | size |
|
||||
// ------------------------------
|
||||
// | +0 | 0x10 | `char[16]: a small string buffer` OR `char*: a large string buffer pointer`
|
||||
// ------------------------------
|
||||
// | +0x10 | 0x8 | size_t: string length
|
||||
// ------------------------------
|
||||
// | +0x18 | 0x8 | size_t: capacity
|
||||
// ------------------------------
|
||||
//
|
||||
uint64_t encoded_key_length;
|
||||
x64_emulator.mem_read(init_rdx + 0x10, &encoded_key_length, sizeof(encoded_key_length));
|
||||
if (encoded_key_length != official_encoded_key.length()) {
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: unexpected encoded key length(%llu).\n", encoded_key_length);
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
uint64_t encoded_key_ptr;
|
||||
x64_emulator.mem_read(init_rdx, &encoded_key_ptr, sizeof(encoded_key_ptr));
|
||||
|
||||
auto encoded_key = x64_emulator.mem_read(encoded_key_ptr, encoded_key_length);
|
||||
if (memcmp(encoded_key.data(), official_encoded_key.data(), encoded_key.size()) == 0) {
|
||||
wprintf_s(L"[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.\n");
|
||||
return true;
|
||||
} else {
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: official encoded key is not found.\n");
|
||||
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool patch_solution_since<16, 0, 7, 0>::check_rsa_privkey(const rsa_cipher& cipher) {
|
||||
return true; // no requirements
|
||||
}
|
||||
|
||||
void patch_solution_since<16, 0, 7, 0>::make_patch(const rsa_cipher& cipher) {
|
||||
auto encoded_key = _build_encoded_key(cipher);
|
||||
|
||||
auto CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey =
|
||||
m_libcc_interpreter.convert_va_to_ptr<uint8_t*>(m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey);
|
||||
|
||||
std::vector<std::string> patch_code_chunks;
|
||||
patch_code_chunks.emplace_back("push rdi;");
|
||||
patch_code_chunks.emplace_back("push rsi;");
|
||||
patch_code_chunks.emplace_back("push rbx;");
|
||||
patch_code_chunks.emplace_back("push rbp;");
|
||||
patch_code_chunks.emplace_back("mov rbp, rsp;");
|
||||
patch_code_chunks.emplace_back("mov rbx, rdx;");
|
||||
patch_code_chunks.emplace_back("sub rsp, 0x20;");
|
||||
patch_code_chunks.emplace_back(fmt::format("mov rcx, {:#x};", encoded_key.length() + 1));
|
||||
patch_code_chunks.emplace_back(fmt::format("call qword ptr [{:#016x}];", m_va_iat_entry_malloc));
|
||||
patch_code_chunks.emplace_back("add rsp, 0x20;");
|
||||
{
|
||||
std::vector<uint64_t> push_values((encoded_key.length() + 1 + 7) / 8, 0);
|
||||
memcpy(push_values.data(), encoded_key.data(), encoded_key.length());
|
||||
|
||||
std::for_each(
|
||||
push_values.crbegin(),
|
||||
push_values.crend(),
|
||||
[&patch_code_chunks](uint64_t x) {
|
||||
patch_code_chunks.emplace_back(fmt::format("mov rdx, {:#016x};", x));
|
||||
patch_code_chunks.emplace_back("push rdx;");
|
||||
}
|
||||
);
|
||||
}
|
||||
patch_code_chunks.emplace_back("mov rdi, rax;");
|
||||
patch_code_chunks.emplace_back("mov rsi, rsp;");
|
||||
patch_code_chunks.emplace_back(fmt::format("mov rcx, {:#x};", encoded_key.length() + 1));
|
||||
patch_code_chunks.emplace_back("rep movs byte ptr [rdi], byte ptr [rsi];");
|
||||
patch_code_chunks.emplace_back("mov qword ptr [rbx], rax;");
|
||||
patch_code_chunks.emplace_back(fmt::format("mov qword ptr [rbx + 0x10], {:#x};", encoded_key.length()));
|
||||
patch_code_chunks.emplace_back(fmt::format("mov qword ptr [rbx + 0x18], {:#x};", encoded_key.length() + 1));
|
||||
patch_code_chunks.emplace_back("mov rax, rbx;");
|
||||
patch_code_chunks.emplace_back("leave;");
|
||||
patch_code_chunks.emplace_back("pop rbx;");
|
||||
patch_code_chunks.emplace_back("pop rsi;");
|
||||
patch_code_chunks.emplace_back("pop rdi;");
|
||||
patch_code_chunks.emplace_back("ret;");
|
||||
|
||||
//auto patch_code = keystone_assembler{ KS_ARCH_X86, KS_MODE_64 }
|
||||
// .assemble(
|
||||
// fmt::format(
|
||||
// " push rdi;"
|
||||
// " push rsi;"
|
||||
// " push rbx;"
|
||||
// " mov rbx, rdx;"
|
||||
// "allocate_string_buf:"
|
||||
// " mov rcx, {encoded_key_length:#x} + 1;"
|
||||
// " sub rsp, 0x20;"
|
||||
// " call qword ptr [{m_va_iat_entry_malloc:#x}];"
|
||||
// " add rsp, 0x20;"
|
||||
// "write_our_own_key_to_string_buf:"
|
||||
// " mov rdi, rax;"
|
||||
// " lea rsi, qword ptr [end_of_code + rip];"
|
||||
// " mov rcx, 0x188;"
|
||||
// " rep movs byte ptr [rdi], byte ptr [rsi];"
|
||||
// " mov byte ptr [rdi], 0;"
|
||||
// "craft_std_string:"
|
||||
// " mov qword ptr [rbx], rax;"
|
||||
// " mov qword ptr [rbx + 0x10], {encoded_key_length:#x};"
|
||||
// " mov qword ptr [rbx + 0x18], {encoded_key_length:#x} + 1;"
|
||||
// "final:"
|
||||
// " mov rax, rbx;"
|
||||
// " pop rbx;"
|
||||
// " pop rsi;"
|
||||
// " pop rdi;"
|
||||
// " ret;"
|
||||
// "end_of_code:",
|
||||
// fmt::arg("encoded_key_length", encoded_key.length()),
|
||||
// fmt::arg("m_va_iat_entry_malloc", m_va_iat_entry_malloc)
|
||||
// ),
|
||||
// m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey
|
||||
// );
|
||||
|
||||
std::vector<uint8_t> assembled_patch_code;
|
||||
{
|
||||
keystone_assembler x86_assembler{ KS_ARCH_X86, KS_MODE_64 };
|
||||
|
||||
auto current_va = m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey;
|
||||
auto next_reloc = m_libcc_interpreter.relocation_distribute().lower_bound(m_libcc_interpreter.convert_va_to_rva(current_va));
|
||||
for (const auto& patch_code_chunk : patch_code_chunks) {
|
||||
auto assembled_patch_code_chunk = x86_assembler.assemble(patch_code_chunk, current_va);
|
||||
|
||||
while (true) {
|
||||
auto next_reloc_va = m_libcc_interpreter.convert_rva_to_va(next_reloc->first);
|
||||
auto next_reloc_size = next_reloc->second;
|
||||
|
||||
if (current_va + assembled_patch_code_chunk.size() + 2 <= next_reloc_va) { // 2 -> size of machine code "jmp rel8"
|
||||
assembled_patch_code.insert(assembled_patch_code.end(), assembled_patch_code_chunk.begin(), assembled_patch_code_chunk.end());
|
||||
current_va += assembled_patch_code_chunk.size();
|
||||
break;
|
||||
} else if (current_va + 2 <= next_reloc_va) {
|
||||
auto next_va = next_reloc_va + next_reloc_size;
|
||||
auto assembled_jmp = x86_assembler.assemble(fmt::format("jmp {:#016x};", next_va), current_va);
|
||||
auto assembled_padding = std::vector<uint8_t>(next_va - (current_va + assembled_jmp.size()), 0xcc); // 0xcc -> int3
|
||||
assembled_patch_code.insert(assembled_patch_code.end(), assembled_jmp.begin(), assembled_jmp.end());
|
||||
assembled_patch_code.insert(assembled_patch_code.end(), assembled_padding.begin(), assembled_padding.end());
|
||||
current_va = next_va;
|
||||
++next_reloc;
|
||||
} else {
|
||||
__assume(false); // impossible to reach here
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
memcpy(CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey, assembled_patch_code.data(), assembled_patch_code.size());
|
||||
wprintf_s(L"[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.\n");
|
||||
}
|
||||
|
||||
}
|
||||
16
navicat-patcher/patch_solution_since_16.0.7.0.generic.cpp
Normal file
16
navicat-patcher/patch_solution_since_16.0.7.0.generic.cpp
Normal file
@ -0,0 +1,16 @@
|
||||
#include "patch_solution_since_16.0.7.0.hpp"
|
||||
#include <regex>
|
||||
|
||||
namespace nkg {
|
||||
|
||||
std::string patch_solution_since<16, 0, 7, 0>::_build_encoded_key(const rsa_cipher& cipher) {
|
||||
auto encoded_key = cipher.export_public_key_string_pem();
|
||||
|
||||
encoded_key = std::regex_replace(encoded_key, std::regex("-----BEGIN PUBLIC KEY-----"), "");
|
||||
encoded_key = std::regex_replace(encoded_key, std::regex("-----END PUBLIC KEY-----"), "");
|
||||
encoded_key = std::regex_replace(encoded_key, std::regex("\n"), "");
|
||||
|
||||
return encoded_key;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user