2 Commits
Author SHA1 Message Date
Double Sine a7d282d608 Use 'latest' tag in download link 2019-09-06 23:21:22 +08:00
Double Sine e83a73b3c9 Upload code for v4.0 2019-09-06 22:35:29 +08:00
417 changed files with 7666 additions and 119977 deletions
+3 -288
View File
@@ -1,289 +1,4 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
MailDataReciever/Renci.SshNet.dll
.vscode/
bin/
obj/
+16 -162
View File
@@ -4,179 +4,33 @@
This repository will tell you how Navicat offline activation works.
[How does it work?](HOW_DOES_IT_WORK.md)
Previous code is archived in [`windows-archived`](https://github.com/DoubleLabyrinth/navicat-keygen/tree/windows-archived) branch for the reason that previos code contains 3rd binary libraries and it gets quite big :-(.
## How to use?
When you git-clone this repo, please add `--single-branch` flag so that archived branch won't be cloned to your computer, which saves your time and disk.
1. Download the latest release [from here](https://github.com/DoubleLabyrinth/navicat-keygen/releases).
```console
$ git clone -b windows --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
```
2. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `navicat.exe` and `libcc.dll`.
```
navicat-patcher.exe <Navicat installation path> [RSA-2048 PEM file]
```
## 1. How does it work?
* `<Navicat installation path>`: The full path to Navicat installation folder.
__This parameter must be specified.__
see [here](doc/how-does-it-work.md)
* `[RSA-2048 PEM file]`: 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.
## 2. How to build?
__Example: (in cmd.exe)__
see [here](doc/how-to-build.md).
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 12" .\RegPrivateKey.pem
```
It has been tested on __Navicat Premium 12.1.7 Simplified Chinese version__. The following is an example of output.
## 3. How to use?
```
MESSAGE: Navicat.exe has been found.
MESSAGE: libcc.dll has been found.
For Windows users, see [here](doc/how-to-use.windows.md).
MESSAGE: [Solution0] Keyword has been found: offset = +0x0297a6e0.
MESSAGE: [Solution1] Keywords[0] has been found: offset = +0x02057530.
MESSAGE: [Solution1] Keywords[1] has been found: offset = +0x006c4f89.
MESSAGE: [Solution1] Keywords[2] has been found: offset = +0x02057240.
MESSAGE: [Solution1] Keywords[3] has been found: offset = +0x006c4f6f.
MESSAGE: [Solution1] Keywords[4] has been found: offset = +0x0205722c.
For Linux users, see [here](doc/how-to-use.linux.md).
Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtOZGsX7UoDPuxCfEuw4i
yWDASpwaN19GaPNrTlWz6K7MKXGrAQpYD5gNZ8nGdfRgp52TErTHSNoRjgfpxGqK
ApPUISsIanGMcyf/H2b8pGuz1oF19kVKSyZTPaVLbE+1Cw7FULbI04bc64XnWSHo
aQAXrYKGpC7oDomRGMtx28figu3AHAk1UQrcCvE3+0ITTA7X8xaRwz6+gb+uLgCd
iXyRYDodG8i+kk1YIt3f2mt7jH+uEHqBYjIfvvo6g5MZz4KNz7Ewc6+sDyO8bmlX
eFnHo6YAgCcaHVvVtGNCxCd1O5wWHvUN985HHQYnFr7qzJaL9cPb735pP2hb0IXe
ywIDAQAB
-----END PUBLIC KEY-----
## 4. Contributor
* Deltafox79
MESSAGE: Navicat.exe has been backed up successfully.
MESSAGE: libcc.dll has been backed up successfully.
* dragonflylee
......
......
......
Solution0 has been done successfully.
Solution1 has been done successfully.
```
3. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>
```
* `<-bin|-text>`: Must be `-bin` or `-text`.
If `-bin` is specified, `navicat-keygen.exe` will finally generate `license_file`. It is used for Navicat old activation method only.
If `-text` is specified, `navicat-keygen.exe` will finally generate a Base64-style string which is __Activation Code__. It is used for Navicat new activation method.
__This parameter must be specified.__
* `[-adv]`: Enable advanced mode.
__This parameter is optional.__ If specified, `navicat-keygen.exe` will ask you input Navicat product ID number, language signature numbers. It is for future use generally.
* `<RSA-2048 PrivateKey(PEM file)>`: The full path or relative path to a RSA-2048 private key file.
__This parameter must be specified.__
__Example: (in cmd.exe)__
```bash
navicat-keygen.exe -text .\RegPrivateKey.pem
```
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
Select Navicat product:
1. DataModeler
2. Premium
3. MySQL
4. PostgreSQL
5. Oracle
6. SQLServer
7. SQLite
8. MariaDB
9. MongoDB
10. ReportViewer
(Input index)> 1
Select product language:
1. English
2. Simplified Chinese
3. Traditional Chinese
4. Japanese
5. Polish
6. Spanish
7. French
8. German
9. Korean
10. Russian
11. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVA-DHCN-P2OI-DV46
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.
```bash
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
4. __Disconnect your network__ and open Navicat. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
5. Generally online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
6. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```bash
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
q/cv0bkTrG1YDkS+fajFdi85bwNVBD/lc5jBYJPOSS5bfl4DdtnfXo+RRxdMjJtEcYQnvLPi2LF0
OB464brX9dqU29/O+A3qstSyhBq5//iezxfu2Maqca4y0rVtZgQSpEnZ0lBNlqKXv7CuTUYCS1pm
tEPgwJysQTMUZf7tu5MR0cQ+hY/AlyQ9iKrQAMhHklqZslaisi8VsnoIqH56vfTyyUwUQXrFNc41
qG5zZNsXu/NI79JOo7qTvcFHQT/k5cTadbKTxY+9c5eh+nF3JR7zEa2BDDfdQRLNvy4DTSyxdYXd
sAk/YPU+JdWI+8ELaa0SuAuNzr5fEkD6NDSG2A==
Request Info:
{"K":"NAVADHCNP2OIDV46", "DI":"Y2eJk9vrvfGudPG7Mbdn", "P":"WIN 8"}
Response Info:
{"K":"NAVADHCNP2OIDV46","DI":"Y2eJk9vrvfGudPG7Mbdn","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1537630251}
License:
oyoMYr9cfVGXeT7F1dqBwHsB/vvWj6SUL6aR+Kzb0lm5IyEj1CgovuSq+qMzFfx+
oHMFaGKFg6viOY2hfJcrO2Vdq0hXZS/B/Ie3jBS2Ov37v8e3ufVajaH+wLkmEpLd
xppCVLkDQjIHYR2IPz5s/L/RuWqDpEY4TPmGFF6q+xQMnqQA3vXPyG+JYMARXLru
Y1gCDLN30v3DpyOeqKmFjUqiHK5h8s0NYiH2OpMyaCpi12JsF23miP89ldQp3+SJ
8moo0cNGy7sFp2gX9ol2zVoo7qxfYlLl03f7CALJ6im0sx4yBsmlzFDdvpQUbXk8
YZ5rT4LML2Fx6Wgnnklb5g==
```
7. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully.
* zenuo
+16 -162
View File
@@ -2,179 +2,33 @@
这份repo将会告诉你Navicat是怎么完成离线激活的。
[注册机是怎么工作的?](HOW_DOES_IT_WORK.zh-CN.md)
由于历史代码包含第三方二进制库,且大小较大,故决定将该项目的历史代码归档到 [`windows-archived`](https://github.com/DoubleLabyrinth/navicat-keygen/tree/windows-archived) 分支。
## 如何使用这个注册机
当你clone该仓库的时候,请使用 `--single-branch` 选项,以此避免clone到 `windows-archived` 分支,并且还可以节省你的时间和磁盘空间。
1. [从这里](https://github.com/DoubleLabyrinth/navicat-keygen/releases)下载最新的release。
```console
$ git clone -b windows --single-branch https://github.com/DoubleLabyrinth/navicat-keygen.git
```
2. 使用`navicat-patcher.exe`替换掉`navicat.exe``libcc.dll`里的Navicat激活公钥。
## 1. 注册机是怎么工作的?
```
navicat-patcher.exe <Navicat installation path> [RSA-2048 PEM file]
```
见[这里](doc/how-does-it-work.zh-CN.md)。
* `<Navicat installation path>`: Navicat的完整安装路径。
__这个参数必须指定。__
## 2. 如何编译?
* `[RSA-2048 PEM file]`: RSA-2048私钥文件的完整路径或相对路径
__这个参数是可选的。__ 如果未指定,`navicat-patcher.exe`将会在当前目录生成一个新的RSA-2048私钥文件。
见[这里](doc/how-to-build.zh-CN.md)
__例如:(在cmd.exe中)__
## 3. 如何使用这个注册机?
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 12" .\RegPrivateKey.pem
```
__Navicat Premium 12.1.7 简体中文版已通过测试__。下面将是一份样例输出。
针对 Windows 用户,请见[这里](doc/how-to-use.windows.zh-CN.md)。
```
MESSAGE: Navicat.exe has been found.
MESSAGE: libcc.dll has been found.
针对 Linux 用户,请见[这里](doc/how-to-use.linux.zh-CN.md)。
MESSAGE: [Solution0] Keyword has been found: offset = +0x0297a6e0.
MESSAGE: [Solution1] Keywords[0] has been found: offset = +0x02057530.
MESSAGE: [Solution1] Keywords[1] has been found: offset = +0x006c4f89.
MESSAGE: [Solution1] Keywords[2] has been found: offset = +0x02057240.
MESSAGE: [Solution1] Keywords[3] has been found: offset = +0x006c4f6f.
MESSAGE: [Solution1] Keywords[4] has been found: offset = +0x0205722c.
## 4. 贡献者
Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtOZGsX7UoDPuxCfEuw4i
yWDASpwaN19GaPNrTlWz6K7MKXGrAQpYD5gNZ8nGdfRgp52TErTHSNoRjgfpxGqK
ApPUISsIanGMcyf/H2b8pGuz1oF19kVKSyZTPaVLbE+1Cw7FULbI04bc64XnWSHo
aQAXrYKGpC7oDomRGMtx28figu3AHAk1UQrcCvE3+0ITTA7X8xaRwz6+gb+uLgCd
iXyRYDodG8i+kk1YIt3f2mt7jH+uEHqBYjIfvvo6g5MZz4KNz7Ewc6+sDyO8bmlX
eFnHo6YAgCcaHVvVtGNCxCd1O5wWHvUN985HHQYnFr7qzJaL9cPb735pP2hb0IXe
ywIDAQAB
-----END PUBLIC KEY-----
* Deltafox79
* dragonflylee
MESSAGE: Navicat.exe has been backed up successfully.
MESSAGE: libcc.dll has been backed up successfully.
......
......
......
Solution0 has been done successfully.
Solution1 has been done successfully.
```
3. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>
```
* `<-bin|-text>`: 必须是`-bin`或`-text`。
如果指定了`-bin``navicat-keygen.exe`最终将生成`license_file`文件。这个选项是给Navicat旧激活方式使用的。
如果指定了`-bin``navicat-keygen.exe`最终将生成Base64样式的激活码。这个选项是给Navicat新激活方式使用的。
__这个参数必须指定。__
* `[-adv]`: 开启高级模式。
__这个参数是可选的。__ 如果指定了这个参数,`navicat-keygen.exe`将会要求你手工填写产品ID号、语言标识号。这个选项一般是给以后用的。
* `<RSA-2048 PrivateKey(PEM file)>`: RSA-2048私钥文件的完整路径或相对路径。
__这个参数必须指定。__
__例如:(在cmd.exe中)__
```bash
navicat-keygen.exe -text .\RegPrivateKey.pem
```
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号。
```
Select Navicat product:
1. DataModeler
2. Premium
3. MySQL
4. PostgreSQL
5. Oracle
6. SQLServer
7. SQLite
8. MariaDB
9. MongoDB
10. ReportViewer
(Input index)> 1
Select product language:
1. English
2. Simplified Chinese
3. Traditional Chinese
4. Japanese
5. Polish
6. Spanish
7. French
8. German
9. Korean
10. Russian
11. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVA-DHCN-P2OI-DV46
Your name:
```
你可以使用这个序列号暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```bash
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
4. __断开网络__ 并打开Navicat。找到`注册`窗口,并填入keygen给你的序列号。然后点击`激活`按钮。
5. 一般来说在线激活肯定会失败,这时候Navicat会询问你是否`手动激活`,直接选吧。
6. 在`手动激活`窗口你会得到一个请求码,复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```bash
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
q/cv0bkTrG1YDkS+fajFdi85bwNVBD/lc5jBYJPOSS5bfl4DdtnfXo+RRxdMjJtEcYQnvLPi2LF0
OB464brX9dqU29/O+A3qstSyhBq5//iezxfu2Maqca4y0rVtZgQSpEnZ0lBNlqKXv7CuTUYCS1pm
tEPgwJysQTMUZf7tu5MR0cQ+hY/AlyQ9iKrQAMhHklqZslaisi8VsnoIqH56vfTyyUwUQXrFNc41
qG5zZNsXu/NI79JOo7qTvcFHQT/k5cTadbKTxY+9c5eh+nF3JR7zEa2BDDfdQRLNvy4DTSyxdYXd
sAk/YPU+JdWI+8ELaa0SuAuNzr5fEkD6NDSG2A==
Request Info:
{"K":"NAVADHCNP2OIDV46", "DI":"Y2eJk9vrvfGudPG7Mbdn", "P":"WIN 8"}
Response Info:
{"K":"NAVADHCNP2OIDV46","DI":"Y2eJk9vrvfGudPG7Mbdn","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1537630251}
License:
oyoMYr9cfVGXeT7F1dqBwHsB/vvWj6SUL6aR+Kzb0lm5IyEj1CgovuSq+qMzFfx+
oHMFaGKFg6viOY2hfJcrO2Vdq0hXZS/B/Ie3jBS2Ov37v8e3ufVajaH+wLkmEpLd
xppCVLkDQjIHYR2IPz5s/L/RuWqDpEY4TPmGFF6q+xQMnqQA3vXPyG+JYMARXLru
Y1gCDLN30v3DpyOeqKmFjUqiHK5h8s0NYiH2OpMyaCpi12JsF23miP89ldQp3+SJ
8moo0cNGy7sFp2gX9ol2zVoo7qxfYlLl03f7CALJ6im0sx4yBsmlzFDdvpQUbXk8
YZ5rT4LML2Fx6Wgnnklb5g==
```
4. 如果不出意外,你会得到一个看似用Base64编码的激活码。直接复制它,并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。
* zenuo
-27
View File
@@ -1,27 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAtOZGsX7UoDPuxCfEuw4iyWDASpwaN19GaPNrTlWz6K7MKXGr
AQpYD5gNZ8nGdfRgp52TErTHSNoRjgfpxGqKApPUISsIanGMcyf/H2b8pGuz1oF1
9kVKSyZTPaVLbE+1Cw7FULbI04bc64XnWSHoaQAXrYKGpC7oDomRGMtx28figu3A
HAk1UQrcCvE3+0ITTA7X8xaRwz6+gb+uLgCdiXyRYDodG8i+kk1YIt3f2mt7jH+u
EHqBYjIfvvo6g5MZz4KNz7Ewc6+sDyO8bmlXeFnHo6YAgCcaHVvVtGNCxCd1O5wW
HvUN985HHQYnFr7qzJaL9cPb735pP2hb0IXeywIDAQABAoIBAA5W7qWlQx+L3lJo
QJz/Styhsbx4UU+wWrl5CjmEa6V3LbHfU8naUw6xY+alRPkWrQ68W+swr1dkCd4z
XGF4fIYlx7v1WE5vv81lD0Ei/cXez7uiOYKTDYeVeyW405i7XMOKoTN7ucGiwCJf
U+5p1K12F2pmnVuoaDa2yuynO9hLBqf3SeQ8qd2dQvKLqL8JVLE+a1txl3YuV5Ap
PzUyLtGOmo5pIyKeeQ2dgR+AhnsUPDj5t0F1see6ysQVsNDk7i8Zcyfn2uWy4DPy
NcWu/zLilelKDiYqI2UH+Fm0RzkG7ce2UmNbrG4ESEPNfwMyzy8IUGv3sBxL8p9a
Xvtg7YkCgYEA7x9+cJNjs1DVxhTCatQrqWUwtwDiXZniz/WRUK7mQgX3mdFRhBhH
GjZCvWOz1muYYvkwPSDMzwjwuV3ItPSUp7sI9FWhkrYqG+lMLpKXrYLSj1Grc9pn
CZLQwmL9UegBUihBonm6bp+xJxbQeF/HStUWXP3xnWyRHBwUyAQC5v8CgYEAwarK
08U7NbRcrYBgzegn0n2z3iG16JR/3kLQt/MJAsbQAxavW98b8rUb3V7XvkECiTcD
74XuFdIAeeZeqlcsnYq2Gbr1tKCbTLHewztuFBwsQzeEmu1i81w0LeUaZqtB8HwQ
evRRQGaEZfIdsXCn+PiPb/O5zGJNTJTD3aE/9DUCgYAdYutw/kwEX2zGGQsDgeuT
t8HS26L2CdFb6TvghH37oywYlSbFaw5h5EUzbStOsI5bq3AIMx24W8rpnOLrihsy
ucOR82wV0Zk/MN6R4qYNRsSFpG3DoRWEkaxiFzQ2eqKe7B+UzgzhR3LH8P/Rq0Oc
qK9E4lhtFkiHAdRz+Do7FQKBgH8thkZtJcXNrHKvdGKjSstaiuybXJbgNdwiKmgx
7D/riRwOIJgHOpY2wparuqeQj3bGLwpy+/dOUcu7MX1RA9ZtCcp50PKN6Y4C3FN+
ynngSlzVr3oB29IOQaHF6oFzgzjGcBgeKuFMsTM1PLSSU2wW5jLRbbi+8R4SL1Fy
m8nlAoGBAJsq8E6qkAErFkjHt7u1Pmp7iGdgoP8hDQ0NXH6BxU432j3cIT+g2W3y
K28wXuHGamDqA9PLq3lb55wEkHqR62mTBqt9nJAW6CmAsl1Appvtf7ynep5SSNZg
jLUllIz/D76Kb4AXehqfkLmU+X3a1dNofpDSqCr4AdEizZHbX8Zp
-----END RSA PRIVATE KEY-----
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
cd `dirname "$0"`
navicat_root=`pwd`
# Wine environment variables
WINEDIR="wine"
export LANG="en_US.UTF-8"
export PATH="$navicat_root/$WINEDIR/bin":"$navicat_root":"$navicat_root/$WINEDIR/drive_c/windows":"$PATH"
export LD_LIBRARY_PATH="$navicat_root/$WINEDIR/lib":"$navicat_root/lib":"$LD_LIBRARY_PATH"
export WINEDLLPATH="$navicat_root/$WINEDIR/lib/wine"
export WINELOADER="$navicat_root/$WINEDIR/bin/wine64"
export WINESERVER="$navicat_root/$WINEDIR/bin/wineserver"
export WINEPREFIX="$HOME/.navicat64"
exec "${WINELOADER:-wine}" "navicat-keygen.exe" "-text" "RegPrivateKey.pem"
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
cd `dirname "$0"`
navicat_root=`pwd`
# Wine environment variables
WINEDIR="wine"
export LANG="en_US.UTF-8"
export PATH="$navicat_root/$WINEDIR/bin":"$navicat_root":"$navicat_root/$WINEDIR/drive_c/windows":"$PATH"
export LD_LIBRARY_PATH="$navicat_root/$WINEDIR/lib":"$navicat_root/lib":"$LD_LIBRARY_PATH"
export WINEDLLPATH="$navicat_root/$WINEDIR/lib/wine"
export WINELOADER="$navicat_root/$WINEDIR/bin/wine64"
export WINESERVER="$navicat_root/$WINEDIR/bin/wineserver"
export WINEPREFIX="$HOME/.navicat64"
# 将斜线替换为反斜线
navicat_root_back_slash=${navicat_root//\//\\}
# 前缀
prefix='Z:\'
# 后缀
suffix='\Navicat'
# wine环境中的navicat路径
navicat_path="$prefix$navicat_root_back_slash$suffix"
# wine执行navicat-patcher.exe
exec "${WINELOADER:-wine}" "navicat-patcher.exe" "$navicat_path"
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include <windows.h>
#include "xstring.hpp"
#include <vector>
namespace nkg {
class Exception {
private:
PCTSTR _SourceFile;
SIZE_T _SourceLine;
PCTSTR _Message;
std::vector<std::xstring> _Hints;
public:
Exception(PCTSTR SourceFile, SIZE_T SourceLine, PCTSTR CustomMessage) noexcept :
_SourceFile(SourceFile),
_SourceLine(SourceLine),
_Message(CustomMessage) {}
[[nodiscard]]
auto File() const noexcept {
return _SourceFile;
}
[[nodiscard]]
auto Line() const noexcept {
return _SourceLine;
}
[[nodiscard]]
auto Message() const noexcept {
return _Message;
}
auto& AddHint(const std::xstring& Hint) {
_Hints.emplace_back(Hint);
return *this;
}
[[nodiscard]]
const auto& Hints() const noexcept {
return _Hints;
}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept {
return false;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept {
return 0;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept {
return nullptr;
}
virtual ~Exception() = default;
};
}
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include "Exception.hpp"
#include <openssl/err.h>
namespace nkg {
class OpensslError final : public Exception {
private:
unsigned long _ErrorCode;
std::xstring _ErrorString;
public:
OpensslError(PCTSTR SourceFile, SIZE_T SourceLine, unsigned long OpensslErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(OpensslErrorCode)
{
static bool CryptoStringsLoaded = false;
if (CryptoStringsLoaded == false) {
ERR_load_crypto_strings();
CryptoStringsLoaded = true;
}
_ErrorString = std::xstring(std::xstring_extension{}, ERR_reason_error_string(_ErrorCode), CP_UTF8);
}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
}
};
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "Exception.hpp"
namespace nkg {
class UserAbortionError final : public Exception {
public:
UserAbortionError(PCTSTR SourceFile, SIZE_T SourceLine, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage) {}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept override {
return false;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return 0;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return nullptr;
}
};
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include "Exception.hpp"
namespace nkg {
class Win32Error final : public Exception {
private:
DWORD _ErrorCode;
std::xstring _ErrorString;
public:
Win32Error(PCTSTR SourceFile, SIZE_T SourceLine, DWORD Win32ErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(Win32ErrorCode)
{
PTSTR Text = NULL;
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL,
Win32ErrorCode,
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
reinterpret_cast<PTSTR>(&Text),
0,
NULL
);
if (Text) {
_ErrorString = Text;
LocalFree(Text);
}
}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
}
};
}
+261
View File
@@ -0,0 +1,261 @@
#pragma once
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include "Exception.hpp"
#include "ExceptionOpenssl.hpp"
#include "ResourceOwned.hpp"
#include "ResourceTraitsOpenssl.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\common\\RSACipher.hpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
enum class RSAKeyType {
PrivateKey,
PublicKey
};
enum class RSAKeyFormat {
PEM,
PKCS1
};
class RSACipher final : private ResourceOwned<OpensslRSATraits> {
private:
template<RSAKeyType __Type, RSAKeyFormat __Format>
static void _WriteRSAToBIO(RSA* lpRSA, BIO* lpBIO) {
if constexpr (__Type == RSAKeyType::PrivateKey) {
if (PEM_write_bio_RSAPrivateKey(lpBIO, lpRSA, nullptr, nullptr, 0, nullptr, nullptr) == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_write_bio_RSAPrivateKey failed."));
}
}
if constexpr (__Type == RSAKeyType::PublicKey) {
if constexpr (__Format == RSAKeyFormat::PEM) {
if (PEM_write_bio_RSA_PUBKEY(lpBIO, lpRSA) == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_write_bio_RSA_PUBKEY failed."));
}
}
if constexpr (__Format == RSAKeyFormat::PKCS1) {
if (PEM_write_bio_RSAPublicKey(lpBIO, lpRSA) == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_write_bio_RSAPublicKey failed."));
}
}
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 Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_read_bio_RSAPrivateKey failed."))
.AddHint(TEXT("Are you sure that you DO provide a valid RSA private key file?"));
}
}
if constexpr (__Type == RSAKeyType::PublicKey) {
if constexpr (__Format == RSAKeyFormat::PEM) {
lpRSA = PEM_read_bio_RSA_PUBKEY(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_read_bio_RSA_PUBKEY failed."))
.AddHint(TEXT("Are you sure that you DO provide a valid RSA public key file with PEM format?"));
}
}
if constexpr (__Format == RSAKeyFormat::PKCS1) {
lpRSA = PEM_read_bio_RSAPublicKey(lpBIO, nullptr, nullptr, nullptr);
if (lpRSA == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PEM_read_bio_RSAPublicKey failed."))
.AddHint(TEXT("Are you sure that you DO provide a valid RSA public key file with PKCS1 format?"));
}
}
static_assert(__Format == RSAKeyFormat::PEM || __Format == RSAKeyFormat::PKCS1);
}
static_assert(__Type == RSAKeyType::PrivateKey || __Type == RSAKeyType::PublicKey);
return lpRSA;
}
public:
RSACipher() : ResourceOwned<OpensslRSATraits>(RSA_new()) {
if (IsValid() == false) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_new failed."));
}
}
[[nodiscard]]
size_t Bits() const {
if (Get()->n == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA modulus has not been set."));
} else {
return BN_num_bits(Get()->n);
}
}
void GenerateKey(int bits, unsigned int e = RSA_F4) {
ResourceOwned<OpensslBNTraits> bn_e(BN_new());
if (bn_e.IsValid() == false) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("BN_new failed."));
}
if (!BN_set_word(bn_e, e)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BN_set_word failed."));
}
if (!RSA_generate_key_ex(Get(), bits, bn_e, nullptr)) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_generate_key_ex failed."));
}
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ExportKeyToFile(const std::xstring& FileName) const {
ResourceOwned<OpensslBIOTraits> BioFile(BIO_new_file(FileName.explicit_string(CP_UTF8).c_str(), "w"));
if (BioFile.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new_file failed."));
}
_WriteRSAToBIO<__Type, __Format>(Get(), BioFile);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
[[nodiscard]]
std::string ExportKeyString() const {
ResourceOwned<OpensslBIOTraits> BioMemory(BIO_new(BIO_s_mem()));
long StringLength;
const char* StringChars = nullptr;
if (BioMemory.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new failed."));
}
_WriteRSAToBIO<__Type, __Format>(Get(), BioMemory);
StringLength = BIO_get_mem_data(BioMemory.Get(), &StringChars);
return std::string(StringChars, StringLength);
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyFromFile(const std::xstring& FileName) {
ResourceOwned<OpensslBIOTraits> BioFile(BIO_new_file(FileName.explicit_string(CP_UTF8).c_str(), "r"));
if (BioFile.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new_file failed."));
}
TakeOver(_ReadRSAFromBIO<__Type, __Format>(BioFile));
}
template<RSAKeyType __Type, RSAKeyFormat __Format>
void ImportKeyString(const std::string& KeyString) {
ResourceOwned<OpensslBIOTraits> BioMemory(BIO_new(BIO_s_mem()));
if (BioMemory.IsValid() == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_new failed."));
}
if (BIO_puts(BioMemory.Get(), KeyString.c_str()) <= 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("BIO_puts failed."));
}
TakeOver(_ReadRSAFromBIO<__Type, __Format>(BioMemory));
}
template<RSAKeyType __Type = RSAKeyType::PublicKey>
size_t Encrypt(const void* lpFrom, size_t cbFrom, void* lpTo, int Padding) const {
int BytesWritten;
if (cbFrom > INT_MAX) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Length overflowed."));
}
if constexpr (__Type == RSAKeyType::PrivateKey) {
BytesWritten = RSA_private_encrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_private_encrypt failed."));
}
} else {
BytesWritten = RSA_public_encrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_public_encrypt failed."));
}
}
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 > INT_MAX) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("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 OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_private_decrypt failed."))
.AddHint(TEXT("Are your sure you DO provide a correct private key?"));
}
} else {
BytesWritten = RSA_public_decrypt(
static_cast<int>(cbFrom),
reinterpret_cast<const unsigned char*>(lpFrom),
reinterpret_cast<unsigned char*>(lpTo),
Get(),
Padding
);
if (BytesWritten == -1) {
throw OpensslError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), TEXT("RSA_public_decrypt failed."))
.AddHint(TEXT("Are your sure you DO provide a correct public key?"));
}
}
return BytesWritten;
}
};
}
+313
View File
@@ -0,0 +1,313 @@
#pragma once
#include <type_traits>
#include <utility>
template<typename __ResourceTraits, typename __LambdaReleasor = void>
class ResourceOwned {
private:
using __HandleType = typename __ResourceTraits::HandleType;
static_assert(std::is_pod_v<__HandleType>);
__HandleType _Handle;
__LambdaReleasor _Releasor;
public:
ResourceOwned(__LambdaReleasor&& Releasor) noexcept :
_Handle(__ResourceTraits::InvalidValue),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
ResourceOwned(const __HandleType& Handle, __LambdaReleasor&& Releasor) noexcept :
_Handle(Handle),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
//
// Construct from custom releasor.
// `_Handle` will be set to an invalid value.
//
ResourceOwned(__ResourceTraits, __LambdaReleasor&& Releasor) noexcept :
_Handle(__ResourceTraits::InvalidValue),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
//
// Construct from handle given and custom releasor.
//
ResourceOwned(__ResourceTraits, const __HandleType& Handle, __LambdaReleasor&& Releasor) noexcept :
_Handle(Handle),
_Releasor(std::forward<__LambdaReleasor>(Releasor)) {}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
//
ResourceOwned(const ResourceOwned<__ResourceTraits, __LambdaReleasor>& Other) = delete;
//
// ResourceOwned allows to move.
//
ResourceOwned(ResourceOwned<__ResourceTraits, __LambdaReleasor>&& Other) noexcept :
_Handle(Other._Handle),
_Releasor(std::move(Other._Releasor))
{
Other._Handle = __ResourceTraits::InvalidValue;
}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
//
ResourceOwned<__ResourceTraits, __LambdaReleasor>& operator=(const ResourceOwned<__ResourceTraits, __LambdaReleasor>& Other) = delete;
//
// ResourceOwned allows to move.
//
ResourceOwned<__ResourceTraits, __LambdaReleasor>& operator=(ResourceOwned<__ResourceTraits, __LambdaReleasor>&& Other) noexcept {
_Handle = Other._Handle;
_Releasor = std::move(Other._Releasor);
Other._Handle = __ResourceTraits::InvalidValue;
return *this;
}
[[nodiscard]]
operator const __HandleType&() const noexcept { // NOLINT: Allow implicit conversion.
return _Handle;
}
template<typename __AsType, bool __IsPointer = std::is_pointer_v<__HandleType>, typename = std::enable_if_t<__IsPointer>>
[[nodiscard]]
__AsType As() const noexcept {
return reinterpret_cast<__AsType>(_Handle);
}
template<bool __IsPointer = std::is_pointer_v<__HandleType>, typename = typename std::enable_if_t<__IsPointer>>
[[nodiscard]]
__HandleType operator->() const noexcept {
return _Handle;
}
[[nodiscard]]
bool IsValid() const noexcept {
return __ResourceTraits::IsValid(_Handle);
}
[[nodiscard]]
const __HandleType& Get() const noexcept {
return _Handle;
}
template<typename __ReturnType = __HandleType*>
[[nodiscard]]
__ReturnType GetAddressOf() noexcept {
return reinterpret_cast<__ReturnType>(&_Handle);
}
void TakeOver(const __HandleType& Handle) {
if (__ResourceTraits::IsValid(_Handle) == true) {
_Releasor(_Handle);
}
_Handle = Handle;
}
void Discard() noexcept {
_Handle = __ResourceTraits::InvalidValue;
}
[[nodiscard]]
__HandleType Transfer() noexcept {
__HandleType t = _Handle;
_Handle = __ResourceTraits::InvalidValue;
return t;
}
void Release() {
if (__ResourceTraits::IsValid(_Handle)) {
_Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
}
}
~ResourceOwned() {
if (__ResourceTraits::IsValid(_Handle)) {
_Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
}
}
};
template<typename __ResourceTraits>
class ResourceOwned<__ResourceTraits, void> {
private:
using __HandleType = typename __ResourceTraits::HandleType;
static_assert(std::is_pod_v<__HandleType>);
__HandleType _Handle;
public:
ResourceOwned() noexcept :
_Handle(__ResourceTraits::InvalidValue) {}
ResourceOwned(const __HandleType& Handle) noexcept :
_Handle(Handle) {}
//
// Construct from custom releasor.
// `_Handle` will be set to an invalid value.
//
explicit ResourceOwned(__ResourceTraits) noexcept :
_Handle(__ResourceTraits::InvalidValue) {}
//
// Construct from handle given and custom releasor.
//
ResourceOwned(__ResourceTraits, const __HandleType& Handle) noexcept :
_Handle(Handle) {}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
//
ResourceOwned(const ResourceOwned<__ResourceTraits, void>& Other) = delete;
//
// ResourceOwned allows to move.
//
ResourceOwned(ResourceOwned<__ResourceTraits, void>&& Other) noexcept :
_Handle(Other._Handle) {
Other._Handle = __ResourceTraits::InvalidValue;
}
//
// ResourceOwned doesn't allow to copy.
// Because it takes `_Handle` exclusively.
//
ResourceOwned<__ResourceTraits, void>& operator=(const ResourceOwned<__ResourceTraits, void>& Other) = delete;
//
// ResourceOwned allows to move.
//
ResourceOwned<__ResourceTraits, void>& operator=(ResourceOwned<__ResourceTraits, void>&& Other) noexcept {
_Handle = Other._Handle;
Other._Handle = __ResourceTraits::InvalidValue;
return *this;
}
[[nodiscard]]
operator const __HandleType&() const noexcept { // NOLINT: Allow implicit conversion.
return _Handle;
}
template<typename __AsType, bool __IsPointer = std::is_pointer_v<__HandleType>, typename = typename std::enable_if_t<__IsPointer>>
[[nodiscard]]
__AsType As() const noexcept {
return reinterpret_cast<__AsType>(_Handle);
}
template<bool __IsPointer = std::is_pointer_v<__HandleType>, typename = typename std::enable_if_t<__IsPointer>>
[[nodiscard]]
__HandleType operator->() const noexcept {
return _Handle;
}
[[nodiscard]]
bool IsValid() const noexcept {
return __ResourceTraits::IsValid(_Handle);
}
[[nodiscard]]
const __HandleType& Get() const noexcept {
return _Handle;
}
template<typename __ReturnType = __HandleType*>
[[nodiscard]]
__ReturnType GetAddressOf() noexcept {
return reinterpret_cast<__ReturnType>(&_Handle);
}
void TakeOver(const __HandleType& Handle) {
if (__ResourceTraits::IsValid(_Handle) == true) {
__ResourceTraits::Releasor(_Handle);
}
_Handle = Handle;
}
void Discard() noexcept {
_Handle = __ResourceTraits::InvalidValue;
}
[[nodiscard]]
__HandleType Transfer() noexcept {
__HandleType t = _Handle;
_Handle = __ResourceTraits::InvalidValue;
return t;
}
void Release() {
if (__ResourceTraits::IsValid(_Handle)) {
__ResourceTraits::Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
}
}
~ResourceOwned() {
if (__ResourceTraits::IsValid(_Handle)) {
__ResourceTraits::Releasor(_Handle);
_Handle = __ResourceTraits::InvalidValue;
}
}
};
template<typename __ResourceTraits>
ResourceOwned(__ResourceTraits) ->
ResourceOwned<__ResourceTraits, void>;
template<typename __ResourceTraits, typename __ArgType>
ResourceOwned(__ResourceTraits, __ArgType&&) ->
ResourceOwned<
__ResourceTraits,
std::conditional_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<__ArgType>>, typename __ResourceTraits::HandleType> == false,
std::remove_reference_t<__ArgType>,
void
>
>;
template<typename __ResourceTraits, typename __LambdaReleasor>
ResourceOwned(__ResourceTraits, const typename __ResourceTraits::HandleType&, __LambdaReleasor&&) ->
ResourceOwned<__ResourceTraits, std::remove_reference_t<__LambdaReleasor>>;
template<typename __ClassType>
struct CppObjectTraits {
using HandleType = __ClassType*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) {
delete Handle;
}
};
template<typename __ClassType>
struct CppDynamicArrayTraits {
using HandleType = __ClassType*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) {
delete[] Handle;
}
};
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include <openssl/bio.h>
#include <openssl/rsa.h>
struct OpensslBIOTraits {
using HandleType = BIO*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
BIO_free(Handle);
}
};
struct OpensslBIOChainTraits {
using HandleType = BIO*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
BIO_free_all(Handle);
}
};
struct OpensslBNTraits {
using HandleType = BIGNUM*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
BN_free(Handle);
}
};
struct OpensslRSATraits {
using HandleType = RSA*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
RSA_free(Handle);
}
};
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#include <windows.h>
struct GenericHandleTraits {
using HandleType = HANDLE;
static inline const HandleType InvalidValue = NULL;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
CloseHandle(Handle);
}
};
struct FileHandleTraits {
using HandleType = HANDLE;
static inline const HandleType InvalidValue = INVALID_HANDLE_VALUE;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
CloseHandle(Handle);
}
};
struct MapViewHandleTraits {
using HandleType = PVOID;
static inline const HandleType InvalidValue = NULL;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
UnmapViewOfFile(Handle);
}
};
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <stdint.h>
#include <vector>
namespace std {
using bytearray = vector<uint8_t>;
}
+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<ItemsProjectGuid>{290c5d5e-52d2-4fef-909f-27fd95ae0af9}</ItemsProjectGuid>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories);$(MSBuildThisFileDirectory)</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ProjectCapability Include="SourceItemsFromImports" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="$(MSBuildThisFileDirectory)bytearray.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)Exception.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ExceptionOpenssl.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ExceptionUser.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ExceptionWin32.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ResourceOwned.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ResourceTraitsOpenssl.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)ResourceTraitsWin32.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)RSACipher.hpp" />
<ClInclude Include="$(MSBuildThisFileDirectory)xstring.hpp" />
</ItemGroup>
</Project>
+6
View File
@@ -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>
+288
View File
@@ -0,0 +1,288 @@
#pragma once
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <string>
#include <utility>
#include <stdexcept>
#include <system_error>
namespace std {
struct xstring_extension {};
#if defined(_UNICODE) || defined(UNICODE)
class xstring final : public wstring {
public:
using wstring::wstring;
using wstring::operator=;
xstring(const wstring& wstr) : wstring(wstr) {}
xstring(wstring&& wstr) : wstring(std::move(wstr)) {}
xstring(xstring_extension, const string& str, DWORD CodePage = CP_ACP) {
auto len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(static_cast<size_t>(len) - 1);
len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
xstring(xstring_extension, const char* lpstr, DWORD CodePage = CP_ACP) {
auto len = MultiByteToWideChar(CodePage, 0, lpstr, -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(static_cast<size_t>(len) - 1);
len = MultiByteToWideChar(CodePage, 0, lpstr, -1, data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
#else
class xstring final : public string {
public:
using string::string;
using string::operator=;
xstring(const string& str) : string(str) {}
xstring(string&& str) : string(std::move(str)) {}
xstring(xstring_extension, const string& str, DWORD CodePage = CP_ACP) {
if (CodePage == CP_ACP || CodePage == GetACP()) {
assign(str);
} else {
std::wstring wstr;
auto len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CodePage, 0, str.c_str(), -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
}
xstring(xstring_extension, const char* lpstr, DWORD CodePage = CP_ACP) {
if (CodePage == CP_ACP || CodePage == GetACP()) {
assign(str);
} else {
std::wstring wstr;
auto len = MultiByteToWideChar(CodePage, 0, lpstr, -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CodePage, 0, lpstr, -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
}
xstring(xstring_extension, const wstring& wstr) {
auto len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
xstring(xstring_extension, const wchar_t* lpwstr) {
auto len = WideCharToMultiByte(CP_ACP, 0, lpwstr, -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
resize(len - 1);
len = WideCharToMultiByte(CP_ACP, 0, lpwstr, -1, data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
}
#endif
std::string explicit_string(DWORD CodePage = CP_ACP) const {
#if defined(_UNICODE) || defined(UNICODE)
std::string str;
auto len = WideCharToMultiByte(CodePage, 0, c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
str.resize(static_cast<size_t>(len) - 1);
len = WideCharToMultiByte(CodePage, 0, c_str(), -1, str.data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
return str;
#else
if (CodePage == CP_ACP || CodePage == GetACP()) {
return *this;
} else {
std::string str;
std::wstring wstr;
auto len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
len = WideCharToMultiByte(CodePage, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
str.resize(len - 1);
len = WideCharToMultiByte(CodePage, 0, wstr.c_str(), -1, str.data(), len, NULL, NULL);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
return str;
}
#endif
}
std::wstring explicit_wstring() const {
#if defined(_UNICODE) || defined(UNICODE)
return *this;
#else
std::wstring wstr;
auto len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, NULL, 0);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
wstr.resize(len - 1);
len = MultiByteToWideChar(CP_ACP, 0, c_str(), -1, wstr.data(), len);
if (len == 0) {
auto err = GetLastError();
throw std::system_error(err, std::system_category());
}
return wstr;
#endif
}
template<typename... __Ts>
static xstring format(const xstring& Format, __Ts&&... Args) {
xstring s;
auto len = _sctprintf(Format.c_str(), std::forward<__Ts>(Args)...);
if (len == -1) {
throw std::invalid_argument("_sctprintf failed.");
}
s.resize(len);
_sntprintf_s(s.data(), s.length() + 1, _TRUNCATE, Format.c_str(), std::forward<__Ts>(Args)...);
return s;
}
template<typename... __Ts>
static xstring format(PCTSTR lpszFormat, __Ts&& ... Args) {
xstring s;
auto len = _sctprintf(lpszFormat, std::forward<__Ts>(Args)...);
if (len == -1) {
throw std::invalid_argument("_sctprintf failed.");
}
s.resize(len);
_sntprintf_s(s.data(), s.length() + 1, _TRUNCATE, lpszFormat, std::forward<__Ts>(Args)...);
return s;
}
};
}
@@ -1,6 +1,6 @@
# Navicat keygen - How does it work?
# Navicat Keygen - How does it work?
[中文版 How does it work?](HOW_DOES_IT_WORK.zh-CN.md)
[中文版](how-does-it-work.zh-CN.md)
## 1. Keyword Explanation.
@@ -8,7 +8,7 @@
It is a __RSA-2048__ public key that Navicat used to encrypt or decrypt offline activation information.
It is stored in __navicat.exe__ as a kind of resource called __RCData__. The resource name is `"ACTIVATIONPUBKEY"`. You can see it by a kind of software [___Resource Hacker___](http://www.angusj.com/resourcehacker/). The public key is
It is stored in __navicat.exe__ as a kind of resource called __RCData__. The resource name is `"ACTIVATIONPUBKEY"`. You can see it by a software called [___Resource Hacker___](http://www.angusj.com/resourcehacker/). The public key is
```
-----BEGIN PUBLIC KEY-----
@@ -26,7 +26,7 @@
__NOTICE:__
Start from __Navicat Premium 12.0.25__, Navicat do not load this public key from resource in `navicat.exe`. Instead, the public key is stored in `libcc.dll` and bas been encrypted. To avoid being replaced easily, the public key is split into 5 parts:
Start from __Navicat Premium 12.0.25__, Navicat do not load this public key from resource in `navicat.exe`. Instead, the public key is stored in `libcc.dll` and has been encrypted. To avoid being replaced easily, the public key is split into 5 parts:
The following content is discovered from `libcc.dll` of __Navicat Premium x64 12.0.25 Simplified Chinese version__. The SHA256 value of `libcc.dll` is `607e0a84c75966b00f3d12fa833e91d159e4f51ac51b6ba66f98d0c3cbefdce0`.
@@ -96,9 +96,7 @@
Then output encrypted public key with format `"%s%d%s%d%s"`. The order is the same as it lists:
```
D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933
```
This encrypted public key can be decrypted by my another repo: [how-does-navicat-encrypt-password](https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password), while the key used is `b'23970790'`.
@@ -126,9 +124,37 @@
-----END PUBLIC KEY-----
```
__NOTICE:__
Start from __Navicat Premium 12.1.11__, Navicat do not load the public key through the method I talked before. Of course, the public key is still stored in `libcc.dll`. When Navicat starts, it encrypts the public key by an 8-bytes-long XOR key and stores the ciphertext in static area. When verifing __Activation Code__, Navicat will regenerate the 8-bytes-long XOR key and decrypts the ciphertext in static area to get the public key.
In `libcc.dll`, x64 version, you can find some instructions that looks like:
```asm
xor eax, 'M'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'B'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'j'
mov byte_xxxxxx, al
...
...
```
* __Request Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the cipher text of __Offline Activation Information__ encrypted by __Navicat Activation Public Key__.
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the cipher text of __Offline Activation Request Information__ encrypted by __Navicat Activation Public Key__.
* __Offline Activation Request Information__
@@ -1,4 +1,4 @@
# Navicat keygen - 注册机是怎么工作的?
# Navicat Keygen - 注册机是怎么工作的?
## 1. 关键词解释.
@@ -122,6 +122,34 @@
-----END PUBLIC KEY-----
```
__注意:__
__Navicat Premium 12.1.11__ 开始,Navicat不再用上面说的方法加载密钥。当然密钥还是储存在`libcc.dll`文件中。当Navicat启动时,它会用8字节长的XOR密钥来加密公钥,并储存到一个静态数据区中。当验证 __激活码__ 时,Navicat会重新生成一样的8字节XOR密钥,并解密在静态储存区中的密文,从而获取公钥。
`libcc.dll`,x64版本中,你会看到如下的几条指令:
```asm
xor eax, 'M'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'B'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'j'
mov byte_xxxxxx, al
...
...
```
* __请求码__
这是一个Base64编码的字符串,代表的是长度为256字节的数据。这256字节的数据是 __离线激活信息____Navicat激活公钥__ 加密的密文。
+52
View File
@@ -0,0 +1,52 @@
# Navicat Keygen - How to build?
[中文版](how-to-build.zh-CN.md)
## 1. Prerequisites
1. Please make sure that you have __Visual Studio 2019__ or the higher. Because this is a VS2019 project.
2. Please make sure you have installed `vcpkg` and the following libraries:
* `capstone[x86]:x64-windows-static`
* `capstone[x86]:x86-windows-static`
* `openssl-windows:x64-windows-static`
* `openssl-windows:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
is installed.
You can install them by:
```console
$ vcpkg install capstone[x86]:x64-windows-static
$ vcpkg install capstone[x86]:x86-windows-static
$ vcpkg install openssl-windows:x64-windows-static
$ vcpkg install openssl-windows:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
```
3. Your `vcpkg` has been integrated into your __Visual Studio__, which means you have run
```console
$ vcpkg integrate install
```
successfully.
## 2. Build
1. Open this project in __Visual Studio__.
2. Select `Release` configuration.
3. Select `Win32` to build keygen/patcher for 32-bits Navicat.
Or select `x64` to build keygen/patcher for 64-bits Navicat.
4. Select __Build > Build Solution__.
You will see executable files in `bin/` directory.
+46
View File
@@ -0,0 +1,46 @@
# Navicat Keygen - 如何编译?
## 1. 前提条件
1. 请确保你有 __Visual Studio 2019__ 或者更高版本。因为这是一个VS2019项目。
2. 请确保你安装了 `vcpkg` 以及下面几个库:
* `capstone[x86]:x64-windows-static`
* `capstone[x86]:x86-windows-static`
* `openssl-windows:x64-windows-static`
* `openssl-windows:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
你可以通过下面的命令来安装它们:
```console
$ vcpkg install capstone[x86]:x64-windows-static
$ vcpkg install capstone[x86]:x86-windows-static
$ vcpkg install openssl-windows:x64-windows-static
$ vcpkg install openssl-windows:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
```
3. 你的 `vcpkg` 已经和你的 __Visual Studio__ 集成了,即你曾成功运行了:
```console
$ vcpkg integrate install
```
## 2. 编译
1. 在 __Visual Studio__ 打开这个项目。
2. 选择 `Release` 配置。
3. 选择 `Win32` 来生成供32位Navicat使用的keygen/patcher。
或者选择 `x64` 来生成供64位Navicat使用的keygen/patcher。
4. 选择 __生成 > 生成解决方案__。
生成完成后,你会在 `bin/` 文件夹下看到编译后的keygen/patcher。
+257
View File
@@ -0,0 +1,257 @@
# Navicat Keygen - How to use? (Linux)
[中文版](how-to-use.linux.zh-CN.md)
* Maintainer(s): zenuo, DoubleLabyrinth
---
> You can download [Screen recoding](image/Screen_recording.mp4) for references.
1. Switch to the path you extracted the installation package. Run Navicat, for initialization:
```console
$ cd ~/navicat121_premium_en_x64 && \
./start_navicat
```
When running for the first time, you will be prompted with the following two windows, click "Cancel" to:
![](image/Screenshot_2019-04-30_12-31-33.png)
![](image/Screenshot_2019-04-30_12-31-52.png)
Until the `Registration` window appears, select `Trial`, close Navicat after loading is complete, and execute `Step 2`:
![](image/Screenshot_2019-04-30_12-32-43.png)
2. Download the latest release [from here](https://github.com/DoubleLabyrinth/navicat-keygen/releases), and extract:
> The 64-bit executable file is downloaded here. If you use 32-bit, please download the corresponding version.
```console
$ curl -O -L https://github.com/DoubleLabyrinth/navicat-keygen/releases/latest/download/navicat-keygen-for-x64.zip && \
unzip navicat-keygen-for-x64.zip
```
3. Download `navicat-pacther.sh` and `navicat-keygen.sh`:
```console
$ curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-patcher.sh && \
chmod +x navicat-patcher.sh && \
curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-keygen.sh && \
chmod +x navicat-keygen.sh
```
4. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `navicat.exe` or `libcc.dll`.
> Please turn off `Navicat` when performing this step.
```console
$ ./navicat-patcher.sh
```
It has been tested on __Navicat Premium 12.1.22 Simplified Chinese version__. The following is an example of output:
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
5. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```console
$ ./navicat-keygen.sh
```
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
6. __Set up__ a invalid proxy. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
7. Online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
8. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
9. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully. Don't forget to close the proxy that we just set up.
+255
View File
@@ -0,0 +1,255 @@
# Navicat Keygen - 如何使用这个注册机? (Linux)
* 维护者:zenuo, DoubleLabyrinth
---
> 可下载[录屏文件](image/Screen_recording.mp4)参考
1. 切换到解压安装包的路径,本示例解压到了 `家目录`,运行Navicat,使其初始化环境:
```console
$ cd ~/navicat121_premium_en_x64 && \
./start_navicat
```
首次启动时,会提示如下两个窗口,点击“Cancel”即可:
![](image/Screenshot_2019-04-30_12-31-33.png)
![](image/Screenshot_2019-04-30_12-31-52.png)
直至出现 `Registration` 窗口,选择 `Trial`,待加载完成后关闭Navicat,执行 `步骤2`
![](image/Screenshot_2019-04-30_12-32-43.png)
2. [从这里](https://github.com/DoubleLabyrinth/navicat-keygen/releases)下载最新的release,并且解压:
> 此处下载的是64位的可执行文件,若您使用32位,请下载对应版本
```console
$ curl -O -L https://github.com/DoubleLabyrinth/navicat-keygen/releases/latest/download/navicat-keygen-for-x64.zip && \
unzip navicat-keygen-for-x64.zip
```
3. 下载 `navicat-pacther.sh` 和 `navicat-keygen.sh`
```console
$ curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-patcher.sh && \
chmod +x navicat-patcher.sh && \
curl -O -L https://raw.githubusercontent.com/DoubleLabyrinth/navicat-keygen/windows/bash/navicat-keygen.sh && \
chmod +x navicat-keygen.sh
```
4. 使用 `navicat-patcher.exe` 替换掉 `navicat.exe` 和 `libcc.dll` 里的Navicat激活公钥。
> 执行此步骤时,请将Navicat关闭
```console
$ ./navicat-patcher.sh
```
__Navicat Premium 12.1.22 简体中文版已通过测试__。下面将是一份样例输出:
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
5. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```console
$ ./navicat-keygen.sh
```
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号。
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
你可以使用这个序列号暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
6. 配置一个不存在的`代理`。找到`注册`窗口,并填入keygen给你的序列号。然后点击`激活`按钮。
7. 在线激活失败,这时候Navicat会询问你是否`手动激活`,直接选吧。
8. 在`手动激活`窗口你会得到一个请求码,复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
9. 如果不出意外,你会得到一个看似用Base64编码的激活码。直接复制它,并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。别忘了关闭我们刚刚设置的不存在的代理哦。
+256
View File
@@ -0,0 +1,256 @@
# Navicat Keygen - How to use? (Windows)
[中文版](how-to-use.windows.zh-CN.md)
1. Download the latest release [from here](https://github.com/DoubleLabyrinth/navicat-keygen/releases).
2. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `navicat.exe` or `libcc.dll`.
```
navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]` Run patcher without applying any patches.
__This parameter is optional.__
* `<Navicat Installation Path>`: The full path to Navicat installation folder.
__This parameter must be specified.__
* `[RSA-2048 PEM File Path]`: The full path or relative path to a RSA-2048 private key file.
__This parameter is optional.__ If not specified, `navicat-patcher.exe` will generate a new RSA-2048 private key file `RegPrivateKey.pem` at current directory.
__Example: (in cmd.exe)__
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 12"
```
It has been tested on __Navicat Premium 12.1.22 Simplified Chinese version__. The following is an example of output.
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
3. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>
```
* `<-bin|-text>`: Must be `-bin` or `-text`.
If `-bin` is specified, `navicat-keygen.exe` will finally generate `license_file`. It is used for Navicat old activation method only.
If `-text` is specified, `navicat-keygen.exe` will finally generate a Base64-style string which is __Activation Code__. It is used for Navicat new activation method.
__This parameter must be specified.__
* `[-adv]`: Enable advanced mode.
__This parameter is optional.__ If specified, `navicat-keygen.exe` will ask you input Navicat product ID number, language signature numbers. It is for future use generally.
* `<RSA-2048 PrivateKey(PEM file)>`: The full path or relative path to a RSA-2048 private key file.
__This parameter must be specified.__
__Example: (in cmd.exe)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
4. __Disconnect your network__ and open Navicat. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
5. Generally online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
6. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
7. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully.
+254
View File
@@ -0,0 +1,254 @@
# Navicat Keygen - 如何使用这个注册机? (Windows)
1. [从这里](https://github.com/DoubleLabyrinth/navicat-keygen/releases)下载最新的release。
2. 使用`navicat-patcher.exe`替换掉`navicat.exe``libcc.dll`里的Navicat激活公钥。
```
navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]`: 运行patcher但不对Navicat程序做任何修改。
__这个参数是可选的。__
* `<Navicat Installation Path>`: Navicat的完整安装路径。
__这个参数必须指定。__
* `[RSA-2048 PEM File Path]`: RSA-2048私钥文件的完整路径或相对路径。
__这个参数是可选的。__ 如果未指定,`navicat-patcher.exe`将会在当前目录生成一个新的RSA-2048私钥文件。
__例如:(在cmd.exe中)__
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 12"
```
__Navicat Premium 12.1.22 简体中文版已通过测试__。下面将是一份样例输出:
```
***************************************************
* Navicat Patcher by @DoubleLabyrinth *
* Version: 4.0 *
***************************************************
Press Enter to continue or Ctrl + C to abort.
[+] Try to open Navicat.exe ... Ok!
[+] Try to open libcc.dll ... Ok!
[+] PatchSolution0 ...... Ready to apply
[*] Patch offset = +0x029bccd8
[+] PatchSolution1 ...... Ready to apply
[*] [0] Patch offset = +0x02206c00
[*] [1] Patch offset = +0x0074c489
[*] [2] Patch offset = +0x02206910
[*] [3] Patch offset = +0x0074c46f
[*] [4] Patch offset = +0x02206904
[-] PatchSolution2 ...... Omitted
[+] PatchSolution3 ...... Ready to apply
[*] [ 0] Instruction RVA = 0x016539c8, Patch Offset = +0x023e64d4
[*] [ 1] Instruction RVA = 0x01653a1f, Patch Offset = +0x01652e23
[*] [ 2] Instruction RVA = 0x01653a25, Patch Offset = +0x01652e28
[*] [ 3] Instruction RVA = 0x01653a8c, Patch Offset = +0x01652e8e
...
...
...
[*] [108] Instruction RVA = 0x016604e1, Patch Offset = +0x023e66d8
[*] [109] Instruction RVA = 0x01660518, Patch Offset = +0x0165f91c
[*] [110] Instruction RVA = 0x0166051e, Patch Offset = +0x0165f921
[*] PatchSolution0 is suppressed in order to keep digital signature valid.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA public key:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1hV66HgU4LrKXWW6O7bK
AN6ZTr5W+Mq8ClTQ+Pc+BdhLu6rww55kVq7OXKGpvx0G4eTafYMGrrBETgDSTaMq
Bx+8bZbGBWh2LtNfqU+xUrpHHBSz0ByBc3iTEzzthJl+Fzf8suDX2lWYIc/Ym/eW
YtxdJ7xOzLb68z4N0zVmA0jFX2FOm75DRYgKqy4SGixapfucL9dVaWVLTUdbrVdj
4LX78t4t5ykbYoThrat4yuLvj/BxLaQ6ivKD+ScfHdtCoY+NA5jmBoUfBq3Q1SXB
iNaoXctbi0/H3MiPu0cRojryAocooF89yFm5/mNnzWGAYPr6DvBI8CDTZmjaQ4oC
aQIDAQAB
-----END PUBLIC KEY-----
*******************************************************
* PatchSolution1 *
*******************************************************
[*] Previous:
+0x0000000002206c00 44 37 35 31 32 35 42 37 30 37 36 37 42 39 34 31 D75125B70767B941
+0x0000000002206c10 34 35 42 34 37 43 31 43 42 33 43 30 37 35 35 45 45B47C1CB3C0755E
+0x0000000002206c20 37 43 43 42 38 38 32 35 43 35 44 43 45 30 43 35 7CCB8825C5DCE0C5
...
...
[*] After:
+0x0000000002206c00 33 43 32 39 30 39 35 38 33 34 38 41 42 43 35 39 3C290958348ABC59
+0x0000000002206c10 36 44 39 30 43 45 45 38 31 36 42 36 39 38 34 44 6D90CEE816B6984D
+0x0000000002206c20 35 32 35 34 37 45 30 32 34 31 42 36 42 43 31 41 52547E0241B6BC1A
...
...
[*] Previous:
+0x000000000074c480 fe ea bc 01 ....
[*] After:
+0x000000000074c480 08 00 00 00 ....
[*] Previous:
+0x0000000002206910 45 31 43 45 44 30 39 42 39 43 32 31 38 36 42 46 E1CED09B9C2186BF
+0x0000000002206920 37 31 41 37 30 43 30 46 45 32 46 31 45 30 41 45 71A70C0FE2F1E0AE
+0x0000000002206930 46 33 42 44 36 42 37 35 32 37 37 41 41 42 32 30 F3BD6B75277AAB20
...
...
[*] After:
+0x0000000002206910 41 33 39 42 41 36 43 34 31 36 33 32 35 30 46 45 A39BA6C4163250FE
+0x0000000002206920 42 32 41 39 31 41 34 32 46 44 42 46 30 41 32 31 B2A91A42FDBF0A21
+0x0000000002206930 33 34 46 34 36 44 43 45 34 30 42 46 41 42 33 35 34F46DCE40BFAB35
...
...
[*] Previous:
+0x000000000074c460 59 Y
+0x000000000074c470 08 01 00 ...
[*] After:
+0x000000000074c460 06 .
+0x000000000074c470 00 00 00 ...
[*] Previous:
+0x0000000002206900 39 32 39 33 33 92933
[*] After:
+0x0000000002206900 42 34 34 33 38 B4438
*******************************************************
* PatchSolution3 *
*******************************************************
[*] +023e64d4: 4d 49 49 ---> 4d 49 49
[*] +01652e23: 42 49 ---> 42 49
[*] +01652e28: 6a ---> 6a
...
...
...
[*] +023e66d8: 77 49 44 41 ---> 51 49 44 41
[*] +0165f91c: 51 41 ---> 51 41
[*] +0165f921: 42 ---> 42
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\github.com\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
3. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>
```
* `<-bin|-text>`: 必须是`-bin`或`-text`。
如果指定了`-bin``navicat-keygen.exe`最终将生成`license_file`文件。这个选项是给Navicat旧激活方式使用的。
如果指定了`-text``navicat-keygen.exe`最终将生成Base64样式的激活码。这个选项是给Navicat新激活方式使用的。
__这个参数必须指定。__
* `[-adv]`: 开启高级模式。
__这个参数是可选的。__ 如果指定了这个参数,`navicat-keygen.exe`将会要求你手工填写产品ID号、语言标识号。这个选项一般是给以后用的。
* `<RSA-2048 PrivateKey(PEM file)>`: RSA-2048私钥文件的完整路径或相对路径。
__这个参数必须指定。__
__例如:(在cmd.exe中)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号。
```
Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 1
(Input major version number, range: 0 ~ 15, default: 12)> 12
Serial number:
NAVO-2ORP-IN5A-GQEE
Your name:
```
你可以使用这个序列号暂时激活Navicat。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
4. __断开网络__ 并打开Navicat。找到`注册`窗口,并填入keygen给你的序列号。然后点击`激活`按钮。
5. 一般来说在线激活肯定会失败,这时候Navicat会询问你是否`手动激活`,直接选吧。
6. 在`手动激活`窗口你会得到一个请求码,复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```
Your name: DoubleLabyrinth
Your organization: DoubleLabyrinth
Input request code (in Base64), input empty line to end:
t2U+0yfE2FfnbjyhCXa0lglZOHu9Ntc3qyGiPbR6xb1QoU63/9BVfdaCq0blwVycXPyT/Vqw5joIKdM5oCRR/afCPM7iRcyhQMAnvqwc+AOKCqayVV+SqKLvtR/AbREI12w++PQ6Ewfs4A8PgB8OJ9G0jKt6Q/iJRblqi2WWw9mwy+YHcYYh3UAfygTnyj/xl+MzRymbY0lkus+6LPtpDecVsFFhM7F32Ee1QPwISko7bAkHOtkt+joPfYDdn9PDGZ4HEmeLvH6UqZCXkzgaAfynB7cQZFEkId8FsW2NGkbpM7wB2Hi3fNFgOIjutTprixTdbpFKn4w6gGc28ve23A==
Request Info:
{"K":"NAVO2ORPIN5AGQEE", "DI":"R91j6WyMhxHznAKSxxxx", "P":"WIN"}
Response Info:
{"K":"NAVO2ORPIN5AGQEE","DI":"R91j6WyMhxHznAKSxxxx","N":"DoubleLabyrinth","O":"DoubleLabyrinth","T":1547826060}
License:
lRF18o+ZhBphyN0U5kFLHtAAGGXuvhqOcxNuvAk4dJcGeR0ISuw74mQvAfdNjv0T
I5NZFzqIJvrzM0XeR88q+3kmZkECuxwwWHP3zzDPhPiylcTV4DoGZ1tfoViUSYQc
LgXG0Fl7koZeP61YOKQ8GfX+Xk2ZTM64bYaF7NlhonM+GQUJCCF2JThmrP921t2p
b/E5pV6fLOYMM13881ZQcQcltMNVDZn4lzgzKRFFxCQFaTl6fJMHZdYVmICQTHtI
sNaym0zduc8/cv34mgJ+7NseXmsEPCdjrZ59wgfPsLhZLXqtfxi5hGWw4NMa3Sb2
UI8dzqFzRp/hSDEM0mEqiA==
```
4. 如果不出意外,你会得到一个看似用Base64编码的激活码。直接复制它,并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+30 -20
View File
@@ -1,13 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-keygen", "navicat-keygen\navicat-keygen.vcxproj", "{CB49F054-83AB-4C16-B73B-33D7DF696E16}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-keygen", "navicat-keygen\navicat-keygen.vcxproj", "{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-patcher", "navicat-patcher\navicat-patcher.vcxproj", "{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-patcher", "navicat-patcher\navicat-patcher.vcxproj", "{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "common", "common\common.vcxitems", "{290C5D5E-52D2-4FEF-909F-27FD95AE0AF9}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
common\common.vcxitems*{290c5d5e-52d2-4fef-909f-27fd95ae0af9}*SharedItemsImports = 9
common\common.vcxitems*{7ee03ef3-d58d-4b53-913d-4a4dc8a29e34}*SharedItemsImports = 4
common\common.vcxitems*{ba201764-eecf-4da8-bcad-7cfba301fc9c}*SharedItemsImports = 4
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
@@ -15,24 +22,27 @@ Global
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x64.ActiveCfg = Debug|x64
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x64.Build.0 = Debug|x64
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x86.ActiveCfg = Debug|Win32
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Debug|x86.Build.0 = Debug|Win32
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x64.ActiveCfg = Release|x64
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x64.Build.0 = Release|x64
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x86.ActiveCfg = Release|Win32
{CB49F054-83AB-4C16-B73B-33D7DF696E16}.Release|x86.Build.0 = Release|Win32
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x64.ActiveCfg = Debug|x64
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x64.Build.0 = Debug|x64
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x86.ActiveCfg = Debug|Win32
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Debug|x86.Build.0 = Debug|Win32
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x64.ActiveCfg = Release|x64
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x64.Build.0 = Release|x64
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x86.ActiveCfg = Release|Win32
{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}.Release|x86.Build.0 = Release|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x64.ActiveCfg = Debug|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x64.Build.0 = Debug|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x86.ActiveCfg = Debug|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Debug|x86.Build.0 = Debug|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x64.ActiveCfg = Release|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x64.Build.0 = Release|x64
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x86.ActiveCfg = Release|Win32
{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}.Release|x86.Build.0 = Release|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x64.ActiveCfg = Debug|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x64.Build.0 = Debug|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x86.ActiveCfg = Debug|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Debug|x86.Build.0 = Debug|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x64.ActiveCfg = Release|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x64.Build.0 = Release|x64
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x86.ActiveCfg = Release|Win32
{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {CB1D6B65-6AEA-44E4-8698-0AEBDBC63CD2}
EndGlobalSection
EndGlobal
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include <Exception.hpp>
#include <ExceptionWin32.hpp>
#include <xstring.hpp>
#include <bytearray.hpp>
#include <wincrypt.h>
#pragma comment(lib, "Crypt32")
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\Base64.hpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
std::xstring Base64Encode(const std::bytearray& Bytes) {
if (Bytes.empty()) {
return std::xstring();
} else {
DWORD cchBase64String = 0;
std::xstring Base64String;
auto bResult = CryptBinaryToString(
Bytes.data(),
static_cast<DWORD>(Bytes.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
NULL,
&cchBase64String
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptBinaryToString failed."));
}
Base64String.resize(cchBase64String - 1);
bResult = CryptBinaryToString(
Bytes.data(),
static_cast<DWORD>(Bytes.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF,
Base64String.data(),
&cchBase64String
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptBinaryToString failed."));
}
return Base64String;
}
}
std::bytearray Base64Decode(const std::xstring& Base64String) {
if (Base64String.empty()) {
return std::bytearray();
} else {
DWORD cbBytes = 0;
std::bytearray Bytes;
auto bResult = CryptStringToBinary(
Base64String.c_str(),
NULL,
CRYPT_STRING_BASE64,
NULL,
&cbBytes,
NULL,
NULL
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptStringToBinary failed."))
.AddHint(TEXT("Are you sure it is a Base64 string?"));
}
Bytes.resize(cbBytes);
bResult = CryptStringToBinary(
Base64String.c_str(),
NULL,
CRYPT_STRING_BASE64,
Bytes.data(),
&cbBytes,
NULL,
NULL
);
if (bResult == FALSE) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CryptStringToBinary failed."));
}
return Bytes;
}
}
}
+152
View File
@@ -0,0 +1,152 @@
#include "SerialNumberGenerator.hpp"
#include <ExceptionUser.hpp>
#include <iostream>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\CollectInformation.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace std {
#if defined(_UNICODE) || defined(UNICODE)
static auto& xcin = wcin;
static auto& xcout = wcout;
static auto& xcerr = wcerr;
#else
static auto& xcin = cin;
static auto& xcout = cout;
static auto& xcerr = cerr;
#endif
}
namespace nkg {
[[nodiscard]]
static int ReadInt(int MinVal, int MaxVal, PCTSTR lpszPrompt, PCTSTR lpszErrorMessage) {
int val;
std::xstring s;
while (true) {
std::xcout << lpszPrompt;
if (!std::getline(std::xcin, s)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
}
if (s.empty())
continue;
try {
val = std::stoi(s, nullptr, 0);
if (MinVal <= val && val <= MaxVal) {
return val;
} else {
throw std::invalid_argument("");
}
} catch (std::invalid_argument&) {
std::xcout << lpszErrorMessage << std::endl;
}
}
}
[[nodiscard]]
static int ReadInt(int MinVal, int MaxVal, int DefaultVal, PCTSTR lpszPrompt, PCTSTR lpszErrorMessage) {
int val;
std::xstring s;
while (true) {
std::xcout << lpszPrompt;
if (!std::getline(std::xcin, s)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
}
if (s.empty()) {
return DefaultVal;
}
try {
val = std::stoi(s, nullptr, 0);
if (MinVal <= val && val <= MaxVal) {
return val;
} else {
throw std::invalid_argument("");
}
} catch (std::invalid_argument&) {
std::xcout << lpszErrorMessage << std::endl;
}
}
}
[[nodiscard]]
SerialNumberGenerator CollectInformationNormal() {
SerialNumberGenerator Generator;
std::xcout << TEXT("[*] Select Navicat product:") << std::endl;
std::xcout << TEXT(" 0. DataModeler") << std::endl;
std::xcout << TEXT(" 1. Premium") << std::endl;
std::xcout << TEXT(" 2. MySQL") << std::endl;
std::xcout << TEXT(" 3. PostgreSQL") << std::endl;
std::xcout << TEXT(" 4. Oracle") << std::endl;
std::xcout << TEXT(" 5. SQLServer") << std::endl;
std::xcout << TEXT(" 6. SQLite") << std::endl;
std::xcout << TEXT(" 7. MariaDB") << std::endl;
std::xcout << TEXT(" 8. MongoDB") << std::endl;
std::xcout << TEXT(" 9. ReportViewer") << std::endl;
std::xcout << std::endl;
Generator.SetProductSignature(
static_cast<NavicatProductType>(ReadInt(0, 9, TEXT("(Input index)> "), TEXT("Invalid index.")))
);
std::xcout << std::endl;
std::xcout << TEXT("[*] Select product language:") << std::endl;
std::xcout << TEXT(" 0. English") << std::endl;
std::xcout << TEXT(" 1. Simplified Chinese") << std::endl;
std::xcout << TEXT(" 2. Traditional Chinese") << std::endl;
std::xcout << TEXT(" 3. Japanese") << std::endl;
std::xcout << TEXT(" 4. Polish") << std::endl;
std::xcout << TEXT(" 5. Spanish") << std::endl;
std::xcout << TEXT(" 6. French") << std::endl;
std::xcout << TEXT(" 7. German") << std::endl;
std::xcout << TEXT(" 8. Korean") << std::endl;
std::xcout << TEXT(" 9. Russian") << std::endl;
std::xcout << TEXT(" 10. Portuguese") << std::endl;
std::xcout << std::endl;
Generator.SetLanguageSignature(
static_cast<NavicatLanguage>(ReadInt(0, 10, TEXT("(Input index)> "), TEXT("Invalid index.")))
);
std::xcout << std::endl;
std::xcout << TEXT("[*] Input major version number:") << std::endl;
Generator.SetVersion(
static_cast<BYTE>(ReadInt(0, 15, 12, TEXT("(range: 0 ~ 15, default: 12)> "), TEXT("Invalid number.")))
);
std::xcout << std::endl;
return Generator;
}
[[nodiscard]]
SerialNumberGenerator CollectInformationAdvanced() {
SerialNumberGenerator Generator;
std::xcout << TEXT("[*] Navicat Product Signature:") << std::endl;
Generator.SetProductSignature(
static_cast<BYTE>(ReadInt(0x00, 0xff, TEXT("(range: 0x00 ~ 0xFF)> "), TEXT("Invalid number.")))
);
std::xcout << std::endl;
std::xcout << TEXT("[*] Navicat Language Signature 0:") << std::endl;
auto s1 = static_cast<BYTE>(ReadInt(0x00, 0xff, TEXT("(range: 0x00 ~ 0xFF)> "), TEXT("Invalid number.")));
std::xcout << std::endl;
std::xcout << TEXT("[*] Navicat Language Signature 1:") << std::endl;
auto s2 = static_cast<BYTE>(ReadInt(0x00, 0xff, TEXT("(range: 0x00 ~ 0xFF)> "), TEXT("Invalid number.")));
Generator.SetLanguageSignature(s1, s2);
std::xcout << std::endl;
std::xcout << TEXT("[*] Input major version number:") << std::endl;
Generator.SetVersion(
static_cast<BYTE>(ReadInt(0, 15, 12, TEXT("(range: 0 ~ 15, default: 12)> "), TEXT("Invalid number.")))
);
std::xcout << std::endl;
return Generator;
}
}
+241
View File
@@ -0,0 +1,241 @@
#include <ExceptionUser.hpp>
#include <ResourceOwned.hpp>
#include <ResourceTraitsWin32.hpp>
#include <xstring.hpp>
#include <bytearray.hpp>
#include <RSACipher.hpp>
#include "Base64.hpp"
#include "SerialNumberGenerator.hpp"
#include <iostream>
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\GenerateLicense.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace std {
#if defined(_UNICODE) || defined(UNICODE)
static auto & xcin = wcin;
static auto& xcout = wcout;
static auto& xcerr = wcerr;
#else
static auto& xcin = cin;
static auto& xcout = cout;
static auto& xcerr = cerr;
#endif
}
namespace nkg {
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator) {
std::xstring username;
std::xstring organization;
std::string utf8username;
std::string utf8organization;
std::xstring b64RequestCode;
std::bytearray RequestCode;
std::string utf8RequestInfo;
std::string utf8ResponseInfo;
std::bytearray ResponseCode;
std::xstring b64ResponseCode;
std::xcout << TEXT("[*] Your name: ");
if (!std::getline(std::xcin, username)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8username = username.explicit_string(CP_UTF8);
}
std::xcout << TEXT("[*] Your organization: ");
if (!std::getline(std::xcin, organization)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8organization = organization.explicit_string(CP_UTF8);
}
std::xcout << TEXT("[*] Input request code in Base64: (Input empty line to end)") << std::endl;
while (true) {
std::xstring temp;
if (!std::getline(std::xcin, temp)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
}
if (temp.empty()) {
break;
}
b64RequestCode.append(temp);
}
RequestCode = Base64Decode(b64RequestCode);
utf8RequestInfo.resize((Cipher.Bits() + 7) / 8);
Cipher.Decrypt(RequestCode.data(), RequestCode.size(), utf8RequestInfo.data(), RSA_PKCS1_PADDING);
while (utf8RequestInfo.back() == '\x00') {
utf8RequestInfo.pop_back();
}
std::xcout << TEXT("[*] Request Info:") << std::endl;
std::xcout << std::xstring(std::xstring_extension{}, utf8RequestInfo, CP_UTF8) << std::endl;
std::xcout << std::endl;
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//
// Begin to parse
//
json.Parse(utf8RequestInfo.c_str());
//
// Remove "Platform" info
//
json.RemoveMember("P");
//
// Set "Name" info
//
N_Key.SetString("N", 1);
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
//
// Set "Organization" info
//
O_Key.SetString("O", 1);
O_Value.SetString(utf8organization.c_str(), static_cast<rapidjson::SizeType>(utf8organization.length()));
//
// Set "Time" info
//
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
//
// Add "Name", "Organization" and "Time"
//
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Response info is too long."));
}
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
std::xcout << TEXT("[*] Response Info:") << std::endl;
std::xcout << std::xstring(std::xstring_extension{}, utf8ResponseInfo, CP_UTF8) << std::endl;
std::xcout << std::endl;
ResponseCode.resize((Cipher.Bits() + 7) / 8);
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
b64ResponseCode = Base64Encode(ResponseCode);
std::xcout << TEXT("[*] Activation Code:") << std::endl;
std::xcout << b64ResponseCode << std::endl;
std::xcout << std::endl;
}
void GenerateLicenseBinary(const RSACipher& Cipher, const SerialNumberGenerator& Generator) {
ResourceOwned hLicenseFile(FileHandleTraits{});
std::string utf8SerialNumber = Generator.GetSerialNumberShort().explicit_string(CP_UTF8);
std::xstring username;
std::xstring organization;
std::string utf8username;
std::string utf8organization;
std::string utf8ResponseInfo;
std::bytearray ResponseCode;
std::xcout << TEXT("[*] Your name: ");
if (!std::getline(std::xcin, username)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8username = username.explicit_string(CP_UTF8);
}
std::xcout << TEXT("[*] Your organization: ");
if (!std::getline(std::xcin, organization)) {
throw UserAbortionError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Abort."));
} else {
utf8organization = organization.explicit_string(CP_UTF8);
}
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::Value K_Key;
rapidjson::Value K_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Parse("{}");
K_Key.SetString("K", 1);
K_Value.SetString(utf8SerialNumber.c_str(), static_cast<rapidjson::SizeType>(utf8SerialNumber.length()));
N_Key.SetString("N", 1);
N_Value.SetString(utf8username.c_str(), static_cast<rapidjson::SizeType>(utf8username.length()));
O_Key.SetString("O", 1);
O_Value.SetString(utf8organization.c_str(), static_cast<rapidjson::SizeType>(utf8organization.length()));
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
json.AddMember(K_Key, K_Value, json.GetAllocator());
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Response info is too long."));
}
utf8ResponseInfo.assign(buffer.GetString(), buffer.GetSize());
std::xcout << TEXT("[*] Response Info:") << std::endl;
std::xcout << std::xstring(std::xstring_extension{}, utf8ResponseInfo, CP_UTF8) << std::endl;
std::xcout << std::endl;
ResponseCode.resize((Cipher.Bits() + 7) / 8);
Cipher.Encrypt<RSAKeyType::PrivateKey>(utf8ResponseInfo.data(), utf8ResponseInfo.size(), ResponseCode.data(), RSA_PKCS1_PADDING);
hLicenseFile.TakeOver(
CreateFile(
TEXT("license_file"),
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL
)
);
if (hLicenseFile.IsValid() == false) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFile failed."));
}
DWORD NumberOfBytesWritten;
if (!WriteFile(hLicenseFile, ResponseCode.data(), static_cast<DWORD>(ResponseCode.size()), &NumberOfBytesWritten, NULL)) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("WriteFile failed."));
}
std::xcout << TEXT("[+] license_file has been generated.") << std::endl;
}
}
-135
View File
@@ -1,135 +0,0 @@
#include <vector>
#include <string>
#include <windows.h>
namespace Helper {
bool ConvertToUTF8(LPCSTR from, std::string& to) {
bool bSuccess = false;
int len = 0;
LPWSTR lpUnicodeString = nullptr;
len = MultiByteToWideChar(CP_ACP, NULL, from, -1, NULL, 0);
if (len == 0)
goto ON_ConvertToUTF8_0_ERROR;
lpUnicodeString = reinterpret_cast<LPWSTR>(HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY,
len * sizeof(WCHAR)));
if (lpUnicodeString == nullptr)
goto ON_ConvertToUTF8_0_ERROR;
if (!MultiByteToWideChar(CP_ACP, NULL, from, -1, lpUnicodeString, len))
goto ON_ConvertToUTF8_0_ERROR;
len = WideCharToMultiByte(CP_UTF8, NULL, lpUnicodeString, -1, NULL, 0, NULL, NULL);
if (len == 0)
goto ON_ConvertToUTF8_0_ERROR;
to.resize(len);
if (!WideCharToMultiByte(CP_UTF8, NULL, lpUnicodeString, -1, to.data(), len, NULL, NULL))
goto ON_ConvertToUTF8_0_ERROR;
while (to.back() == 0)
to.pop_back();
bSuccess = true;
ON_ConvertToUTF8_0_ERROR:
if (lpUnicodeString)
HeapFree(GetProcessHeap(), NULL, lpUnicodeString);
return bSuccess;
}
bool ConvertToUTF8(LPCWSTR from, std::string& to) {
bool bSuccess = false;
int len = 0;
len = WideCharToMultiByte(CP_UTF8, NULL, from, -1, NULL, 0, NULL, NULL);
if (len == 0)
goto ON_ConvertToUTF8_1_ERROR;
to.resize(len);
if (!WideCharToMultiByte(CP_UTF8, NULL, from, -1, to.data(), len, NULL, NULL))
goto ON_ConvertToUTF8_1_ERROR;
while (to.back() == 0)
to.pop_back();
bSuccess = true;
ON_ConvertToUTF8_1_ERROR:
return bSuccess;
}
bool ConvertToUTF8(std::string& str) {
bool bSuccess = false;
std::string temp;
bSuccess = ConvertToUTF8(str.c_str(), temp);
if (!bSuccess)
return false;
str = temp;
return true;
}
std::string Base64Encode(const std::vector<uint8_t>& bytes) {
std::string Result;
DWORD pcchString = 0;
if (bytes.empty())
return Result;
CryptBinaryToStringA(bytes.data(),
bytes.size(),
CRYPT_STRING_BASE64,
NULL,
&pcchString);
if (pcchString == 0)
return Result;
Result.resize(pcchString + 1);
if (!CryptBinaryToStringA(bytes.data(),
bytes.size(),
CRYPT_STRING_BASE64,
Result.data(),
&pcchString))
Result.clear();
return Result;
}
std::vector<uint8_t> Base64Decode(std::string& str) {
std::vector<uint8_t> Result;
DWORD pcbBinary = 0;
if (str.empty())
return Result;
CryptStringToBinaryA(str.c_str(),
NULL,
CRYPT_STRING_BASE64,
NULL,
&pcbBinary,
NULL,
NULL);
if (pcbBinary == 0)
return Result;
Result.resize(pcbBinary);
if (!CryptStringToBinaryA(str.c_str(),
NULL,
CRYPT_STRING_BASE64,
Result.data(),
&pcbBinary,
NULL,
NULL))
Result.clear();
return Result;
}
}
-210
View File
@@ -1,210 +0,0 @@
#pragma once
#include "RSACipher.hpp"
#include <openssl/des.h>
#include <string>
#include <random>
class NavicatKeygen {
public:
enum class Language {
English,
SimplifiedChinese,
TraditionalChinese,
Japanese,
Polish,
Spanish,
French,
German,
Korean,
Russian,
Portuguese
};
enum class Product {
DataModeler,
Premium,
MySQL,
PostgreSQL,
Oracle,
SQLServer,
SQLite,
MariaDB,
MongoDB,
ReportViewer
};
private:
std::random_device rand_dev;
std::default_random_engine rand_eng;
std::uniform_int_distribution<int> rand;
uint8_t data[10];
void DoEncrypt() {
const_DES_cblock DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
DES_key_schedule schedule;
DES_cblock enc_data;
DES_set_key_unchecked(&DESKey, &schedule);
DES_ecb_encrypt(reinterpret_cast<const_DES_cblock*>(data + 2),
&enc_data,
&schedule,
DES_ENCRYPT);
memcpy(data + 2, enc_data, sizeof(enc_data));
}
public:
NavicatKeygen() : rand_eng(rand_dev()), rand(0, UINT8_MAX), data() {
data[0] = 0x68;
data[1] = 0x2A;
}
void SetLanguageSignature(Language _language) {
switch (_language) {
case Language::English:
data[5] = 0xAC; // Must be 0xAC for English version.
data[6] = 0x88; // Must be 0x88 for English version.
break;
case Language::SimplifiedChinese:
data[5] = 0xCE; // Must be 0xCE for Simplified Chinese version.
data[6] = 0x32; // Must be 0x32 for Simplified Chinese version.
break;
case Language::TraditionalChinese:
data[5] = 0xAA; // Must be 0xAA for Traditional Chinese version.
data[6] = 0x99; // Must be 0x99 for Traditional Chinese version.
break;
case Language::Japanese:
data[5] = 0xAD; // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
data[6] = 0x82; // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
break;
case Language::Polish:
data[5] = 0xBB; // Must be 0xBB for Polish version. Discoverer: @dragonflylee
data[6] = 0x55; // Must be 0x55 for Polish version. Discoverer: @dragonflylee
break;
case Language::Spanish:
data[5] = 0xAE; // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
data[6] = 0x10; // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
break;
case Language::French:
data[5] = 0xFA; // Must be 0xFA for French version. Discoverer: @Deltafox79
data[6] = 0x20; // Must be 0x20 for French version. Discoverer: @Deltafox79
break;
case Language::German:
data[5] = 0xB1; // Must be 0xB1 for German version. Discoverer: @dragonflylee
data[6] = 0x60; // Must be 0x60 for German version. Discoverer: @dragonflylee
break;
case Language::Korean:
data[5] = 0xB5; // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
data[6] = 0x60; // Must be 0x60 for Korean version. Discoverer: @dragonflylee
break;
case Language::Russian:
data[5] = 0xEE; // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
data[6] = 0x16; // Must be 0x60 for Russian version. Discoverer: @dragonflylee
break;
case Language::Portuguese:
data[5] = 0xCD; // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
break;
}
}
void SetLanguageSignature(uint8_t value0, uint8_t value1) {
data[5] = value0;
data[6] = value1;
}
void SetProductSignature(Product _product) {
switch (_product) {
case Product::DataModeler:
data[7] = 0x47;
break;
case Product::Premium:
data[7] = 0x65;
break;
case Product::MySQL:
data[7] = 0x68;
break;
case Product::PostgreSQL:
data[7] = 0x6C;
break;
case Product::Oracle:
data[7] = 0x70;
break;
case Product::SQLServer:
data[7] = 0x74;
break;
case Product::SQLite:
data[7] = 0x78;
break;
case Product::MariaDB:
data[7] = 0x7C;
break;
case Product::MongoDB:
data[7] = 0x80;
break;
case Product::ReportViewer:
data[7] = 0xb;
default:
break;
}
}
void SetProductSignature(uint8_t value) {
data[7] = value;
}
void SetVersion(uint8_t version) {
data[8] = version << 4;
}
void Generate() {
data[2] = rand(rand_eng);
data[3] = rand(rand_eng);
data[4] = rand(rand_eng);
data[9] = 0x32;
DoEncrypt();
}
std::string GetKey() const {
std::string Key;
const char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
Key.resize(16);
Key[0] = EncodeTable[data[0] >> 3];
Key[1] = EncodeTable[(data[0] & 0x07) << 2 | data[1] >> 6];
Key[2] = EncodeTable[data[1] >> 1 & 0x1F];
Key[3] = EncodeTable[(data[1] & 0x1) << 4 | data[2] >> 4];
Key[4] = EncodeTable[(data[2] & 0xF) << 1 | data[3] >> 7];
Key[5] = EncodeTable[data[3] >> 2 & 0x1F];
Key[6] = EncodeTable[data[3] << 3 & 0x1F | data[4] >> 5];
Key[7] = EncodeTable[data[4] & 0x1F];
Key[8] = EncodeTable[data[5] >> 3];
Key[9] = EncodeTable[(data[5] & 0x07) << 2 | data[6] >> 6];
Key[10] = EncodeTable[data[6] >> 1 & 0x1F];
Key[11] = EncodeTable[(data[6] & 0x1) << 4 | data[7] >> 4];
Key[12] = EncodeTable[(data[7] & 0xF) << 1 | data[8] >> 7];
Key[13] = EncodeTable[data[8] >> 2 & 0x1F];
Key[14] = EncodeTable[data[8] << 3 & 0x1F | data[9] >> 5];
Key[15] = EncodeTable[data[9] & 0x1F];
return Key;
}
std::string GetFormatedKey() const {
std::string Key = GetKey();
auto ptr = Key.begin() + 4;
ptr = Key.insert(ptr, '-');
ptr++;
ptr += 4;
ptr = Key.insert(ptr, '-');
ptr++;
ptr += 4;
Key.insert(ptr, '-');
return Key;
}
};
-342
View File
@@ -1,342 +0,0 @@
#include <iostream>
#include <ctime>
#include <windows.h>
#include "RSACipher.hpp"
#include "NavicatKeygen.hpp"
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
namespace Helper {
bool ConvertToUTF8(LPCSTR from, std::string& to);
bool ConvertToUTF8(LPCWSTR from, std::string& to);
bool ConvertToUTF8(std::string& str);
std::string Base64Encode(const std::vector<uint8_t>& bytes);
std::vector<uint8_t> Base64Decode(std::string& str);
template<int min_num, int max_num>
bool ReadNumber(int& num, const char* msg, const char* err_msg) {
int temp;
std::string input;
while (true) {
std::cout << msg;
if (!std::getline(std::cin, input))
return false;
try {
temp = std::stoi(input, nullptr, 0);
if (min_num <= temp && temp <= max_num) {
num = temp;
return true;
} else {
throw std::invalid_argument("Invalid number");
}
} catch (...) {
std::cout << err_msg << std::endl;
}
}
}
}
#define MODE_SIMPLE 1
#define MODE_ADVANCED 2
#define FLAG_BIN 1
#define FLAG_TEXT 2
void Process(RSACipher* cipher, int mode, int flag) {
std::string input;
int num;
NavicatKeygen::Product product;
NavicatKeygen::Language language;
uint8_t product0;
uint8_t language0, language1;
uint8_t version;
NavicatKeygen keygen;
std::string username;
std::string organization;
std::string RequestCode_b64;
std::vector<uint8_t> RequestCode;
char RequestInfo[256] = {};
char ResponseInfo[256] = {};
std::vector<uint8_t> ResponseCode;
std::string ResponseCode_b64;
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
if (mode == MODE_SIMPLE) {
std::cout << "Select Navicat product:" << std::endl
<< "0. DataModeler" << std::endl
<< "1. Premium" << std::endl
<< "2. MySQL" << std::endl
<< "3. PostgreSQL" << std::endl
<< "4. Oracle" << std::endl
<< "5. SQLServer" << std::endl
<< "6. SQLite" << std::endl
<< "7. MariaDB" << std::endl
<< "8. MongoDB" << std::endl
<< "9. ReportViewer" << std::endl
<< std::endl;
if (!Helper::ReadNumber<0, 9>(num,
"(Input index)> ",
"Invalid index.")) {
return;
}
product = static_cast<NavicatKeygen::Product>(num);
std::cout << std::endl;
std::cout << "Select product language:" << std::endl
<< "0. English" << std::endl
<< "1. Simplified Chinese" << std::endl
<< "2. Traditional Chinese" << std::endl
<< "3. Japanese" << std::endl
<< "4. Polish" << std::endl
<< "5. Spanish" << std::endl
<< "6. French" << std::endl
<< "7. German" << std::endl
<< "8. Korean" << std::endl
<< "9. Russian" << std::endl
<< "10. Portuguese" << std::endl
<< std::endl;
if (!Helper::ReadNumber<0, 10>(num,
"(Input index)> ",
"Invalid index.")) {
return;
}
language = static_cast<NavicatKeygen::Language>(num);
std::cout << std::endl;
keygen.SetProductSignature(product);
keygen.SetLanguageSignature(language);
}
if (mode == MODE_ADVANCED) {
if (!Helper::ReadNumber<0, 255>(num,
"(Navicat Product ID, 0x00 ~ 0xFF)> ",
"Invalid number.")) {
return;
}
product0 = static_cast<uint8_t>(num);
if (!Helper::ReadNumber<0, 255>(num,
"(Navicat Language Signature 0, 0x00 ~ 0xFF)> ",
"Invalid number.")) {
return;
}
language0 = static_cast<uint8_t>(num);
if (!Helper::ReadNumber<0, 255>(num,
"(Navicat Language Signature 1, 0x00 ~ 0xFF)> ",
"Invalid number.")) {
return;
}
language1 = static_cast<uint8_t>(num);
keygen.SetProductSignature(product0);
keygen.SetLanguageSignature(language0, language1);
}
if (!Helper::ReadNumber<0, 16 - 1>(num,
"(Input major version number, range: 0 ~ 15, default: 12)> ",
"Invalid number.")) {
return;
}
version = static_cast<uint8_t>(num);
keygen.SetVersion(version);
keygen.Generate();
std::cout << std::endl;
std::cout << "Serial number:" << std::endl;
std::cout << keygen.GetFormatedKey() << std::endl;
std::cout << std::endl;
std::cout << "Your name: ";
if (!std::getline(std::cin, username))
return;
if (!Helper::ConvertToUTF8(username)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: ConvertToUTF8 fails." << std::endl;
return;
}
std::cout << "Your organization: ";
if (!std::getline(std::cin, organization))
return;
if (!Helper::ConvertToUTF8(organization)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: ConvertToUTF8 fails." << std::endl;
return;
}
std::cout << std::endl;
if (flag == FLAG_TEXT) {
std::cout << "Input request code (in Base64), input empty line to end:" << std::endl;
while (true) {
std::string temp;
if (!std::getline(std::cin, temp))
return;
if (temp.empty())
break;
RequestCode_b64 += temp;
}
RequestCode = Helper::Base64Decode(RequestCode_b64);
if (RequestCode.empty()) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: Base64Decode fails." << std::endl;
return;
}
if (!cipher->Decrypt(RequestCode.data(),
RequestCode.size(),
RequestInfo,
RSA_PKCS1_PADDING)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: Decrypt<RSACipher::KeyType::PrivateKey> fails." << std::endl;
return;
}
std::cout << "Request Info:" << std::endl;
std::cout << RequestInfo << std::endl;
std::cout << std::endl;
json.Parse(RequestInfo);
json.RemoveMember("P"); // remove Platform info
N_Key.SetString("N", 1);
N_Value.SetString(username.c_str(), username.length());
O_Key.SetString("O", 1);
O_Value.SetString(organization.c_str(), organization.length());
T_Key.SetString("T", 1);
T_Value.SetUint(std::time(nullptr));
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
std::cout << "ERROR: Response info is too long." << std::endl;
return;
}
memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());
std::cout << "Response Info:" << std::endl;
std::cout << ResponseInfo << std::endl;
std::cout << std::endl;
ResponseCode.resize(256);
if (!cipher->Encrypt<RSACipher::KeyType::PrivateKey>(ResponseInfo,
strlen(ResponseInfo),
ResponseCode.data(),
RSA_PKCS1_PADDING)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: Encrypt<RSACipher::KeyType::PrivateKey> fails." << std::endl;
return;
}
ResponseCode_b64 = Helper::Base64Encode(ResponseCode);
if (ResponseCode_b64.empty()) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "Base64Encode fails." << std::endl;
return;
}
std::cout << "License:" << std::endl;
std::cout << ResponseCode_b64 << std::endl;
}
if (flag == FLAG_BIN) {
rapidjson::Value K_Key;
rapidjson::Value K_Value;
HANDLE hFile = INVALID_HANDLE_VALUE;
DWORD NumberOfBytesWritten;
json.Parse("{}");
K_Key.SetString("K", 1);
K_Value.SetString(keygen.GetKey().c_str(), keygen.GetKey().size());
N_Key.SetString("N", 1);
N_Value.SetString(username.c_str(), username.length());
O_Key.SetString("O", 1);
O_Value.SetString(organization.c_str(), organization.length());
T_Key.SetString("T", 1);
T_Value.SetUint(std::time(nullptr));
json.AddMember(K_Key, K_Value, json.GetAllocator());
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
json.Accept(writer);
if (buffer.GetSize() > 240) {
std::cout << "ERROR: Response info is too long." << std::endl;
return;
}
memcpy(ResponseInfo, buffer.GetString(), buffer.GetSize());
std::cout << "Response Info:" << std::endl;
std::cout << ResponseInfo << std::endl;
std::cout << std::endl;
ResponseCode.resize(256);
if (!cipher->Encrypt<RSACipher::KeyType::PrivateKey>(ResponseInfo,
strlen(ResponseInfo),
ResponseCode.data(),
RSA_PKCS1_PADDING)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: Encrypt<RSACipher::KeyType::PrivateKey> fails." << std::endl;
return;
}
hFile = CreateFile(TEXT("license_file"),
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
DWORD dwLastError = GetLastError();
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: CreateFile fails. CODE: " << dwLastError << std::endl;
return;
}
if (!WriteFile(hFile, ResponseCode.data(), ResponseCode.size(), &NumberOfBytesWritten, nullptr)) {
DWORD dwLastError = GetLastError();
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: WriteFile fails. CODE: " << dwLastError << std::endl;
CloseHandle(hFile);
return;
}
CloseHandle(hFile);
std::cout << "license_file has been generated." << std::endl;
}
}
-266
View File
@@ -1,266 +0,0 @@
#pragma once
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <string>
#ifdef _DEBUG
#pragma comment(lib, "libcryptoMTd.lib")
#else
#pragma comment(lib, "libcryptoMT.lib")
#endif
#pragma comment(lib, "WS2_32.lib") // some symbol are used in OpenSSL static lib
#pragma comment(lib, "Crypt32.lib") // some symbol are used in OpenSSL static lib
class RSACipher {
private:
RSA * _RsaObj;
RSACipher() : _RsaObj(nullptr) {}
RSACipher(RSA* lpRsa) : _RsaObj(lpRsa) {}
RSACipher(const RSACipher&) = delete;
RSACipher(RSACipher&&) = delete;
RSACipher& operator=(const RSACipher&) = delete;
RSACipher& operator=(RSACipher&&) = delete;
public:
enum class KeyType {
PrivateKey,
PublicKey
};
enum class KeyFormat {
NotSpecified,
PEM,
PKCS1
};
~RSACipher() {
if (_RsaObj)
RSA_free(_RsaObj);
_RsaObj = nullptr;
}
static RSACipher* Create() {
RSACipher* aCipher = new RSACipher(RSA_new());
if (aCipher->_RsaObj == nullptr) {
delete aCipher;
aCipher = nullptr;
}
return aCipher;
}
bool GenerateKey(int bits, unsigned int e = RSA_F4) {
bool bSuccess = false;
BIGNUM* bn_e = nullptr;
bn_e = BN_new();
if (bn_e == nullptr)
goto ON_RSACipher_GenerateKey0_ERROR;
if (!BN_set_word(bn_e, e))
goto ON_RSACipher_GenerateKey0_ERROR;
if (!RSA_generate_key_ex(_RsaObj, bits, bn_e, nullptr))
goto ON_RSACipher_GenerateKey0_ERROR;
bSuccess = true;
ON_RSACipher_GenerateKey0_ERROR:
if (bn_e)
BN_free(bn_e);
return bSuccess;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
bool ExportKeyToFile(const std::string& filename) {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
bool bSuccess = false;
BIO* bio_file = nullptr;
bio_file = BIO_new_file(filename.c_str(), "w");
if (bio_file == nullptr)
goto ON_RSACipher_ExportKeyToFile_0_ERROR;
if (_Type == KeyType::PrivateKey) {
bSuccess = PEM_write_bio_RSAPrivateKey(bio_file, _RsaObj, nullptr, nullptr, 0, nullptr, nullptr) ? true : false;
} else {
if (_Format == KeyFormat::PEM)
bSuccess = PEM_write_bio_RSA_PUBKEY(bio_file, _RsaObj) ? true : false;
else if (_Format == KeyFormat::PKCS1)
bSuccess = PEM_write_bio_RSAPublicKey(bio_file, _RsaObj) ? true : false;
}
ON_RSACipher_ExportKeyToFile_0_ERROR:
return bSuccess;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
std::string ExportKeyString() {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
std::string KeyString;
BIO* bio_mem = nullptr;
int len = 0;
const char* lpdata = nullptr;
bio_mem = BIO_new(BIO_s_mem());
if (bio_mem == nullptr)
goto ON_RSACipher_ExportKeyString_0_ERROR;
if (_Type == KeyType::PrivateKey) {
if (!PEM_write_bio_RSAPrivateKey(bio_mem, _RsaObj, nullptr, nullptr, 0, nullptr, nullptr))
goto ON_RSACipher_ExportKeyString_0_ERROR;
} else {
if (_Format == KeyFormat::PEM) {
if (!PEM_write_bio_RSA_PUBKEY(bio_mem, _RsaObj))
goto ON_RSACipher_ExportKeyString_0_ERROR;
} else if (_Format == KeyFormat::PKCS1) {
if (!PEM_write_bio_RSAPublicKey(bio_mem, _RsaObj))
goto ON_RSACipher_ExportKeyString_0_ERROR;
}
}
len = BIO_get_mem_data(bio_mem, &lpdata);
KeyString.resize(len);
memcpy(KeyString.data(), lpdata, len);
ON_RSACipher_ExportKeyString_0_ERROR:
if (bio_mem)
BIO_free_all(bio_mem);
return KeyString;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
bool ImportKeyFromFile(const std::string& filename) {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
bool bSuccess = false;
BIO* bio_file = nullptr;
RSA* _newRsaObj = nullptr;
bio_file = BIO_new_file(filename.c_str(), "r");
if (bio_file == nullptr)
goto ON_RSACipher_ImportKeyFromFile_0_ERROR;
if (_Type == KeyType::PrivateKey) {
_newRsaObj = PEM_read_bio_RSAPrivateKey(bio_file, nullptr, nullptr, nullptr);
} else {
if (_Format == KeyFormat::PEM)
_newRsaObj = PEM_read_bio_RSA_PUBKEY(bio_file, nullptr, nullptr, nullptr);
else if (_Format == KeyFormat::PKCS1)
_newRsaObj = PEM_read_bio_RSAPublicKey(bio_file, nullptr, nullptr, nullptr);
}
if (_newRsaObj) {
RSA_free(_RsaObj);
_RsaObj = _newRsaObj;
bSuccess = true;
}
ON_RSACipher_ImportKeyFromFile_0_ERROR:
if (bio_file)
BIO_free_all(bio_file);
return bSuccess;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
bool ImportKeyString(const std::string& KeyString) {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
bool bSuccess = false;
BIO* bio_mem = nullptr;
RSA* _newRsaObj = nullptr;
bio_mem = BIO_new(BIO_s_mem());
if (bio_mem == nullptr)
goto ON_RSACipher_ImportKeyString_0_ERROR;
BIO_puts(bio_mem, KeyString.c_str());
if (_Type == KeyType::PrivateKey) {
_newRsaObj = PEM_read_bio_RSAPrivateKey(bio_mem, nullptr, nullptr, nullptr);
} else {
if (_Format == KeyFormat::PEM)
_newRsaObj = PEM_read_bio_RSA_PUBKEY(bio_mem, nullptr, nullptr, nullptr);
else if (_Format == KeyFormat::PKCS1)
_newRsaObj = PEM_read_bio_RSAPublicKey(bio_mem, nullptr, nullptr, nullptr);
}
if (_newRsaObj) {
RSA_free(_RsaObj);
_RsaObj = _newRsaObj;
bSuccess = true;
}
ON_RSACipher_ImportKeyString_0_ERROR:
if (bio_mem)
BIO_free_all(bio_mem);
return bSuccess;
}
template<KeyType _Type = KeyType::PublicKey>
int Encrypt(const void* from, int len, void* to, int padding) {
int write_bytes = 0;
if (_Type == KeyType::PrivateKey) {
write_bytes = RSA_private_encrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
} else {
write_bytes = RSA_public_encrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
}
if (write_bytes == -1)
write_bytes = 0;
return write_bytes;
}
template<KeyType _Type = KeyType::PrivateKey>
int Decrypt(const void* from, int len, void* to, int padding) {
int write_bytes = 0;
if (_Type == KeyType::PrivateKey) {
write_bytes = RSA_private_decrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
} else {
write_bytes = RSA_public_decrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
}
if (write_bytes == -1)
write_bytes = 0;
return write_bytes;
}
};
+195
View File
@@ -0,0 +1,195 @@
#include "SerialNumberGenerator.hpp"
#include <Exception.hpp>
#include <openssl/des.h>
#include <NTSecAPI.h>
#include <iostream>
#pragma comment(lib, "Advapi32")
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\NavicatKeygen.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace std {
#if defined(_UNICODE) || defined(UNICODE)
static auto & xcin = wcin;
static auto& xcout = wcout;
static auto& xcerr = wcerr;
#else
static auto& xcin = cin;
static auto& xcout = cout;
static auto& xcerr = cerr;
#endif
}
namespace nkg {
SerialNumberGenerator::SerialNumberGenerator() noexcept :
_Data{ 0x68 , 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32 } {}
void SerialNumberGenerator::SetLanguageSignature(NavicatLanguage Language) noexcept {
switch (Language) {
case NavicatLanguage::English:
_Data[5] = 0xAC; // Must be 0xAC for English version.
_Data[6] = 0x88; // Must be 0x88 for English version.
break;
case NavicatLanguage::SimplifiedChinese:
_Data[5] = 0xCE; // Must be 0xCE for Simplified Chinese version.
_Data[6] = 0x32; // Must be 0x32 for Simplified Chinese version.
break;
case NavicatLanguage::TraditionalChinese:
_Data[5] = 0xAA; // Must be 0xAA for Traditional Chinese version.
_Data[6] = 0x99; // Must be 0x99 for Traditional Chinese version.
break;
case NavicatLanguage::Japanese:
_Data[5] = 0xAD; // Must be 0xAD for Japanese version. Discoverer: @dragonflylee
_Data[6] = 0x82; // Must be 0x82 for Japanese version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Polish:
_Data[5] = 0xBB; // Must be 0xBB for Polish version. Discoverer: @dragonflylee
_Data[6] = 0x55; // Must be 0x55 for Polish version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Spanish:
_Data[5] = 0xAE; // Must be 0xAE for Spanish version. Discoverer: @dragonflylee
_Data[6] = 0x10; // Must be 0x10 for Spanish version. Discoverer: @dragonflylee
break;
case NavicatLanguage::French:
_Data[5] = 0xFA; // Must be 0xFA for French version. Discoverer: @Deltafox79
_Data[6] = 0x20; // Must be 0x20 for French version. Discoverer: @Deltafox79
break;
case NavicatLanguage::German:
_Data[5] = 0xB1; // Must be 0xB1 for German version. Discoverer: @dragonflylee
_Data[6] = 0x60; // Must be 0x60 for German version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Korean:
_Data[5] = 0xB5; // Must be 0xB5 for Korean version. Discoverer: @dragonflylee
_Data[6] = 0x60; // Must be 0x60 for Korean version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Russian:
_Data[5] = 0xEE; // Must be 0xB5 for Russian version. Discoverer: @dragonflylee
_Data[6] = 0x16; // Must be 0x60 for Russian version. Discoverer: @dragonflylee
break;
case NavicatLanguage::Portuguese:
_Data[5] = 0xCD; // Must be 0xCD for Portuguese version. Discoverer: @dragonflylee
_Data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
break;
}
}
void SerialNumberGenerator::SetLanguageSignature(BYTE LanguageSignature0, BYTE LanguageSignature1) noexcept {
_Data[5] = LanguageSignature0;
_Data[6] = LanguageSignature1;
}
void SerialNumberGenerator::SetProductSignature(NavicatProductType ProductType) noexcept {
switch (ProductType) {
case NavicatProductType::DataModeler:
_Data[7] = 0x47;
break;
case NavicatProductType::Premium:
_Data[7] = 0x65;
break;
case NavicatProductType::MySQL:
_Data[7] = 0x68;
break;
case NavicatProductType::PostgreSQL:
_Data[7] = 0x6C;
break;
case NavicatProductType::Oracle:
_Data[7] = 0x70;
break;
case NavicatProductType::SQLServer:
_Data[7] = 0x74;
break;
case NavicatProductType::SQLite:
_Data[7] = 0x78;
break;
case NavicatProductType::MariaDB:
_Data[7] = 0x7C;
break;
case NavicatProductType::MongoDB:
_Data[7] = 0x80;
break;
case NavicatProductType::ReportViewer:
_Data[7] = 0xb;
default:
break;
}
}
void SerialNumberGenerator::SetProductSignature(BYTE ProductSignature) noexcept {
_Data[7] = ProductSignature;
}
void SerialNumberGenerator::SetVersion(BYTE Version) {
if (Version < 0x10) {
_Data[8] = static_cast<BYTE>(Version << 4);
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid version for Navicat."));
}
}
void SerialNumberGenerator::Generate() {
static const TCHAR EncodeTable[] = TEXT("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");
RtlGenRandom(_Data + 2, 3);
const_DES_cblock key = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
DES_key_schedule schedule;
DES_set_key_unchecked(&key, &schedule);
DES_ecb_encrypt(
reinterpret_cast<const_DES_cblock*>(_Data + 2),
reinterpret_cast<const_DES_cblock*>(_Data + 2),
&schedule,
DES_ENCRYPT
);
_SerialNumberShort.resize(16);
_SerialNumberShort[0] = EncodeTable[_Data[0] >> 3];
_SerialNumberShort[1] = EncodeTable[(_Data[0] & 0x07) << 2 | _Data[1] >> 6];
_SerialNumberShort[2] = EncodeTable[_Data[1] >> 1 & 0x1F];
_SerialNumberShort[3] = EncodeTable[(_Data[1] & 0x1) << 4 | _Data[2] >> 4];
_SerialNumberShort[4] = EncodeTable[(_Data[2] & 0xF) << 1 | _Data[3] >> 7];
_SerialNumberShort[5] = EncodeTable[_Data[3] >> 2 & 0x1F];
_SerialNumberShort[6] = EncodeTable[_Data[3] << 3 & 0x1F | _Data[4] >> 5];
_SerialNumberShort[7] = EncodeTable[_Data[4] & 0x1F];
_SerialNumberShort[8] = EncodeTable[_Data[5] >> 3];
_SerialNumberShort[9] = EncodeTable[(_Data[5] & 0x07) << 2 | _Data[6] >> 6];
_SerialNumberShort[10] = EncodeTable[_Data[6] >> 1 & 0x1F];
_SerialNumberShort[11] = EncodeTable[(_Data[6] & 0x1) << 4 | _Data[7] >> 4];
_SerialNumberShort[12] = EncodeTable[(_Data[7] & 0xF) << 1 | _Data[8] >> 7];
_SerialNumberShort[13] = EncodeTable[_Data[8] >> 2 & 0x1F];
_SerialNumberShort[14] = EncodeTable[_Data[8] << 3 & 0x1F | _Data[9] >> 5];
_SerialNumberShort[15] = EncodeTable[_Data[9] & 0x1F];
_SerialNumberLong = std::xstring::format(
TEXT("%.4s-%.4s-%.4s-%.4s"),
_SerialNumberShort.c_str() + 0,
_SerialNumberShort.c_str() + 4,
_SerialNumberShort.c_str() + 8,
_SerialNumberShort.c_str() + 12
);
}
[[nodiscard]]
const std::xstring& SerialNumberGenerator::GetSerialNumberShort() const noexcept {
return _SerialNumberShort;
}
[[nodiscard]]
const std::xstring& SerialNumberGenerator::GetSerialNumberLong() const noexcept {
return _SerialNumberLong;
}
void SerialNumberGenerator::ShowInConsole() const {
std::xcout << TEXT("[*] Serial number:") << std::endl;
std::xcout << _SerialNumberLong << std::endl;
std::xcout << std::endl;
}
}
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include <windows.h>
#include <xstring.hpp>
namespace nkg {
enum class NavicatLanguage {
English,
SimplifiedChinese,
TraditionalChinese,
Japanese,
Polish,
Spanish,
French,
German,
Korean,
Russian,
Portuguese
};
enum class NavicatProductType {
DataModeler,
Premium,
MySQL,
PostgreSQL,
Oracle,
SQLServer,
SQLite,
MariaDB,
MongoDB,
ReportViewer
};
class SerialNumberGenerator {
private:
BYTE _Data[10];
std::xstring _SerialNumberShort;
std::xstring _SerialNumberLong;
public:
SerialNumberGenerator() noexcept;
void SetLanguageSignature(NavicatLanguage Language) noexcept;
void SetLanguageSignature(BYTE LanguageSignature0, BYTE LanguageSignature1) noexcept;
void SetProductSignature(NavicatProductType ProductType) noexcept;
void SetProductSignature(BYTE ProductSignature) noexcept;
void SetVersion(BYTE Version);
void Generate();
[[nodiscard]]
const std::xstring& GetSerialNumberShort() const noexcept;
[[nodiscard]]
const std::xstring& GetSerialNumberLong() const noexcept;
void ShowInConsole() const;
};
}
+117
View File
@@ -0,0 +1,117 @@
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <Exception.hpp>
#include <ExceptionUser.hpp>
#include <RSACipher.hpp>
#include "SerialNumberGenerator.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-keygen\\_tmain.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
using fnCollectInformation = SerialNumberGenerator();
using fnGenerateLicense = void(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
SerialNumberGenerator CollectInformationNormal();
SerialNumberGenerator CollectInformationAdvanced();
void GenerateLicenseText(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
void GenerateLicenseBinary(const RSACipher& Cipher, const SerialNumberGenerator& Generator);
}
static void Welcome() {
_putts(TEXT("***************************************************"));
_putts(TEXT("* Navicat Keygen by @DoubleLabyrinth *"));
_putts(TEXT("* Version: 4.0 *"));
_putts(TEXT("***************************************************"));
_putts(TEXT(""));
}
static void Help() {
_putts(TEXT("Usage:"));
_putts(TEXT(" navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>"));
_putts(TEXT(""));
_putts(TEXT(" <-bin|-text> Specify \"-bin\" to generate \"license_file\" used by Navicat 11."));
_putts(TEXT(" Specify \"-text\" to generate base64-encoded activation code."));
_putts(TEXT(" This parameter must be specified."));
_putts(TEXT(""));
_putts(TEXT(" [-adv] Enable advance mode."));
_putts(TEXT(" This parameter is optional."));
_putts(TEXT(""));
_putts(TEXT(" <RSA-2048 Private Key File> A path to an RSA-2048 private key file."));
_putts(TEXT(" This parameter must be specified."));
_putts(TEXT(""));
_putts(TEXT("Example:"));
_putts(TEXT(" navicat-keygen.exe -text .\\RegPrivateKey.pem"));
}
int _tmain(int argc, PTSTR argv[]) {
Welcome();
if (argc == 3 || argc == 4) {
nkg::fnCollectInformation* lpfnCollectInformation = nullptr;
nkg::fnGenerateLicense* lpfnGenerateLicense = nullptr;
if (_tcsicmp(argv[1], TEXT("-bin")) == 0) {
lpfnGenerateLicense = nkg::GenerateLicenseBinary;
} else if (_tcsicmp(argv[1], TEXT("-text")) == 0) {
lpfnGenerateLicense = nkg::GenerateLicenseText;
} else {
Help();
return -1;
}
if (argc == 4) {
if (_tcsicmp(argv[2], TEXT("-adv")) == 0) {
lpfnCollectInformation = nkg::CollectInformationAdvanced;
} else {
Help();
return -1;
}
} else {
lpfnCollectInformation = nkg::CollectInformationNormal;
}
try {
nkg::RSACipher Cipher;
Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(argv[argc - 1]);
if (Cipher.Bits() != 2048) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA key length mismatches."))
.AddHint(TEXT("You must provide an RSA key whose modulus length is 2048 bits."));
}
auto Generator = lpfnCollectInformation();
Generator.Generate();
Generator.ShowInConsole();
lpfnGenerateLicense(Cipher, Generator);
return 0;
} catch (nkg::UserAbortionError&) {
return -1;
} catch (nkg::Exception& e) {
_tprintf_s(TEXT("[-] %s:%zu ->\n"), e.File(), e.Line());
_tprintf_s(TEXT(" %s\n"), e.Message());
if (e.HasErrorCode()) {
_tprintf_s(TEXT(" %s (0x%zx)\n"), e.ErrorString(), e.ErrorCode());
}
for (auto& Hint : e.Hints()) {
_tprintf_s(TEXT(" Hints: %s\n"), Hint.c_str());
}
return -1;
} catch (std::exception& e) {
_tprintf_s(TEXT("[-] %hs\n"), e.what());
return -1;
}
} else {
Help();
return -1;
}
}
-69
View File
@@ -1,69 +0,0 @@
#include <iostream>
#include "RSACipher.hpp"
namespace Helper {
bool ConvertToUTF8(std::string& str);
}
#define MODE_SIMPLE 1
#define MODE_ADVANCED 2
#define FLAG_BIN 1
#define FLAG_TEXT 2
void Process(RSACipher* cipher, int mode, int flag);
void help() {
std::cout << "Usage:" << std::endl;
std::cout << " navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 PrivateKey(PEM file)>" << std::endl;
}
int main(int argc, char* argv[]) {
if (argc != 3 && argc != 4) {
help();
return 0;
}
std::string RSAPrivateKeyPath = argv[argc - 1];
RSACipher* cipher = nullptr;
cipher = RSACipher::Create();
if (cipher == nullptr) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: Failed to create RSACipher." << std::endl;
goto ON_tmain_ERROR;
}
if (!Helper::ConvertToUTF8(RSAPrivateKeyPath)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: ConvertToUTF8 fails." << std::endl;
goto ON_tmain_ERROR;
}
if (!cipher->ImportKeyFromFile<RSACipher::KeyType::PrivateKey>(RSAPrivateKeyPath)) {
std::cout << "@Function: " << __FUNCSIG__ << " LINE: " << __LINE__ << std::endl;
std::cout << "ERROR: ImportKeyFromFile<RSACipher::KeyType::PrivateKey> fails." << std::endl;
goto ON_tmain_ERROR;
}
if (argc == 3) {
if (_stricmp(argv[1], "-bin") == 0)
Process(cipher, MODE_SIMPLE, FLAG_BIN);
else if (_stricmp(argv[1], "-text") == 0)
Process(cipher, MODE_SIMPLE, FLAG_TEXT);
else
help();
}
if (argc == 4) {
if (_stricmp(argv[1], "-bin") == 0)
Process(cipher, MODE_ADVANCED, FLAG_BIN);
else if (_stricmp(argv[1], "-text") == 0)
Process(cipher, MODE_ADVANCED, FLAG_TEXT);
else
help();
}
ON_tmain_ERROR:
if (cipher)
delete cipher;
return 0;
}
+46 -45
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<?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>
@@ -19,42 +19,50 @@
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{CB49F054-83AB-4C16-B73B-33D7DF696E16}</ProjectGuid>
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{BA201764-EECF-4DA8-BCAD-7CFBA301FC9C}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>navicatkeygen</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<VcpkgTriplet Condition="'$(Platform)'=='Win32'">x86-windows-static</VcpkgTriplet>
<VcpkgTriplet Condition="'$(Platform)'=='x64'">x64-windows-static</VcpkgTriplet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
<Import Project="..\common\common.vcxitems" Label="Shared" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
@@ -71,38 +79,33 @@
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(SolutionDir)rapidjson-lib\include;$(SolutionDir)openssl-lib\include;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib;$(LibraryPath)</LibraryPath>
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(SolutionDir)rapidjson-lib\include;$(SolutionDir)openssl-lib\include64;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib64;$(LibraryPath)</LibraryPath>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>$(SolutionDir)rapidjson-lib\include;$(SolutionDir)openssl-lib\include;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib;$(LibraryPath)</LibraryPath>
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>$(SolutionDir)rapidjson-lib\include;$(SolutionDir)openssl-lib\include64;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib64;$(LibraryPath)</LibraryPath>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -111,14 +114,13 @@
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -128,15 +130,14 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -148,15 +149,14 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -166,13 +166,14 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Helper.cpp" />
<ClCompile Include="Process.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="CollectInformation.cpp" />
<ClCompile Include="GenerateLicense.cpp" />
<ClCompile Include="SerialNumberGenerator.cpp" />
<ClCompile Include="_tmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="NavicatKeygen.hpp" />
<ClInclude Include="RSACipher.hpp" />
<ClInclude Include="Base64.hpp" />
<ClInclude Include="SerialNumberGenerator.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
@@ -7,7 +7,7 @@
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
@@ -15,21 +15,24 @@
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Helper.cpp">
<ClCompile Include="_tmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Process.cpp">
<ClCompile Include="SerialNumberGenerator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<ClCompile Include="CollectInformation.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="GenerateLicense.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="RSACipher.hpp">
<ClInclude Include="Base64.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="NavicatKeygen.hpp">
<ClInclude Include="SerialNumberGenerator.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
@@ -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>
+94
View File
@@ -0,0 +1,94 @@
#include "CapstoneDisassembler.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\CapstoneDisassembler.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
CapstoneDisassembler::CapstoneDisassembler(const CapstoneEngine& Engine) :
ResourceOwned<CapstoneInsnTraits>(cs_malloc(Engine)),
_Engine(Engine),
_CurrentState{},
_NextState{},
_lpCurrentInsn(nullptr)
{
if (IsValid() == false) {
throw CapstoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), cs_errno(Engine), TEXT("cs_malloc failed."));
}
}
CapstoneDisassembler::CapstoneDisassembler(CapstoneDisassembler&& Other) noexcept :
ResourceOwned<CapstoneInsnTraits>(static_cast<ResourceOwned<CapstoneInsnTraits>&&>(Other)),
_Engine(Other._Engine),
_CurrentState(Other._CurrentState),
_NextState(Other._NextState),
_lpCurrentInsn(Other._lpCurrentInsn) {}
CapstoneDisassembler& CapstoneDisassembler::SetContext(const CapstoneContext& Ctx) noexcept {
_lpCurrentInsn = nullptr;
_CurrentState.lpMachineCode = nullptr;
_CurrentState.cbMachineCode = 0;
_CurrentState.Address = 0;
_NextState = Ctx;
return *this;
}
[[nodiscard]]
const CapstoneContext& CapstoneDisassembler::GetContext() const noexcept {
return _NextState;
}
[[nodiscard]]
bool CapstoneDisassembler::Next() noexcept {
bool bSucceed;
CapstoneContext backup = _NextState;
bSucceed = cs_disasm_iter(_Engine.Get(), reinterpret_cast<const uint8_t**>(&_NextState.lpMachineCode), &_NextState.cbMachineCode, &_NextState.Address, Get());
if (bSucceed) {
if (_lpCurrentInsn == nullptr) {
_lpCurrentInsn = Get();
}
_CurrentState = backup;
} else {
_lpCurrentInsn = nullptr;
}
return bSucceed;
}
[[nodiscard]]
const cs_insn* CapstoneDisassembler::GetInstruction() const noexcept {
return _lpCurrentInsn;
}
[[nodiscard]]
const CapstoneContext& CapstoneDisassembler::GetInstructionContext() const noexcept {
return _CurrentState;
}
CapstoneEngine::CapstoneEngine(cs_arch ArchType, cs_mode Mode) {
auto err = cs_open(ArchType, Mode, GetAddressOf());
if (err != CS_ERR_OK) {
throw CapstoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, TEXT("cs_open failed."));
}
}
void CapstoneEngine::Option(cs_opt_type Type, size_t Value) {
auto err = cs_option(Get(), Type, Value);
if (err != CS_ERR_OK) {
throw CapstoneError(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, TEXT("cs_option failed."));
}
}
[[nodiscard]]
CapstoneDisassembler CapstoneEngine::CreateDisassembler() const {
return CapstoneDisassembler(*this);
}
}
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include "ExceptionCapstone.hpp"
#include <ResourceOwned.hpp>
#include "ResourceTraitsCapstone.hpp"
namespace nkg {
struct CapstoneContext {
const void* lpMachineCode;
size_t cbMachineCode;
uint64_t Address;
};
class CapstoneEngine;
class CapstoneDisassembler : private ResourceOwned<CapstoneInsnTraits> {
friend class CapstoneEngine;
private:
const CapstoneEngine& _Engine;
CapstoneContext _CurrentState;
CapstoneContext _NextState;
cs_insn* _lpCurrentInsn;
CapstoneDisassembler(const CapstoneEngine& Engine);
public:
CapstoneDisassembler(CapstoneDisassembler&& Other) noexcept;
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 ResourceOwned<CapstoneHandleTraits> {
friend class CapstoneDisassembler;
public:
CapstoneEngine(cs_arch ArchType, cs_mode Mode);
void Option(cs_opt_type Type, size_t Value);
[[nodiscard]]
CapstoneDisassembler CreateDisassembler() const;
};
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <Exception.hpp>
#include <capstone/capstone.h>
namespace nkg {
class CapstoneError final : public Exception {
private:
cs_err _ErrorCode;
std::xstring _ErrorString;
public:
CapstoneError(PCTSTR SourceFile, SIZE_T SourceLine, cs_err CapstoneErrorCode, PCTSTR CustomMessage) noexcept :
Exception(SourceFile, SourceLine, CustomMessage),
_ErrorCode(CapstoneErrorCode),
_ErrorString(std::xstring_extension{}, cs_strerror(CapstoneErrorCode), CP_UTF8) {}
[[nodiscard]]
virtual bool HasErrorCode() const noexcept override {
return true;
}
[[nodiscard]]
virtual ULONG_PTR ErrorCode() const noexcept override {
return _ErrorCode;
}
[[nodiscard]]
virtual PCTSTR ErrorString() const noexcept override {
return _ErrorString.c_str();
}
};
}
-153
View File
@@ -1,153 +0,0 @@
#include "def.hpp"
#include "NavicatCrypto.hpp"
namespace Helper {
static Navicat11Crypto NavicatCipher("23970790", 8);
std::string EncryptPublicKey(const std::string& PublicKeyString) {
return NavicatCipher.EncryptString(PublicKeyString.c_str(),
PublicKeyString.length());
}
bool ConvertToUTF8(LPCSTR from, std::string& to) {
bool bSuccess = false;
int RequireLength = 0;
LPWSTR lpUnicodeString = nullptr;
RequireLength = MultiByteToWideChar(CP_ACP, NULL, from, -1, nullptr, 0);
if (RequireLength == 0)
goto ON_ConvertToUTF8_0_ERROR;
lpUnicodeString = reinterpret_cast<LPWSTR>(HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY,
RequireLength * sizeof(WCHAR)));
if (lpUnicodeString == nullptr)
goto ON_ConvertToUTF8_0_ERROR;
if (!MultiByteToWideChar(CP_ACP, NULL, from, -1, lpUnicodeString, RequireLength))
goto ON_ConvertToUTF8_0_ERROR;
RequireLength = WideCharToMultiByte(CP_UTF8, NULL, lpUnicodeString, -1, nullptr, 0, nullptr, nullptr);
if (RequireLength == 0)
goto ON_ConvertToUTF8_0_ERROR;
to.resize(RequireLength);
if (!WideCharToMultiByte(CP_UTF8, NULL, lpUnicodeString, -1, to.data(), RequireLength, nullptr, nullptr))
goto ON_ConvertToUTF8_0_ERROR;
while (to.back() == 0)
to.pop_back();
bSuccess = true;
ON_ConvertToUTF8_0_ERROR:
if (lpUnicodeString)
HeapFree(GetProcessHeap(), NULL, lpUnicodeString);
return bSuccess;
}
bool ConvertToUTF8(LPCWSTR from, std::string& to) {
bool bSuccess = false;
int RequireLength = 0;
RequireLength = WideCharToMultiByte(CP_UTF8, NULL, from, -1, nullptr, 0, nullptr, nullptr);
if (RequireLength == 0)
goto ON_ConvertToUTF8_1_ERROR;
to.resize(RequireLength);
if (!WideCharToMultiByte(CP_UTF8, NULL, from, -1, to.data(), RequireLength, nullptr, nullptr))
goto ON_ConvertToUTF8_1_ERROR;
while (to.back() == 0)
to.pop_back();
bSuccess = true;
ON_ConvertToUTF8_1_ERROR:
return bSuccess;
}
bool ConvertToUTF8(std::string& str) {
bool bSuccess = false;
std::string temp;
bSuccess = ConvertToUTF8(str.c_str(), temp);
if (bSuccess)
str = temp;
return bSuccess;
}
void ErrorReport(LPCTSTR at, UINT line, LPCTSTR msg) {
_tprintf_s(TEXT("@%s LINE: %u\n"), at, line);
_tprintf_s(TEXT("%s\n"), msg);
}
void ErrorReport(LPCTSTR at, UINT line, LPCTSTR msg, DWORD err_code) {
_tprintf_s(TEXT("@%s LINE: %u\n"), at, line);
_tprintf_s(TEXT("%s CODE: 0x%08X\n"), msg, err_code);
}
template<typename _Type>
static __forceinline bool ProbeForRead(const void* p, void* out) {
__try {
*reinterpret_cast<_Type*>(out) = *reinterpret_cast<const _Type*>(p);
return true;
} __except (1) {
return false;
}
}
void PrintMemory(const void* a, const void* b, const void* base) {
const uint8_t* start = reinterpret_cast<const uint8_t*>(a);
const uint8_t* end = reinterpret_cast<const uint8_t*>(b);
const uint8_t* base_ptr = reinterpret_cast<const uint8_t*>(base);
if (start >= end)
return;
while (reinterpret_cast<uintptr_t>(start) % 16)
start--;
while (reinterpret_cast<uintptr_t>(start) % 16)
end++;
while (start < end) {
uint16_t value[16] = {};
if (base_ptr)
_tprintf(TEXT("+0x%p "), reinterpret_cast<const void*>(start - base_ptr));
else
_tprintf(TEXT("0x%p "), start);
for (int i = 0; i < 16; ++i) {
if (ProbeForRead<uint8_t>(start + i, value + i)) {
_tprintf(TEXT("%02x "), value[i]);
} else {
value[i] = -1;
_tprintf(TEXT("?? "));
}
}
_tprintf(TEXT(" "));
for (int i = 0; i < 16; ++i) {
if (value[i] < 0x20) {
_tprintf(TEXT("."));
} else if (value[i] > 0x7e) {
_tprintf(TEXT("."));
} else {
_tprintf(TEXT("%c"), value[i]);
}
}
_tprintf(TEXT("\n"));
start += 0x10;
}
}
}
+284
View File
@@ -0,0 +1,284 @@
#include "ImageInterpreter.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\ImageInterpreter.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
ImageInterpreter::ImageInterpreter() :
_DosHeader(nullptr),
_NtHeaders(nullptr),
_SectionHeaderTable(nullptr),
_VsFixedFileInfo(nullptr) {}
[[nodiscard]]
ImageInterpreter ImageInterpreter::ParseImage(PVOID ImageBase, bool DisableRelocationParsing) {
ImageInterpreter NewImage;
NewImage._DosHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(ImageBase);
if (NewImage._DosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (DOS signature check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid WinPE file?"));
}
NewImage._NtHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(
reinterpret_cast<uint8_t*>(ImageBase) + NewImage._DosHeader->e_lfanew
);
if (NewImage._NtHeaders->Signature != IMAGE_NT_SIGNATURE) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (NT signature check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid WinPE file?"));
}
#if defined(_M_AMD64)
if (NewImage._NtHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Optional header magic check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 64-bits WinPE file?"));
}
if (NewImage._NtHeaders->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Machine check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 64-bits WinPE file?"));
}
#elif defined(_M_IX86)
if (NewImage._NtHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Optional header magic check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 32-bits WinPE file?"));
}
if (NewImage._NtHeaders->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Invalid Image. (Machine check failure)"))
.AddHint(TEXT("Are you sure you DO provide a valid 32-bits WinPE file?"));
}
#else
#error "Unsupported architecture."
#endif
NewImage._SectionHeaderTable = reinterpret_cast<PIMAGE_SECTION_HEADER>(
reinterpret_cast<char*>(&NewImage._NtHeaders->OptionalHeader) + NewImage._NtHeaders->FileHeader.SizeOfOptionalHeader
);
for (WORD i = 0; i < NewImage._NtHeaders->FileHeader.NumberOfSections; ++i) {
uint64_t SectionName = *reinterpret_cast<uint64_t*>(NewImage._SectionHeaderTable[i].Name);
if (NewImage._SectionNameTable.find(SectionName) == NewImage._SectionNameTable.end()) {
NewImage._SectionNameTable[SectionName] = i;
}
NewImage._SectionAddressTable[NewImage._SectionHeaderTable[i].VirtualAddress] = i;
NewImage._SectionOffsetTable[NewImage._SectionHeaderTable[i].PointerToRawData] = i;
}
if (!DisableRelocationParsing && NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress != 0) {
auto RelocTableRva = NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress;
auto RelocTable = NewImage.RvaToPointer<PIMAGE_BASE_RELOCATION>(RelocTableRva);
while (RelocTable->VirtualAddress != 0) {
uintptr_t Rva = RelocTable->VirtualAddress;
PWORD RelocItems = reinterpret_cast<PWORD>(RelocTable + 1);
DWORD RelocItemsCount = (RelocTable->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
for (DWORD i = 0; i < RelocItemsCount; ++i) {
auto RelocType = RelocItems[i] >> 12;
switch (RelocType) {
case IMAGE_REL_BASED_ABSOLUTE:
break;
case IMAGE_REL_BASED_HIGH:
case IMAGE_REL_BASED_LOW:
case IMAGE_REL_BASED_HIGHADJ:
NewImage._RelocationAddressTable[Rva + (RelocItems[i] & 0x0fff)] = 2;
break;
case IMAGE_REL_BASED_HIGHLOW:
NewImage._RelocationAddressTable[Rva + (RelocItems[i] & 0x0fff)] = 4;
break;
#if defined(IMAGE_REL_BASED_DIR64)
case IMAGE_REL_BASED_DIR64:
NewImage._RelocationAddressTable[Rva + (RelocItems[i] & 0x0fff)] = 8;
break;
#endif
default:
break;
}
}
RelocTable = reinterpret_cast<PIMAGE_BASE_RELOCATION>(&RelocItems[RelocItemsCount]);
}
}
if (NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress) {
uintptr_t ResourceRva = NewImage._NtHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
auto ResourceTypeTable =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DIRECTORY>(ResourceRva);
auto ResourceTypeNameEntries =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(ResourceTypeTable + 1);
auto ResourceTypeIdEntries =
ResourceTypeNameEntries + ResourceTypeTable->NumberOfNamedEntries;
bool VS_FII_Ok = false;
for (WORD i = 0; i < ResourceTypeTable->NumberOfIdEntries && !VS_FII_Ok; ++i) {
if (ResourceTypeIdEntries[i].Id == reinterpret_cast<uintptr_t>(RT_VERSION) && ResourceTypeIdEntries[i].DataIsDirectory) {
auto ResourceNameTable =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DIRECTORY>(ResourceRva + ResourceTypeIdEntries[i].OffsetToDirectory);
auto ResourceNameNameEntries =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(ResourceNameTable + 1);
auto ResourceNameIdEntries =
ResourceNameNameEntries + ResourceNameTable->NumberOfNamedEntries;
for (WORD j = 0; j < ResourceNameTable->NumberOfIdEntries && !VS_FII_Ok; ++j) {
if (ResourceNameIdEntries[j].Id == VS_VERSION_INFO && ResourceNameIdEntries[j].DataIsDirectory) {
auto ResourceLangTable =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DIRECTORY>(ResourceRva + ResourceNameIdEntries[j].OffsetToDirectory);
auto ResourceLangNameEntries =
reinterpret_cast<PIMAGE_RESOURCE_DIRECTORY_ENTRY>(ResourceLangTable + 1);
auto ResourceLangIdEntries =
ResourceLangNameEntries + ResourceLangTable->NumberOfNamedEntries;
for (WORD k = 0; k < ResourceLangTable->NumberOfIdEntries && !VS_FII_Ok; ++k) {
if (ResourceLangIdEntries[k].Id == MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) && !ResourceLangIdEntries[k].DataIsDirectory) {
auto ResourceDataEntry =
NewImage.RvaToPointer<PIMAGE_RESOURCE_DATA_ENTRY>(ResourceRva + ResourceLangIdEntries[k].OffsetToData);
auto VsVersionInfo = NewImage.RvaToPointer<PBYTE>(ResourceDataEntry->OffsetToData);
auto VsVersionInfoszKey = reinterpret_cast<PWSTR>(VsVersionInfo + 6);
if (_wcsicmp(VsVersionInfoszKey, L"VS_VERSION_INFO") == 0) {
auto p = reinterpret_cast<PBYTE>(VsVersionInfoszKey + _countof(L"VS_VERSION_INFO"));
while (NewImage.PointerToRva(p) % sizeof(DWORD)) {
++p;
}
if (reinterpret_cast<VS_FIXEDFILEINFO*>(p)->dwSignature == VS_FFI_SIGNATURE) {
NewImage._VsFixedFileInfo = reinterpret_cast<VS_FIXEDFILEINFO*>(p);
VS_FII_Ok = true;
}
}
}
}
}
}
}
}
}
return NewImage;
}
[[nodiscard]]
PIMAGE_DOS_HEADER ImageInterpreter::ImageDosHeader() const noexcept {
return _DosHeader;
}
[[nodiscard]]
PIMAGE_NT_HEADERS ImageInterpreter::ImageNtHeaders() const noexcept {
return _NtHeaders;
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionTable() const noexcept {
return _SectionHeaderTable;
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeader(PCSTR lpszSectionName) const {
uint64_t NameValue = 0;
for (int i = 0; i < sizeof(NameValue) && lpszSectionName[i]; ++i)
reinterpret_cast<PSTR>(&NameValue)[i] = lpszSectionName[i];
auto it = _SectionNameTable.find(NameValue);
if (it == _SectionNameTable.end()) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Target section header is not found."))
.AddHint(std::xstring::format(TEXT("lpszSectionName = %s"), lpszSectionName));
}
return &_SectionHeaderTable[it->second];
}
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageInterpreter::ImageSectionHeader(uintptr_t Rva) const {
auto it = _SectionAddressTable.upper_bound(Rva);
if (it != _SectionAddressTable.begin()) {
--it;
}
auto SectionHeader = &_SectionHeaderTable[it->second];
uintptr_t SectionRvaBegin = SectionHeader->VirtualAddress;
uintptr_t SectionRvaEnd = SectionRvaBegin + SectionHeader->Misc.VirtualSize;
if (SectionRvaBegin <= Rva && Rva < SectionRvaEnd) {
return SectionHeader;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Target section header is not found."))
.AddHint(std::xstring::format(TEXT("Rva = 0x%zx"), Rva));
}
}
[[nodiscard]]
uintptr_t ImageInterpreter::RvaToFileOffset(uintptr_t Rva) const {
auto SectionHeader = ImageSectionHeader(Rva);
return SectionHeader->PointerToRawData + (Rva - static_cast<uintptr_t>(SectionHeader->VirtualAddress));
}
[[nodiscard]]
uintptr_t ImageInterpreter::FileOffsetToRva(uintptr_t FileOffset) const {
auto it = _SectionOffsetTable.upper_bound(FileOffset);
if (it != _SectionOffsetTable.begin()) {
--it;
}
auto SectionHeader = &_SectionHeaderTable[it->second];
uintptr_t SectionFileOffsetBegin = SectionHeader->PointerToRawData;
uintptr_t SectionFileOffsetEnd = SectionFileOffsetBegin + SectionHeader->SizeOfRawData;
if (SectionFileOffsetBegin <= FileOffset && FileOffset < SectionFileOffsetEnd) {
return SectionHeader->VirtualAddress + (FileOffset - SectionHeader->PointerToRawData);
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Target section header is not found."))
.AddHint(std::xstring::format(TEXT("FileOffset = 0x%zx"), FileOffset));
}
}
[[nodiscard]]
bool ImageInterpreter::IsRvaRangeInRelocTable(uintptr_t Rva, size_t Size) const {
auto it = _RelocationAddressTable.upper_bound(Rva);
if (it != _RelocationAddressTable.begin()) {
--it;
}
return it->first <= Rva && Rva < it->first + it->second;
}
DWORD ImageInterpreter::ImageFileMajorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwFileVersionMS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
DWORD ImageInterpreter::ImageFileMinorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwFileVersionLS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
DWORD ImageInterpreter::ImageProductMajorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwProductVersionMS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
DWORD ImageInterpreter::ImageProductMinorVersion() const {
if (_VsFixedFileInfo) {
return _VsFixedFileInfo->dwProductVersionLS;
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Image does not have version info."));
}
}
}
+173
View File
@@ -0,0 +1,173 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <Exception.hpp>
#include <windows.h>
#include <map>
#include <utility>
#include <type_traits>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\ImageInterpreter.hpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
class ImageInterpreter {
private:
PIMAGE_DOS_HEADER _DosHeader;
PIMAGE_NT_HEADERS _NtHeaders;
PIMAGE_SECTION_HEADER _SectionHeaderTable;
std::map<uint64_t, size_t> _SectionNameTable;
std::map<uintptr_t, size_t> _SectionAddressTable;
std::map<uintptr_t, size_t> _SectionOffsetTable;
std::map<uintptr_t, size_t> _RelocationAddressTable;
VS_FIXEDFILEINFO* _VsFixedFileInfo;
ImageInterpreter();
public:
[[nodiscard]]
static ImageInterpreter ParseImage(PVOID PtrToImageBase, bool DisableRelocationParsing = false);
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageBase() const noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__PtrType>(_DosHeader);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageOffset(size_t Offset) const noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__PtrType>(reinterpret_cast<char*>(_DosHeader) + Offset);
}
[[nodiscard]]
PIMAGE_DOS_HEADER ImageDosHeader() const noexcept;
[[nodiscard]]
PIMAGE_NT_HEADERS ImageNtHeaders() const noexcept;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionTable() const noexcept;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeader(PCSTR lpszSectionName) const;
[[nodiscard]]
PIMAGE_SECTION_HEADER ImageSectionHeader(uintptr_t Rva) const;
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionView(PCSTR lpszSectionName, size_t Offset = 0) const {
return ImageOffset<__PtrType>(ImageSectionHeader(lpszSectionName)->PointerToRawData + Offset);
}
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType ImageSectionView(PIMAGE_SECTION_HEADER SectionHeader, size_t Offset = 0) const {
return ImageOffset<__PtrType>(SectionHeader->PointerToRawData + Offset);
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PCSTR lpszSectionName, __Hint&& Hint) const {
return SearchSection<__ReturnType>(ImageSectionHeader(lpszSectionName), std::forward<__Hint>(Hint));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PCSTR lpszSectionName, size_t Offset, __Hint&& Hint) const {
return SearchSection<__ReturnType>(ImageSectionHeader(lpszSectionName), Offset, std::forward<__Hint>(Hint));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PIMAGE_SECTION_HEADER SectionHeader, __Hint&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto begin = ImageSectionView<const uint8_t*>(SectionHeader);
auto end = begin + SectionHeader->Misc.VirtualSize;
for (; begin < end; ++begin) {
if (Hint(begin) == true) {
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(begin));
}
}
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Data is not found."));
}
template<typename __ReturnType, typename __Hint>
[[nodiscard]]
__ReturnType SearchSection(PIMAGE_SECTION_HEADER SectionHeader, size_t Offset, __Hint&& Hint) const {
static_assert(std::is_pointer_v<__ReturnType>);
auto begin = ImageSectionView<const uint8_t*>(SectionHeader) + Offset;
auto end = begin + SectionHeader->Misc.VirtualSize;
for (; begin < end; ++begin) {
if (Hint(begin) == true) {
return reinterpret_cast<__ReturnType>(const_cast<uint8_t*>(begin));
}
}
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Data is not found."));
}
[[nodiscard]]
uintptr_t RvaToFileOffset(uintptr_t Rva) const;
[[nodiscard]]
uintptr_t FileOffsetToRva(uintptr_t FileOffset) const;
template<typename __PtrType = PVOID>
[[nodiscard]]
__PtrType RvaToPointer(uintptr_t Rva) const {
static_assert(std::is_pointer_v<__PtrType>);
return ImageOffset<__PtrType>(RvaToFileOffset(Rva));
}
template<typename __PtrType>
[[nodiscard]]
uintptr_t PointerToRva(__PtrType Ptr) const {
static_assert(std::is_pointer_v<__PtrType>);
return FileOffsetToRva(reinterpret_cast<const volatile char*>(Ptr) - reinterpret_cast<const volatile char*>(_DosHeader));
}
template<typename __PtrType>
[[nodiscard]]
__PtrType FileOffsetToPointer(uintptr_t FileOffset) const noexcept {
return ImageOffset<__PtrType>(FileOffset);
}
template<typename __PtrType>
[[nodiscard]]
uintptr_t PointerToFileOffset(__PtrType Ptr) const noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<const volatile char*>(Ptr) - reinterpret_cast<const volatile char*>(_DosHeader);
}
[[nodiscard]]
bool IsRvaRangeInRelocTable(uintptr_t Rva, size_t Size) const;
[[nodiscard]]
DWORD ImageFileMajorVersion() const;
[[nodiscard]]
DWORD ImageFileMinorVersion() const;
[[nodiscard]]
DWORD ImageProductMajorVersion() const;
[[nodiscard]]
DWORD ImageProductMinorVersion() const;
};
}
+176
View File
@@ -0,0 +1,176 @@
#include <stddef.h>
#include <stdint.h>
#include <tchar.h>
#include <windows.h>
#include <ExceptionWin32.hpp>
#include <xstring.hpp>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\Misc.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
template<typename __Type>
static inline bool ProbeForRead(const void* p, void* out) {
__try {
*reinterpret_cast<__Type*>(out) = *reinterpret_cast<const __Type*>(p);
return true;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
}
//
// Print memory data in [lpMemBegin, lpMemEnd)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMemBegin, const void* lpMemEnd, const void* lpBase) noexcept {
auto pbBegin = reinterpret_cast<const uint8_t*>(lpMemBegin);
auto pbEnd = reinterpret_cast<const uint8_t*>(lpMemEnd);
auto pbBase = reinterpret_cast<const uint8_t*>(lpBase);
if (pbBegin >= pbEnd)
return;
while (reinterpret_cast<uintptr_t>(pbBegin) % 16)
pbBegin--;
while (reinterpret_cast<uintptr_t>(pbEnd) % 16)
pbEnd++;
while (pbBegin < pbEnd) {
uint16_t Values[16] = {};
if (pbBase) {
uintptr_t d = pbBegin >= lpBase ? pbBegin - pbBase : pbBase - pbBegin;
if (pbBegin >= lpBase) {
_tprintf_s(TEXT("+0x%.*zx "), static_cast<int>(2 * sizeof(void*)), d);
} else {
_tprintf_s(TEXT("-0x%.*zx "), static_cast<int>(2 * sizeof(void*)), d);
}
} else {
_tprintf_s(TEXT("0x%.*zx "), static_cast<int>(2 * sizeof(void*)), reinterpret_cast<uintptr_t>(pbBegin));
}
for (int i = 0; i < 16; ++i) {
if (pbBegin + i < lpMemBegin || pbBegin + i >= lpMemEnd) {
_tprintf_s(TEXT(" "));
Values[i] = 0xfffe;
} else if (ProbeForRead<uint8_t>(pbBegin + i, Values + i)) {
_tprintf_s(TEXT("%02x "), Values[i]);
} else {
_tprintf_s(TEXT("?? "));
Values[i] = 0xffff;
}
}
_tprintf_s(TEXT(" "));
for (int i = 0; i < 16; ++i) { // NOLINT
if (0x20 <= Values[i] && Values[i] < 0x7f) {
_tprintf_s(TEXT("%c"), Values[i]);
} else if (Values[i] == 0xfffe) {
_tprintf_s(TEXT(" "));
} else {
_tprintf_s(TEXT("."));
}
}
_tprintf_s(TEXT("\n"));
pbBegin += 0x10;
}
}
//
// Print memory data in [lpMem, lpMem + cbMem)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMem, size_t cbMem, const void* lpBase) noexcept {
PrintMemory(lpMem, reinterpret_cast<const uint8_t*>(lpMem) + cbMem, lpBase);
}
void PrintBytes(const void* lpMemBegin, const void* lpMemEnd) noexcept {
auto pbMemBegin = reinterpret_cast<const uint8_t*>(lpMemBegin);
auto pbMemEnd = reinterpret_cast<const uint8_t*>(lpMemEnd);
if (pbMemBegin < pbMemEnd) {
uint8_t v;
if (ProbeForRead<uint8_t>(pbMemBegin, &v)) {
_tprintf_s(TEXT("%.2x"), v);
} else {
_tprintf_s(TEXT("??"));
}
++pbMemBegin;
}
while (pbMemBegin < pbMemEnd) {
uint8_t v;
if (ProbeForRead<uint8_t>(pbMemBegin, &v)) {
_tprintf_s(TEXT(" %.2x"), v);
} else {
_tprintf_s(TEXT(" ??"));
}
++pbMemBegin;
}
}
void PrintBytes(const void* lpMem, size_t cbMem) noexcept {
PrintBytes(lpMem, reinterpret_cast<const char*>(lpMem) + cbMem);
}
[[nodiscard]]
bool IsValidDirectoryPath(PCTSTR lpszDirectoryPath) noexcept {
DWORD Attribute = GetFileAttributes(lpszDirectoryPath);
return Attribute != INVALID_FILE_ATTRIBUTES && (Attribute & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
[[nodiscard]]
bool IsValidFilePath(PCTSTR lpszFilePath) noexcept {
DWORD Attribute = GetFileAttributes(lpszFilePath);
return Attribute != INVALID_FILE_ATTRIBUTES && (Attribute & FILE_ATTRIBUTE_DIRECTORY) == 0;
}
[[nodiscard]]
bool IsWineEnvironment() noexcept {
static bool Checked = false;
static bool IsWineEnv = false;
if (Checked == false) {
auto hNtdll = GetModuleHandle(TEXT("ntdll.dll"));
IsWineEnv = hNtdll && GetProcAddress(hNtdll, "wine_get_version") != nullptr;
Checked = true;
}
return IsWineEnv;
}
std::xstring GetCurrentWorkingDirectory() {
std::xstring CurrentDirectory;
auto s = ::GetCurrentDirectory(0, NULL);
if (s == 0) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("GetCurrentDirectory failed"));
}
CurrentDirectory.resize(static_cast<size_t>(s) - 1);
s = ::GetCurrentDirectory(s, CurrentDirectory.data());
if (s == 0) {
throw Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("GetCurrentDirectory failed"));
}
return CurrentDirectory;
}
}
+74
View File
@@ -0,0 +1,74 @@
#pragma once
#include <stddef.h>
#include <tchar.h>
#include <windows.h>
#include <type_traits>
#include <xstring.hpp>
#define LOG_SUCCESS(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[+] " fmt "\n"), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[+] " fmt "\n"), __VA_ARGS__)
#define LOG_FAILURE(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[-] " fmt "\n"), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[-] " fmt "\n"), __VA_ARGS__)
#define LOG_HINT(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[*] " fmt "\n"), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[*] " fmt "\n"), __VA_ARGS__)
#define LOG_SELECT(tab, fmt, ...) tab ? _tprintf_s(TEXT("%*c[?] " fmt " "), tab, ' ', __VA_ARGS__) : _tprintf_s(TEXT("[?] " fmt " "), __VA_ARGS__)
namespace nkg {
template<size_t __Len>
constexpr size_t literal_length(const char (&)[__Len]) noexcept {
return __Len - 1;
}
template<typename __PtrType1, typename __PtrType2>
constexpr auto address_delta(__PtrType1 p1, __PtrType2 p2) noexcept {
static_assert(std::is_pointer_v<__PtrType1>);
static_assert(std::is_pointer_v<__PtrType2>);
return reinterpret_cast<const volatile char*>(p1) - reinterpret_cast<const volatile char*>(p2);
}
template<typename __PtrType>
constexpr __PtrType address_offset(__PtrType p, decltype(static_cast<char*>(nullptr) - static_cast<char*>(nullptr)) offset) noexcept {
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__PtrType>(
const_cast<char*>(reinterpret_cast<const volatile char*>(p)) + offset
);
}
template<typename __ReturnType, typename __PtrType>
constexpr __ReturnType address_offset_cast(__PtrType p, decltype(static_cast<char*>(nullptr) - static_cast<char*>(nullptr)) offset) noexcept {
static_assert(std::is_pointer_v<__ReturnType>);
static_assert(std::is_pointer_v<__PtrType>);
return reinterpret_cast<__ReturnType>(
const_cast<char*>(reinterpret_cast<const volatile char*>(p)) + offset
);
}
//
// Print memory data in [lpMemBegin, lpMemEnd)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMemBegin, const void* lpMemEnd, const void* lpBase) noexcept;
//
// Print memory data in [lpMem, lpMem + cbMem)
// If `base` is not nullptr, print address as offset. Otherwise, as absolute address.
// NOTICE:
// `base` must >= `from`
//
void PrintMemory(const void* lpMem, size_t cbMem, const void* lpBase) noexcept;
void PrintBytes(const void* lpMemBegin, const void* lpMemEnd) noexcept;
void PrintBytes(const void* lpMem, size_t cbMem) noexcept;
[[nodiscard]]
bool IsValidDirectoryPath(PCTSTR lpszDirectoryPath) noexcept;
[[nodiscard]]
bool IsValidFilePath(PCTSTR lpszFilePath) noexcept;
[[nodiscard]]
bool IsWineEnvironment() noexcept;
std::xstring GetCurrentWorkingDirectory();
}
+167 -130
View File
@@ -2,179 +2,216 @@
#include <openssl/crypto.h>
#include <openssl/blowfish.h>
#include <openssl/sha.h>
#include <string>
#ifdef _DEBUG
#pragma comment(lib, "libcryptoMTd.lib")
#else
#pragma comment(lib, "libcryptoMT.lib")
#endif
#pragma comment(lib, "WS2_32.lib") // some symbol are used in OpenSSL static lib
#pragma comment(lib, "Crypt32.lib") // some symbol are used in OpenSSL static lib
#include <stdexcept>
class Navicat11Crypto {
protected:
BF_KEY BlowfishKey;
using BlockType = uint8_t[BF_BLOCK];
void BytesToHex(const void* src, size_t len, char* dst) {
BF_KEY _BlowfishKey;
template<bool __UpperCase = true>
static void _BytesToHex(const void* src, size_t len, char* dst) noexcept {
auto pb_src = reinterpret_cast<const uint8_t*>(src);
for (size_t i = 0; i < len; ++i) {
char h = reinterpret_cast<const uint8_t*>(src)[i] >> 4;
char l = reinterpret_cast<const uint8_t*>(src)[i] & 0x0F;
char h = pb_src[i] >> 4;
char l = pb_src[i] & 0x0F;
if constexpr (__UpperCase) {
h += h >= 10 ? 'A' - 10 : '0';
l += l >= 10 ? 'A' - 10 : '0';
} else {
h += h >= 10 ? 'a' - 10 : '0';
l += l >= 10 ? 'a' - 10 : '0';
}
h += h >= 10 ? 'A' - 10 : '0';
l += l >= 10 ? 'A' - 10 : '0';
dst[2 * i] = h;
dst[2 * i + 1] = l;
}
}
bool CheckHex(const char* src, size_t len) {
if (len % 2 != 0)
return false;
for (size_t i = 0; i < len; i += 2) {
char h = src[i];
char l = src[i + 1];
if (src[i] < '0' || src[i] > 'F')
return false;
if (src[i] < 'A' && src[i] > '9')
return false;
if (src[i + 1] < '0' || src[i + 1] > 'F')
return false;
if (src[i + 1] < 'A' && src[i + 1] > '9')
return false;
}
return true;
}
void HexToBytes(const char* src, size_t len, void* dst) {
static void _HexToBytes(const char* src, size_t len, void* dst) {
auto pb_dst = reinterpret_cast<uint8_t*>(dst);
for (size_t i = 0; i < len; i += 2) {
uint8_t h = src[i];
uint8_t l = src[i + 1];
h -= h > '9' ? 'A' - 10 : '0';
l -= l > '9' ? 'A' - 10 : '0';
if ('0' <= h && h <= '9') {
h -= '0';
} else if ('A' <= h && h <= 'F') {
h -= 'A';
} else if ('a' <= h && h <= 'f') {
h -= 'a';
} else {
throw std::invalid_argument("Non-hex character detected.");
}
reinterpret_cast<uint8_t*>(dst)[i / 2] = (h << 4) ^ l;
if ('0' <= l && l <= '9') {
l -= '0';
} else if ('A' <= l && l <= 'F') {
l -= 'A';
} else if ('a' <= l && l <= 'f') {
l -= 'a';
} else {
throw std::invalid_argument("Non-hex character detected.");
}
pb_dst[i / 2] = (h << 4) ^ l;
}
}
static void _XorBlock(BlockType& a, const BlockType& b) noexcept {
reinterpret_cast<uint64_t&>(a) ^= reinterpret_cast<const uint64_t&>(b);
}
[[nodiscard]]
std::string _EncryptString(const void* lpPlaintext, size_t cbPlaintext) const {
std::string Ciphertext;
if (cbPlaintext) {
Ciphertext.resize(2 * cbPlaintext);
alignas(sizeof(BlockType)) BlockType CV = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
alignas(sizeof(BlockType)) BlockType Block;
auto lpPlaintextBlock = reinterpret_cast<const uint8_t*>(lpPlaintext);
auto lpCiphertextHexBlock = Ciphertext.data();
auto BlockCount = cbPlaintext / BF_BLOCK;
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < BlockCount; ++i, lpPlaintextBlock += sizeof(BlockType), lpCiphertextHexBlock += 2 * sizeof(BlockType)) {
memcpy(Block, lpPlaintextBlock, sizeof(BlockType));
_XorBlock(Block, CV);
BF_ecb_encrypt(Block, Block, &_BlowfishKey, BF_ENCRYPT);
_XorBlock(CV, Block);
_BytesToHex(Block, sizeof(Block), lpCiphertextHexBlock);
}
auto LeftByteCount = cbPlaintext % sizeof(BlockType);
if (LeftByteCount) {
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < LeftByteCount; ++i) {
CV[i] ^= lpPlaintextBlock[i];
}
_BytesToHex(CV, LeftByteCount, lpCiphertextHexBlock);
}
}
return Ciphertext;
}
[[nodiscard]]
std::string _DecryptString(const char* lpCiphertext, size_t cbCiphertext) const {
std::string Plaintext;
if (cbCiphertext) {
if (cbCiphertext % 2) {
throw std::invalid_argument("Ciphertext is not a hex string.");
}
Plaintext.resize(cbCiphertext / 2);
alignas(sizeof(BlockType)) BlockType CV = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
alignas(sizeof(BlockType)) BlockType Block;
auto lpPlaintextBlock = Plaintext.data();
auto lpCiphertextHexBlock = lpCiphertext;
auto BlockCount = cbCiphertext / (2 * sizeof(BlockType));
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < BlockCount; ++i, lpPlaintextBlock += sizeof(BlockType), lpCiphertextHexBlock += 2 * sizeof(BlockType)) {
alignas(sizeof(BlockType)) BlockType CiphertextBlock;
_HexToBytes(lpCiphertextHexBlock, 2 * sizeof(BlockType), CiphertextBlock);
memcpy(Block, CiphertextBlock, sizeof(BlockType));
BF_ecb_encrypt(Block, Block, &_BlowfishKey, BF_DECRYPT);
_XorBlock(Block, CV);
_XorBlock(CV, CiphertextBlock);
memcpy(lpPlaintextBlock, Block, sizeof(BlockType));
}
auto LeftHexCount = cbCiphertext % (2 * sizeof(BlockType));
if (LeftHexCount) {
_HexToBytes(lpCiphertextHexBlock, LeftHexCount, Block);
BF_ecb_encrypt(CV, CV, &_BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < LeftHexCount / 2; ++i) {
lpPlaintextBlock[i] = Block[i] ^ CV[i];
}
}
}
return Plaintext;
}
public:
Navicat11Crypto() {
static const uint8_t PresetKey[20] = {
Navicat11Crypto() noexcept {
static const uint8_t PresetKey[SHA_DIGEST_LENGTH] = {
0x42, 0xCE, 0xB2, 0x71, 0xA5, 0xE4, 0x58, 0xB7,
0x4A, 0xEA, 0x93, 0x94, 0x79, 0x22, 0x35, 0x43,
0x91, 0x87, 0x33, 0x40
};
BF_set_key(&BlowfishKey, SHA_DIGEST_LENGTH, PresetKey);
BF_set_key(&_BlowfishKey, sizeof(PresetKey), PresetKey);
}
Navicat11Crypto(const void* UserKey, size_t Length) {
SetKey(UserKey, Length);
Navicat11Crypto(const void* lpUserKey, size_t cbUserKey) noexcept {
SetKey(lpUserKey, cbUserKey);
}
void SetKey(const void* UserKey, size_t Length) {
unsigned char MessageDigest[SHA_DIGEST_LENGTH];
Navicat11Crypto(const std::initializer_list<uint8_t>& UserKey) noexcept {
SetKey(UserKey);
}
void SetKey(const void* lpUserKey, size_t cbUserKey) noexcept {
uint8_t MessageDigest[SHA_DIGEST_LENGTH];
BF_set_key(
&_BlowfishKey,
sizeof(MessageDigest),
SHA1(reinterpret_cast<const uint8_t*>(lpUserKey), cbUserKey, MessageDigest)
);
SHA1(reinterpret_cast<const unsigned char*>(UserKey), Length, MessageDigest);
BF_set_key(&BlowfishKey, SHA_DIGEST_LENGTH, MessageDigest);
OPENSSL_cleanse(MessageDigest, SHA_DIGEST_LENGTH);
}
std::string EncryptString(const void* srcBytes, size_t srclen) {
std::string ret;
uint8_t CV[BF_BLOCK] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
void SetKey(const std::initializer_list<uint8_t>& UserKey) noexcept {
uint8_t MessageDigest[SHA_DIGEST_LENGTH];
if (srclen == 0)
return ret;
ret.resize(2 * srclen);
BF_set_key(
&_BlowfishKey,
sizeof(MessageDigest),
SHA1(UserKey.begin(), UserKey.size(), MessageDigest)
);
BF_ecb_encrypt(CV, CV, &BlowfishKey, BF_ENCRYPT);
const uint64_t* blocks = reinterpret_cast<const uint64_t*>(srcBytes);
size_t blocks_len = srclen / BF_BLOCK;
for (size_t i = 0; i < blocks_len; ++i) {
union {
uint8_t byte[8];
uint64_t qword;
} temp;
temp.qword = blocks[i];
temp.qword ^= *reinterpret_cast<uint64_t*>(CV);
BF_ecb_encrypt(temp.byte, temp.byte, &BlowfishKey, BF_ENCRYPT);
*reinterpret_cast<uint64_t*>(CV) ^= temp.qword;
BytesToHex(&temp, 8, ret.data() + 16 * i);
}
if (srclen % BF_BLOCK) {
BF_ecb_encrypt(CV, CV, &BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < srclen % BF_BLOCK; ++i) {
CV[i] ^= reinterpret_cast<const uint8_t*>(blocks + blocks_len)[i];
}
BytesToHex(CV, srclen % BF_BLOCK, ret.data() + 16 * blocks_len);
}
return ret;
OPENSSL_cleanse(MessageDigest, SHA_DIGEST_LENGTH);
}
std::string DecryptString(const char* srchex, size_t srclen) {
std::string ret;
uint8_t CV[BF_BLOCK] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
if (CheckHex(srchex, srclen) == false)
return ret;
ret.resize(srclen / 2);
BF_ecb_encrypt(CV, CV, &BlowfishKey, BF_ENCRYPT);
const char(*blocks)[16] = reinterpret_cast<const char(*)[16]>(srchex);
size_t blocks_len = srclen / 16;
for (size_t i = 0; i < blocks_len; ++i) {
union {
uint8_t byte[8];
uint64_t qword;
} temp, temp2;
HexToBytes(blocks[i], 16, temp.byte);
temp2.qword = temp.qword;
BF_ecb_encrypt(temp.byte, temp.byte, &BlowfishKey, BF_DECRYPT);
temp.qword ^= *reinterpret_cast<uint64_t*>(CV);
*reinterpret_cast<uint64_t*>(ret.data() + 8 * i) = temp.qword;
*reinterpret_cast<uint64_t*>(CV) ^= temp2.qword;
}
if (srclen % 16) {
union {
uint8_t byte[8];
uint64_t qword;
} temp = { };
HexToBytes(blocks[blocks_len], srclen % 16, temp.byte);
BF_ecb_encrypt(CV, CV, &BlowfishKey, BF_ENCRYPT);
for (size_t i = 0; i < (srclen % 16) / 2; ++i)
ret[blocks_len * 8 + i] = temp.byte[i] ^ CV[i];
}
return ret;
[[nodiscard]]
std::string EncryptString(const std::string& Plaintext) const {
return _EncryptString(Plaintext.c_str(), Plaintext.length());
}
void Clear() {
OPENSSL_cleanse(&BlowfishKey, sizeof(BlowfishKey));
[[nodiscard]]
std::string DecryptString(const std::string& Ciphertext) const {
return _DecryptString(Ciphertext.c_str(), Ciphertext.length());
}
~Navicat11Crypto() {
void Clear() noexcept {
OPENSSL_cleanse(&_BlowfishKey, sizeof(_BlowfishKey));
}
~Navicat11Crypto() noexcept {
Clear();
}
};
+82
View File
@@ -0,0 +1,82 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution0.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
const char PatchSolution0::Keyword[461] =
"-----BEGIN PUBLIC KEY-----\r\n"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I\r\n"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv\r\n"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF\r\n"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2\r\n"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt\r\n"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ\r\n"
"awIDAQAB\r\n"
"-----END PUBLIC KEY-----\r\n";
[[nodiscard]]
bool PatchSolution0::FindPatchOffset() noexcept {
try {
_PatchOffset = _Image.PointerToFileOffset(
_Image.SearchSection<uint8_t*>(".rsrc", [](const uint8_t* p) {
__try {
return memcmp(p, Keyword, literal_length(Keyword)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
})
);
LOG_SUCCESS(0, "PatchSolution0 ...... Ready to apply");
LOG_HINT(4, "Patch offset = +0x%.8zx", _PatchOffset);
return true;
} catch (nkg::Exception&) {
_PatchOffset = InvalidOffset;
LOG_FAILURE(0, "PatchSolution0 ...... Omitted");
return false;
}
}
[[nodiscard]]
bool PatchSolution0::CheckKey(const RSACipher& Cipher) const noexcept {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
return szPublicKey.length() == literal_length(Keyword);
}
void PatchSolution0::MakePatch(const RSACipher& Cipher) const {
if (_PatchOffset == InvalidOffset) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution0 has not been ready yet."));
}
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution0 *"));
_putts(TEXT("*******************************************************"));
LOG_HINT(0, "Previous:");
PrintMemory(_Image.ImageOffset(_PatchOffset), literal_length(Keyword), _Image.ImageBase());
memcpy(_Image.ImageOffset(_PatchOffset), szPublicKey.c_str(), literal_length(Keyword));
LOG_HINT(0, "After:");
PrintMemory(_Image.ImageOffset(_PatchOffset), literal_length(Keyword), _Image.ImageBase());
_putts(TEXT(""));
}
}
+308
View File
@@ -0,0 +1,308 @@
#include "PatchSolutions.hpp"
#include "NavicatCrypto.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution1.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
static Navicat11Crypto g_NavicatCipher = Navicat11Crypto("23970790", 8);
const char PatchSolution1::Keyword0[160 + 1] =
"D75125B70767B94145B47C1CB3C0755E"
"7CCB8825C5DCE0C58ACF944E08280140"
"9A02472FAFFD1CD77864BB821AE36766"
"FEEDE6A24F12662954168BFA314BD950"
"32B9D82445355ED7BC0B880887D650F5";
const char PatchSolution1::Keyword1[4 + 1] =
"\xfe\xea\xbc\x01";
const char PatchSolution1::Keyword2[742 + 1] =
"E1CED09B9C2186BF71A70C0FE2F1E0AE"
"F3BD6B75277AAB20DFAF3D110F75912B"
"FB63AC50EC4C48689D1502715243A79F"
"39FF2DE2BF15CE438FF885745ED54573"
"850E8A9F40EE2FF505EB7476F95ADB78"
"3B28CA374FAC4632892AB82FB3BF4715"
"FCFE6E82D03731FC3762B6AAC3DF1C3B"
"C646FE9CD3C62663A97EE72DB932A301"
"312B4A7633100C8CC357262C39A2B3A6"
"4B224F5276D5EDBDF0804DC3AC4B8351"
"62BB1969EAEBADC43D2511D6E0239287"
"81B167A48273B953378D3D2080CC0677"
"7E8A2364F0234B81064C5C739A8DA28D"
"C5889072BF37685CBC94C2D31D0179AD"
"86D8E3AA8090D4F0B281BE37E0143746"
"E6049CCC06899401264FA471C016A96C"
"79815B55BBC26B43052609D9D175FBCD"
"E455392F10E51EC162F51CF732E6BB39"
"1F56BBFD8D957DF3D4C55B71CEFD54B1"
"9C16D458757373E698D7E693A8FC3981"
"5A8BF03BA05EA8C8778D38F9873D62B4"
"460F41ACF997C30E7C3AF025FA171B5F"
"5AD4D6B15E95C27F6B35AD61875E5505"
"449B4E";
const char PatchSolution1::Keyword3[4 + 1] =
"\x59\x08\x01\x00";
const char PatchSolution1::Keyword4[5 + 1] =
"92933";
[[nodiscard]]
bool PatchSolution1::FindPatchOffset() noexcept {
try {
PIMAGE_SECTION_HEADER SectionHeader_text = _Image.ImageSectionHeader(".text");
PIMAGE_SECTION_HEADER SectionHeader_rdata = _Image.ImageSectionHeader(".rdata");
const uint8_t* pbPatch[_countof(_PatchOffset)] = {};
pbPatch[0] = _Image.SearchSection<const uint8_t*>(SectionHeader_rdata, [](const uint8_t* p) {
__try {
return memcmp(p, Keyword0, sizeof(Keyword0)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
pbPatch[2] = _Image.SearchSection<const uint8_t*>(SectionHeader_rdata, [](const uint8_t* p) {
__try {
return memcmp(p, Keyword2, sizeof(Keyword2)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
pbPatch[4] = _Image.SearchSection<const uint8_t*>(SectionHeader_rdata, [](const uint8_t* p) {
__try {
return memcmp(p, Keyword4, sizeof(Keyword4)) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
pbPatch[1] = _Image.SearchSection<const uint8_t*>(SectionHeader_text, [&pbPatch](const uint8_t* p) {
__try {
if (memcmp(p, Keyword1, literal_length(Keyword1)) == 0) {
// Keyword3 must be close to Keyword1
for (auto j = p - 64; j < p + 64; ++j) {
if (memcmp(j, Keyword3, literal_length(Keyword3)) == 0) {
pbPatch[3] = j;
return true;
}
}
}
return false;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = _Image.PointerToFileOffset(pbPatch[i]);
}
_PatchSize[0] = literal_length(Keyword0);
while (pbPatch[0][_PatchSize[0] + 1] == 0 && _PatchSize[0] < literal_length(Keyword0) + literal_length("29158142") - 1) {
++_PatchSize[0];
}
_PatchSize[1] = sizeof(uint32_t);
_PatchSize[2] = literal_length(Keyword2);
while (pbPatch[2][_PatchSize[2] + 1] == 0 && _PatchSize[2] < literal_length(Keyword2) + literal_length("67673") - 1) {
++_PatchSize[2];
}
_PatchSize[3] = sizeof(uint32_t);
_PatchSize[4] = literal_length(Keyword4);
LOG_SUCCESS(0, "PatchSolution1 ...... Ready to apply");
LOG_HINT(4, "[0] Patch offset = +0x%.8zx", _PatchOffset[0]);
LOG_HINT(4, "[1] Patch offset = +0x%.8zx", _PatchOffset[1]);
LOG_HINT(4, "[2] Patch offset = +0x%.8zx", _PatchOffset[2]);
LOG_HINT(4, "[3] Patch offset = +0x%.8zx", _PatchOffset[3]);
LOG_HINT(4, "[4] Patch offset = +0x%.8zx", _PatchOffset[4]);
return true;
} catch (nkg::Exception&) {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
_PatchSize[i] = 0;
}
LOG_FAILURE(0, "PatchSolution1 ...... Omitted");
return false;
}
}
[[nodiscard]]
bool PatchSolution1::CheckKey(const RSACipher& Cipher) const noexcept {
if (_PatchSize[0] && _PatchSize[1] && _PatchSize[2] && _PatchSize[3] && _PatchSize[4]) {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
auto szPublicKeyEncrypted = g_NavicatCipher.EncryptString(szPublicKey);
if (szPublicKeyEncrypted.length() != 920) {
return false;
}
// we require the chars in [p1, p2) of szPublicKeyEncrypted must be number chars
size_t p1, p2;
p1 = _PatchSize[0];
p2 = literal_length(Keyword0) + literal_length("29158142");
if (('1' <= szPublicKeyEncrypted[p1] && szPublicKeyEncrypted[p1] <= '9') == false) {
return false;
}
for (size_t i = p1 + 1; i < p2; ++i) {
if (('0' <= szPublicKeyEncrypted[i] && szPublicKeyEncrypted[i] <= '9') == false) {
return false;
}
}
// we require the chars in [p1, p2) of szPublicKeyEncrypted must be number chars
p1 = literal_length(Keyword0) + literal_length("29158142") + _PatchSize[2];
p2 = literal_length(Keyword0) + literal_length("29158142") + literal_length(Keyword2) + literal_length("67673");
if (('1' <= szPublicKeyEncrypted[p1] && szPublicKeyEncrypted[p1] <= '9') == false) {
return false;
}
for (size_t i = p1 + 1; i < p2; ++i) {
if (('0' <= szPublicKeyEncrypted[i] && szPublicKeyEncrypted[i] <= '9') == false) {
return false;
}
}
return true;
} else {
return false;
}
}
void PatchSolution1::MakePatch(const RSACipher& Cipher) const {
if (_PatchSize[0] && _PatchSize[1] && _PatchSize[2] && _PatchSize[3] && _PatchSize[4]) {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto i = szPublicKey.find("\n"); i != std::string::npos; i = szPublicKey.find("\n", i + 2)) {
szPublicKey.replace(i, 1, "\r\n");
}
auto szPublicKeyEncrypted = g_NavicatCipher.EncryptString(szPublicKey);
//
// p0 p1 p2 p3 p4 p5
// Original encrypted public key layout: |160 chars|8 chars|742 chars|5 chars|5 chars|
// | |
// V V
// ImmValue1 ImmValue3
size_t p0, p1, p2, p3, p4, p5;
p0 = 0;
p1 = _PatchSize[0];
p2 = literal_length(Keyword0) + literal_length("29158142");
p3 = literal_length(Keyword0) + literal_length("29158142") + _PatchSize[2];
p4 = literal_length(Keyword0) + literal_length("29158142") + literal_length(Keyword2) + literal_length("67673");
p5 = literal_length(Keyword0) + literal_length("29158142") + literal_length(Keyword2) + literal_length("67673") + literal_length(Keyword4);
if (szPublicKeyEncrypted.length() != 920) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("szPublicKeyEncrypted.length() != 920"));
}
std::string EncryptedPEM0(szPublicKeyEncrypted.begin() + p0, szPublicKeyEncrypted.begin() + p1);
std::string EncryptedPEM1(szPublicKeyEncrypted.begin() + p1, szPublicKeyEncrypted.begin() + p2);
std::string EncryptedPEM2(szPublicKeyEncrypted.begin() + p2, szPublicKeyEncrypted.begin() + p3);
std::string EncryptedPEM3(szPublicKeyEncrypted.begin() + p3, szPublicKeyEncrypted.begin() + p4);
std::string EncryptedPEM4(szPublicKeyEncrypted.begin() + p4, szPublicKeyEncrypted.begin() + p5);
uint32_t ImmValue1 = std::stoul(EncryptedPEM1.c_str());
uint32_t ImmValue3 = std::stoul(EncryptedPEM3.c_str());
uint8_t* pbPatch[_countof(_PatchOffset)] = {};
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
pbPatch[i] = _Image.FileOffsetToPointer<uint8_t*>(_PatchOffset[i]);
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution1 *"));
_putts(TEXT("*******************************************************"));
// ----------------------------------
// process PatchOffsets[0]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[0], _PatchSize[0], _Image.ImageBase());
memcpy(pbPatch[0], EncryptedPEM0.data(), _PatchSize[0]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[0], _PatchSize[0], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[1]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[1], _PatchSize[1], _Image.ImageBase());
memcpy(pbPatch[1], &ImmValue1, _PatchSize[1]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[1], _PatchSize[1], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[2]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[2], _PatchSize[2], _Image.ImageBase());
memcpy(pbPatch[2], EncryptedPEM2.data(), _PatchSize[2]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[2], _PatchSize[2], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[3]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[3], _PatchSize[3], _Image.ImageBase());
memcpy(pbPatch[3], &ImmValue3, _PatchSize[3]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[3], _PatchSize[3], _Image.ImageBase());
_putts(TEXT(""));
// ----------------------------------
// process PatchOffsets[4]
// ----------------------------------
LOG_HINT(0, "Previous:");
PrintMemory(pbPatch[4], _PatchSize[4], _Image.ImageBase());
memcpy(pbPatch[4], EncryptedPEM4.data(), _PatchSize[4]);
LOG_HINT(0, "After:");
PrintMemory(pbPatch[4], _PatchSize[4], _Image.ImageBase());
_putts(TEXT(""));
} else {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution1 has not been ready yet."));
}
}
}
+511
View File
@@ -0,0 +1,511 @@
#include "PatchSolutions.hpp"
#include <vector>
#include <algorithm>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution2-amd64.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
/*
Keyword[0x188][5] is generated by the following python script:
-----Begin Python3 Script-----
meta = \
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I" \
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv" \
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF" \
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2" \
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt" \
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ" \
"awIDAQAB"
print('const uint8_t PatchSolution2::Keyword[0x188][5] = {')
for i in range(0, len(meta)):
i1 = '0x83, 0xf0, 0x%.2x' % ord(meta[i]) # asm('xor eax, meta[i]')
i2 = '0x88, 0x05' # asm_prefix('mov byte ptr ds:xxxxxxxxxxxxxxxx, al')
print(' { %s, %s }' % (i1, i2), end = ',\n' if i != len(meta) - 1 else '\n')
print('};')
-----End Python3 Script-----
*/
const uint8_t PatchSolution2::Keyword[0x188][5] = {
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x7a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x39, 0x88, 0x05 },
{ 0x83, 0xf0, 0x56, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x54, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x56, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x75, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x38, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x64, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x70, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x50, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4b, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x71, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x69, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x55, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x5a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x33, 0x88, 0x05 },
{ 0x83, 0xf0, 0x68, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x45, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x65, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x54, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x59, 0x88, 0x05 },
{ 0x83, 0xf0, 0x79, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x34, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x32, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x30, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x56, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x35, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x47, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x37, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x43, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x4f, 0x88, 0x05 },
{ 0x83, 0xf0, 0x46, 0x88, 0x05 },
{ 0x83, 0xf0, 0x48, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x66, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x67, 0x88, 0x05 },
{ 0x83, 0xf0, 0x7a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x58, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x62, 0x88, 0x05 },
{ 0x83, 0xf0, 0x52, 0x88, 0x05 },
{ 0x83, 0xf0, 0x53, 0x88, 0x05 },
{ 0x83, 0xf0, 0x76, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6d, 0x88, 0x05 },
{ 0x83, 0xf0, 0x74, 0x88, 0x05 },
{ 0x83, 0xf0, 0x31, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6e, 0x88, 0x05 },
{ 0x83, 0xf0, 0x72, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x37, 0x88, 0x05 },
{ 0x83, 0xf0, 0x73, 0x88, 0x05 },
{ 0x83, 0xf0, 0x57, 0x88, 0x05 },
{ 0x83, 0xf0, 0x36, 0x88, 0x05 },
{ 0x83, 0xf0, 0x63, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x78, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6c, 0x88, 0x05 },
{ 0x83, 0xf0, 0x6a, 0x88, 0x05 },
{ 0x83, 0xf0, 0x75, 0x88, 0x05 },
{ 0x83, 0xf0, 0x75, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x61, 0x88, 0x05 },
{ 0x83, 0xf0, 0x77, 0x88, 0x05 },
{ 0x83, 0xf0, 0x49, 0x88, 0x05 },
{ 0x83, 0xf0, 0x44, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x51, 0x88, 0x05 },
{ 0x83, 0xf0, 0x41, 0x88, 0x05 },
{ 0x83, 0xf0, 0x42, 0x88, 0x05 }
};
[[nodiscard]]
bool PatchSolution2::FindPatchOffset() noexcept {
try {
auto SectionHeader_text = _Image.ImageSectionHeader(".text");
auto SectionView_text = _Image.ImageSectionView<const uint8_t*>(SectionHeader_text);
const uint8_t* lpPatch[_countof(_PatchOffset)] = {};
std::vector<size_t> Hints;
DWORD PossibleRangeStart = 0xffffffff;
DWORD PossibleRangeEnd;
for (DWORD i = 0; i < SectionHeader_text->SizeOfRawData; ++i) {
if (memcmp(SectionView_text + i, Keyword[0], sizeof(Keyword[0])) == 0) {
size_t RRip = i + sizeof(Keyword[0]) + sizeof(uint32_t);
size_t RRipOffset = *reinterpret_cast<const uint32_t*>(SectionView_text + i + sizeof(Keyword[0]));
Hints.emplace_back(RRip + RRipOffset);
if (i < PossibleRangeStart) {
PossibleRangeStart = i;
}
}
}
PossibleRangeStart -= 0x1000;
PossibleRangeEnd = PossibleRangeStart + 0x100000;
// Keywords[0] should occur 9 times.
// Because there's only 9 'M' chars in `KeywordMeta`.
if (Hints.size() != 9) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.size() != 9"));
}
std::sort(Hints.begin(), Hints.end());
// assert
// if not satisfied, refuse to patch
if (Hints.back() - Hints.front() != 0x18360F8F8 - 0x18360F7D0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.back() - Hints.front() != 0x18360F8F8 - 0x18360F7D0"));
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
for (DWORD j = PossibleRangeStart; j < PossibleRangeEnd; ++j) {
if (memcmp(SectionView_text + j, Keyword[i], sizeof(Keyword[i])) == 0) {
size_t RRip = j + sizeof(Keyword[i]) + sizeof(uint32_t);
size_t RRipOffset = *reinterpret_cast<const uint32_t*>(SectionView_text + j + sizeof(Keyword[i]));
size_t Index = RRip + RRipOffset - Hints.front();
if (Index == i) {
lpPatch[i] = SectionView_text + j;
}
}
}
// if not found, refuse to patch
if (lpPatch[i] == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("A patch point is missing."));
}
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = _Image.PointerToFileOffset(lpPatch[i]);
}
LOG_SUCCESS(0, "PatchSolution2 ...... Ready to apply");
for (size_t i = 0; i < _countof(_PatchOffset); i += 4) {
static_assert(sizeof(_countof(_PatchOffset)) % 4 == 0);
LOG_HINT(4, "Patch offset[%zu ... %zu] = 0x%.8zx, 0x%.8zx, 0x%.8zx, 0x%.8zx", i, i + 3, _PatchOffset[i], _PatchOffset[i + 1], _PatchOffset[i + 2], _PatchOffset[i + 3]);
}
return true;
} catch (nkg::Exception&) {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
LOG_FAILURE(0, "PatchSolution2 ...... Omitted");
return false;
}
}
}
@@ -0,0 +1,92 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution2-generic.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
const char PatchSolution2::KeywordMeta[0x188 + 1] =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ"
"awIDAQAB";
[[nodiscard]]
bool PatchSolution2::CheckKey(const RSACipher& Cipher) const noexcept {
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
return szPublicKey.length() == literal_length(KeywordMeta);
}
void PatchSolution2::MakePatch(const RSACipher& Cipher) const {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
if (_PatchOffset[i] == InvalidOffset) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution2 has not been ready yet."));
}
}
auto pbImage = _Image.ImageBase<uint8_t*>();
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
if (szPublicKey.length() != literal_length(KeywordMeta)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("szPublicKey.length() != literal_length(KeywordMeta)"));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution2 *"));
_putts(TEXT("*******************************************************"));
for (size_t i = 0; i < _countof(_PatchOffset); i += 2) {
static_assert(_countof(_PatchOffset) % 2 == 0);
LOG_HINT(0, "+0x%.8zx: %.2x %.2x %.2x -> %.2x %.2x %.2x | +0x%.8zx: %.2x %.2x %.2x -> %.2x %.2x %.2x",
_PatchOffset[i],
pbImage[_PatchOffset[i]],
pbImage[_PatchOffset[i] + 1],
pbImage[_PatchOffset[i] + 2],
pbImage[_PatchOffset[i]],
pbImage[_PatchOffset[i] + 1],
szPublicKey[i],
_PatchOffset[i + 1],
pbImage[_PatchOffset[i + 1]],
pbImage[_PatchOffset[i + 1] + 1],
pbImage[_PatchOffset[i + 1] + 2],
pbImage[_PatchOffset[i + 1]],
pbImage[_PatchOffset[i + 1] + 1],
szPublicKey[i + 1]
);
pbImage[_PatchOffset[i] + 2] = szPublicKey[i];
pbImage[_PatchOffset[i + 1] + 2] = szPublicKey[i + 1];
}
}
}
+517
View File
@@ -0,0 +1,517 @@
#include "PatchSolutions.hpp"
#include <vector>
#include <algorithm>
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution2-i386.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
/*
Keyword[0x188][5] is generated by the following python script:
-----Begin Python3 Script-----
meta = \
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I" \
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv" \
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF" \
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2" \
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt" \
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ" \
"awIDAQAB"
print('const uint8_t PatchSolution2::Keywords[0x188][5] = {')
for i in range(0, len(meta)):
if i % 3 == 0:
i1 = '0x83, 0xf2, 0x%.2x' % ord(meta[i]) # asm('xor edx, meta[i]')
i2 = '0x88, 0x15' # asm_prefix('mov byte ptr ds:xxxxxxxx, dl')
elif i % 3 == 1:
i1 = '0x83, 0xf0, 0x%.2x' % ord(meta[i]) # asm('xor eax, meta[i]')
i2 = '0xa2' # asm_prefix('mov byte ptr ds:xxxxxxxx, al')
else:
i1 = '0x83, 0xf1, 0x%.2x' % ord(meta[i]) # asm('xor ecx, meta[i]')
i2 = '0x88, 0x0d' # asm_prefix('mov byte ptr ds:xxxxxxxx, cl')
print(' { %s, %s }' % (i1, i2), end=',\n' if i != len(meta) - 1 else '\n')
print('};')
-----End Python3 Script-----
*/
const uint8_t PatchSolution2::Keyword[0x188][5] = {
{ 0x83, 0xf2, 0x4d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x42, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4e, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x67, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x71, 0x88, 0x0d },
{ 0x83, 0xf2, 0x68, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x39, 0xa2 },
{ 0x83, 0xf1, 0x77, 0x88, 0x0d },
{ 0x83, 0xf2, 0x30, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 },
{ 0x83, 0xf1, 0x41, 0x88, 0x0d },
{ 0x83, 0xf2, 0x51, 0x88, 0x15 },
{ 0x83, 0xf0, 0x45, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x4f, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x38, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x67, 0xa2 },
{ 0x83, 0xf1, 0x4b, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x45, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x77, 0x88, 0x0d },
{ 0x83, 0xf2, 0x31, 0x88, 0x15 },
{ 0x83, 0xf0, 0x64, 0xa2 },
{ 0x83, 0xf1, 0x71, 0x88, 0x0d },
{ 0x83, 0xf2, 0x46, 0x88, 0x15 },
{ 0x83, 0xf0, 0x33, 0xa2 },
{ 0x83, 0xf1, 0x53, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6b, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x61, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x6d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x7a, 0xa2 },
{ 0x83, 0xf1, 0x73, 0x88, 0x0d },
{ 0x83, 0xf2, 0x38, 0x88, 0x15 },
{ 0x83, 0xf0, 0x38, 0xa2 },
{ 0x83, 0xf1, 0x39, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x71, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x39, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x64, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x64, 0x88, 0x15 },
{ 0x83, 0xf0, 0x68, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x47, 0xa2 },
{ 0x83, 0xf1, 0x39, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x50, 0xa2 },
{ 0x83, 0xf1, 0x63, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4c, 0xa2 },
{ 0x83, 0xf1, 0x6e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4a, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x70, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x46, 0x88, 0x15 },
{ 0x83, 0xf0, 0x34, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x39, 0x88, 0x15 },
{ 0x83, 0xf0, 0x56, 0xa2 },
{ 0x83, 0xf1, 0x48, 0x88, 0x0d },
{ 0x83, 0xf2, 0x53, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4d, 0xa2 },
{ 0x83, 0xf1, 0x47, 0x88, 0x0d },
{ 0x83, 0xf2, 0x65, 0x88, 0x15 },
{ 0x83, 0xf0, 0x38, 0xa2 },
{ 0x83, 0xf1, 0x6f, 0x88, 0x0d },
{ 0x83, 0xf2, 0x50, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x79, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x4a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x44, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x34, 0x88, 0x0d },
{ 0x83, 0xf2, 0x42, 0x88, 0x15 },
{ 0x83, 0xf0, 0x63, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x67, 0xa2 },
{ 0x83, 0xf1, 0x76, 0x88, 0x0d },
{ 0x83, 0xf2, 0x73, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x66, 0x88, 0x15 },
{ 0x83, 0xf0, 0x67, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x76, 0xa2 },
{ 0x83, 0xf1, 0x61, 0x88, 0x0d },
{ 0x83, 0xf2, 0x35, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x35, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x35, 0x88, 0x15 },
{ 0x83, 0xf0, 0x32, 0xa2 },
{ 0x83, 0xf1, 0x55, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6f, 0xa2 },
{ 0x83, 0xf1, 0x44, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x55, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6b, 0xa2 },
{ 0x83, 0xf1, 0x54, 0x88, 0x0d },
{ 0x83, 0xf2, 0x58, 0x88, 0x15 },
{ 0x83, 0xf0, 0x47, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x68, 0x88, 0x15 },
{ 0x83, 0xf0, 0x70, 0xa2 },
{ 0x83, 0xf1, 0x41, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4d, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x34, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x42, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 },
{ 0x83, 0xf1, 0x70, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x33, 0xa2 },
{ 0x83, 0xf1, 0x45, 0x88, 0x0d },
{ 0x83, 0xf2, 0x65, 0x88, 0x15 },
{ 0x83, 0xf0, 0x64, 0xa2 },
{ 0x83, 0xf1, 0x47, 0x88, 0x0d },
{ 0x83, 0xf2, 0x36, 0x88, 0x15 },
{ 0x83, 0xf0, 0x32, 0xa2 },
{ 0x83, 0xf1, 0x72, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x71, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 },
{ 0x83, 0xf1, 0x67, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x53, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x79, 0xa2 },
{ 0x83, 0xf1, 0x78, 0x88, 0x0d },
{ 0x83, 0xf2, 0x43, 0x88, 0x15 },
{ 0x83, 0xf0, 0x53, 0xa2 },
{ 0x83, 0xf1, 0x50, 0x88, 0x0d },
{ 0x83, 0xf2, 0x42, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x4a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4f, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x52, 0x88, 0x15 },
{ 0x83, 0xf0, 0x30, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x67, 0x88, 0x15 },
{ 0x83, 0xf0, 0x5a, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x62, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x6e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x55, 0x88, 0x15 },
{ 0x83, 0xf0, 0x30, 0xa2 },
{ 0x83, 0xf1, 0x66, 0x88, 0x0d },
{ 0x83, 0xf2, 0x72, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6a, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x34, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x56, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x67, 0x88, 0x0d },
{ 0x83, 0xf2, 0x59, 0x88, 0x15 },
{ 0x83, 0xf0, 0x69, 0xa2 },
{ 0x83, 0xf1, 0x4c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x75, 0x88, 0x15 },
{ 0x83, 0xf0, 0x5a, 0xa2 },
{ 0x83, 0xf1, 0x53, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x62, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x38, 0x88, 0x0d },
{ 0x83, 0xf2, 0x5a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x78, 0xa2 },
{ 0x83, 0xf1, 0x69, 0x88, 0x0d },
{ 0x83, 0xf2, 0x48, 0x88, 0x15 },
{ 0x83, 0xf0, 0x50, 0xa2 },
{ 0x83, 0xf1, 0x64, 0x88, 0x0d },
{ 0x83, 0xf2, 0x70, 0x88, 0x15 },
{ 0x83, 0xf0, 0x31, 0xa2 },
{ 0x83, 0xf1, 0x6f, 0x88, 0x0d },
{ 0x83, 0xf2, 0x44, 0x88, 0x15 },
{ 0x83, 0xf0, 0x34, 0xa2 },
{ 0x83, 0xf1, 0x74, 0x88, 0x0d },
{ 0x83, 0xf2, 0x55, 0x88, 0x15 },
{ 0x83, 0xf0, 0x70, 0xa2 },
{ 0x83, 0xf1, 0x76, 0x88, 0x0d },
{ 0x83, 0xf2, 0x73, 0x88, 0x15 },
{ 0x83, 0xf0, 0x46, 0xa2 },
{ 0x83, 0xf1, 0x63, 0x88, 0x0d },
{ 0x83, 0xf2, 0x69, 0x88, 0x15 },
{ 0x83, 0xf0, 0x34, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x59, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6a, 0xa2 },
{ 0x83, 0xf1, 0x4e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x47, 0xa2 },
{ 0x83, 0xf1, 0x55, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x57, 0xa2 },
{ 0x83, 0xf1, 0x50, 0x88, 0x0d },
{ 0x83, 0xf2, 0x48, 0x88, 0x15 },
{ 0x83, 0xf0, 0x36, 0xa2 },
{ 0x83, 0xf1, 0x72, 0x88, 0x0d },
{ 0x83, 0xf2, 0x76, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x68, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6c, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x49, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x4b, 0x88, 0x0d },
{ 0x83, 0xf2, 0x72, 0x88, 0x15 },
{ 0x83, 0xf0, 0x78, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x74, 0x88, 0x15 },
{ 0x83, 0xf0, 0x71, 0xa2 },
{ 0x83, 0xf1, 0x4c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x69, 0x88, 0x15 },
{ 0x83, 0xf0, 0x65, 0xa2 },
{ 0x83, 0xf1, 0x6c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x73, 0x88, 0x15 },
{ 0x83, 0xf0, 0x76, 0xa2 },
{ 0x83, 0xf1, 0x61, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x55, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x72, 0xa2 },
{ 0x83, 0xf1, 0x67, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x36, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x79, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x59, 0xa2 },
{ 0x83, 0xf1, 0x4d, 0x88, 0x0d },
{ 0x83, 0xf2, 0x76, 0x88, 0x15 },
{ 0x83, 0xf0, 0x5a, 0xa2 },
{ 0x83, 0xf1, 0x4e, 0x88, 0x0d },
{ 0x83, 0xf2, 0x45, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x33, 0x88, 0x0d },
{ 0x83, 0xf2, 0x68, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x46, 0x88, 0x0d },
{ 0x83, 0xf2, 0x45, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x4c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x31, 0x88, 0x15 },
{ 0x83, 0xf0, 0x65, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x62, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x79, 0x88, 0x0d },
{ 0x83, 0xf2, 0x54, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x44, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x59, 0x88, 0x0d },
{ 0x83, 0xf2, 0x79, 0x88, 0x15 },
{ 0x83, 0xf0, 0x51, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x34, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x32, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6c, 0xa2 },
{ 0x83, 0xf1, 0x78, 0x88, 0x0d },
{ 0x83, 0xf2, 0x66, 0x88, 0x15 },
{ 0x83, 0xf0, 0x30, 0xa2 },
{ 0x83, 0xf1, 0x77, 0x88, 0x0d },
{ 0x83, 0xf2, 0x56, 0x88, 0x15 },
{ 0x83, 0xf0, 0x49, 0xa2 },
{ 0x83, 0xf1, 0x52, 0x88, 0x0d },
{ 0x83, 0xf2, 0x35, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6d, 0xa2 },
{ 0x83, 0xf1, 0x63, 0x88, 0x0d },
{ 0x83, 0xf2, 0x47, 0x88, 0x15 },
{ 0x83, 0xf0, 0x4e, 0xa2 },
{ 0x83, 0xf1, 0x37, 0x88, 0x0d },
{ 0x83, 0xf2, 0x58, 0x88, 0x15 },
{ 0x83, 0xf0, 0x43, 0xa2 },
{ 0x83, 0xf1, 0x58, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4a, 0x88, 0x15 },
{ 0x83, 0xf0, 0x52, 0xa2 },
{ 0x83, 0xf1, 0x48, 0x88, 0x0d },
{ 0x83, 0xf2, 0x4f, 0x88, 0x15 },
{ 0x83, 0xf0, 0x46, 0xa2 },
{ 0x83, 0xf1, 0x48, 0x88, 0x0d },
{ 0x83, 0xf2, 0x53, 0x88, 0x15 },
{ 0x83, 0xf0, 0x66, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x67, 0x88, 0x15 },
{ 0x83, 0xf0, 0x7a, 0xa2 },
{ 0x83, 0xf1, 0x58, 0x88, 0x0d },
{ 0x83, 0xf2, 0x57, 0x88, 0x15 },
{ 0x83, 0xf0, 0x61, 0xa2 },
{ 0x83, 0xf1, 0x62, 0x88, 0x0d },
{ 0x83, 0xf2, 0x52, 0x88, 0x15 },
{ 0x83, 0xf0, 0x53, 0xa2 },
{ 0x83, 0xf1, 0x76, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6d, 0x88, 0x15 },
{ 0x83, 0xf0, 0x74, 0xa2 },
{ 0x83, 0xf1, 0x31, 0x88, 0x0d },
{ 0x83, 0xf2, 0x6e, 0x88, 0x15 },
{ 0x83, 0xf0, 0x72, 0xa2 },
{ 0x83, 0xf1, 0x6c, 0x88, 0x0d },
{ 0x83, 0xf2, 0x37, 0x88, 0x15 },
{ 0x83, 0xf0, 0x73, 0xa2 },
{ 0x83, 0xf1, 0x57, 0x88, 0x0d },
{ 0x83, 0xf2, 0x36, 0x88, 0x15 },
{ 0x83, 0xf0, 0x63, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x78, 0x88, 0x15 },
{ 0x83, 0xf0, 0x6c, 0xa2 },
{ 0x83, 0xf1, 0x6a, 0x88, 0x0d },
{ 0x83, 0xf2, 0x75, 0x88, 0x15 },
{ 0x83, 0xf0, 0x75, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x61, 0x88, 0x15 },
{ 0x83, 0xf0, 0x77, 0xa2 },
{ 0x83, 0xf1, 0x49, 0x88, 0x0d },
{ 0x83, 0xf2, 0x44, 0x88, 0x15 },
{ 0x83, 0xf0, 0x41, 0xa2 },
{ 0x83, 0xf1, 0x51, 0x88, 0x0d },
{ 0x83, 0xf2, 0x41, 0x88, 0x15 },
{ 0x83, 0xf0, 0x42, 0xa2 }
};
[[nodiscard]]
bool PatchSolution2::FindPatchOffset() noexcept {
try {
auto SectionHeader_text = _Image.ImageSectionHeader(".text");
auto SectionView_text = _Image.ImageSectionView<const uint8_t*>(SectionHeader_text);
const uint8_t* lpPatch[_countof(_PatchOffset)] = {};
std::vector<size_t> Hints;
DWORD PossibleRangeStart = 0xffffffff;
DWORD PossibleRangeEnd;
for (DWORD i = 0; i < SectionHeader_text->SizeOfRawData; ++i) {
if (memcmp(SectionView_text + i, Keyword[0], sizeof(Keyword[0])) == 0) {
Hints.emplace_back(
*reinterpret_cast<const uint32_t*>(SectionView_text + i + sizeof(Keyword[0]))
);
if (i < PossibleRangeStart) {
PossibleRangeStart = i;
}
}
}
PossibleRangeStart -= 0x1000;
PossibleRangeEnd = PossibleRangeStart + 0x100000;
// Keywords[0] should occur 3 times.
if (Hints.size() != 3) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.size() != 3"));
}
std::sort(Hints.begin(), Hints.end());
if (Hints.back() - Hints.front() != 0x127382BE - 0x12738210) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Hints.back() - Hints.front() != 0x127382BE - 0x12738210"));
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
uint8_t CurrentKeyword[9];
size_t CurrentKeywordSize = i % 3 == 1 ? 4 : 5;
memcpy(CurrentKeyword, Keyword[i], CurrentKeywordSize);
*reinterpret_cast<uint32_t*>(CurrentKeyword + CurrentKeywordSize) = Hints[0] + i;
CurrentKeywordSize += sizeof(uint32_t);
for (DWORD j = PossibleRangeStart; j < PossibleRangeEnd; ++j) {
if (memcmp(SectionView_text + j, CurrentKeyword, CurrentKeywordSize) == 0) {
lpPatch[i] = SectionView_text + j;
break;
}
}
// if not found, refuse to patch
if (lpPatch[i] == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("A patch point is missing."));
}
}
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = _Image.PointerToFileOffset(lpPatch[i]);
}
LOG_SUCCESS(0, "PatchSolution2 ...... Ready to apply");
for (size_t i = 0; i < _countof(_PatchOffset); i += 4) {
static_assert(sizeof(_countof(_PatchOffset)) % 4 == 0);
LOG_HINT(4, "Patch offset[%zu ... %zu] = 0x%.8zx, 0x%.8zx, 0x%.8zx, 0x%.8zx", i, i + 3, _PatchOffset[i], _PatchOffset[i + 1], _PatchOffset[i + 2], _PatchOffset[i + 3]);
}
return true;
} catch (nkg::Exception&) {
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
LOG_FAILURE(0, "PatchSolution2 ...... Omitted");
return false;
}
}
}
+231
View File
@@ -0,0 +1,231 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution3-amd64.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
PatchSolution3::PatchSolution3(const ImageInterpreter& Image) :
_Image(Image),
_Engine(CS_ARCH_X86, CS_MODE_64),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
PatchSolution3::PatchSolution3(const ImageInterpreter* lpImage) :
_Image(*lpImage),
_Engine(CS_ARCH_X86, CS_MODE_64),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
[[nodiscard]]
bool PatchSolution3::CheckIfMatchPattern(const cs_insn* lpInsn) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for IMM_DATA
// 2. lea REG, PTR [MEM] (MEM must point to a non-empty printable string) // for STRING_DATA
if (_stricmp(lpInsn->mnemonic, "mov") == 0) {
if (lpInsn->detail->x86.operands[1].type != X86_OP_IMM) {
return false;
}
auto pbImmValue = lpInsn->bytes + lpInsn->detail->x86.encoding.imm_offset;
auto cbImmValue = lpInsn->detail->x86.encoding.imm_size;
return IsPrintable(pbImmValue, cbImmValue);
} else if (_stricmp(lpInsn->mnemonic, "lea") == 0) {
// as far as I know, all strings are loaded by "lea REG, QWORD PTR [RIP + disp]"
// so operands[1] must look like "[RIP + disp]"
if (lpInsn->detail->x86.operands[1].mem.base != X86_REG_RIP) {
return false;
}
// scale must 1, otherwise pattern mismatches
if (lpInsn->detail->x86.operands[1].mem.scale != 1) {
return false;
}
auto StringRva = static_cast<uintptr_t>(
lpInsn->address + lpInsn->size + // Next RIP
lpInsn->detail->x86.operands[1].mem.disp
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
auto StringLength = strlen(StringPtr);
// StringPtr must have at least one char
// every char in StringPtr must be printable, otherwise pattern mismatches
return StringLength && IsPrintable(StringPtr, StringLength);
} catch (nkg::Exception&) {
// If not found, pattern mismatches
return false;
}
} else {
return false;
}
}
[[nodiscard]]
bool PatchSolution3::CheckIfFound(const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for IMM_DATA
// 2. lea REG, PTR [MEM] (MEM must point to a non-empty printable string) // for STRING_DATA
auto& op_count = lpInsn->detail->x86.op_count;
auto& operands = lpInsn->detail->x86.operands;
if (op_count != 2) {
return false;
}
if (Keyword[KeywordIdx].Type == IMM_DATA && operands[1].type == X86_OP_IMM) {
static_assert(sizeof(operands[1].imm) == sizeof(Keyword[KeywordIdx].Value));
return
operands[1].imm == *reinterpret_cast<const int64_t*>(Keyword[KeywordIdx].Value) &&
lpInsn->detail->x86.encoding.imm_size == Keyword[KeywordIdx].Size;
} else if (Keyword[KeywordIdx].Type == STRING_DATA && operands[1].type == X86_OP_MEM) {
auto StringRva = static_cast<uintptr_t>(
lpInsn->address + lpInsn->size + // Next RIP
operands[1].mem.disp
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
return
strncmp(StringPtr, reinterpret_cast<const char*>(Keyword[KeywordIdx].Value), Keyword[KeywordIdx].Size) == 0 &&
StringPtr[Keyword[KeywordIdx].Size] == '\x00';
} catch (nkg::Exception&) {
return false;
}
} else {
return false;
}
}
[[nodiscard]]
PatchSolution3::PatchInfo PatchSolution3::CreatePatchPoint(const void* lpOpcode, const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
PatchInfo NewPatch;
NewPatch.OpcodeRva = lpInsn->address;
NewPatch.lpOpcode = const_cast<void*>(lpOpcode);
if (lpInsn->detail->x86.operands[1].type == X86_OP_MEM) {
auto StringRva = static_cast<uintptr_t>(
lpInsn->address + lpInsn->size + // Next RIP
lpInsn->detail->x86.operands[1].mem.disp
);
NewPatch.lpOriginalString = _Image.RvaToPointer<char*>(StringRva);
if (Keyword[KeywordIdx].NotRecommendedToModify) {
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.disp_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.disp_size;
} else {
NewPatch.lpPatch = reinterpret_cast<uint8_t*>(NewPatch.lpOriginalString);
NewPatch.cbPatch = Keyword[KeywordIdx].Size;
}
} else { // X86_OP_IMM
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.imm_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.imm_size;
NewPatch.lpOriginalString = nullptr;
}
NewPatch.lpReplaceString = nullptr;
return NewPatch;
}
[[nodiscard]]
bool PatchSolution3::FindPatchOffset() noexcept {
try {
static const uint8_t HeaderOfTargetFunction[] = {
0x40, 0x55, // push rbp
0x48, 0x8D, 0xAC, 0x24, 0x70, 0xBC, 0xFF, 0xFF, // lea rbp, [rsp-4390h]
0xB8, 0x90, 0x44, 0x00, 0x00 // mov eax, 4490h
};
PatchInfo Patch[_countof(_Patch)] = {};
const uint8_t* lpTargetFunction = nullptr;
auto lptargetFunctionHint = _Image.SearchSection<const uint8_t*>(".text", [&lpTargetFunction](const uint8_t* p) {
__try {
if (*reinterpret_cast<const uint32_t*>(p) == 0x6b67424e) {
auto i = p - 0x250;
for (; i < p; ++i) {
if (memcmp(i, HeaderOfTargetFunction, sizeof(HeaderOfTargetFunction)) == 0) {
lpTargetFunction = i;
return true;
}
}
}
return false;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
size_t KeywordIndex = 0;
CapstoneDisassembler Disassembler = _Engine.CreateDisassembler();
Disassembler.SetContext(CapstoneContext{ lpTargetFunction, 0xcd03, _Image.PointerToRva(lpTargetFunction) });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIndex));
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Reach end of function."));
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
if (CheckIfFound(lpInsn, KeywordIndex) == false) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Missing a patch."));
}
Patch[KeywordIndex] = CreatePatchPoint(Disassembler.GetInstructionContext().lpMachineCode, lpInsn, KeywordIndex);
++KeywordIndex;
}
if (KeywordIndex == _countof(Patch)) {
break;
}
}
if (KeywordIndex != _countof(Patch)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Some patches are not found."));
}
LOG_SUCCESS(0, "PatchSolution3 ...... Ready to apply");
for (size_t i = 0; i < _countof(Patch); ++i) {
_Patch[i] = Patch[i];
LOG_HINT(4, "[%3zu] Instruction RVA = 0x%.8llx, Patch Offset = +0x%.8zx", i, _Patch[i].OpcodeRva, address_delta(_Patch[i].lpPatch, _Image.ImageBase()));
}
return true;
} catch (nkg::Exception&) {
memset(_Patch, 0, sizeof(_Patch));
LOG_FAILURE(0, "PatchSolution3 ...... Omitted");
return false;
}
}
}
+424
View File
@@ -0,0 +1,424 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution3-generic.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
const PatchSolution3::KeywordInfo PatchSolution3::Keyword[111] = {
{ { 0x4d, 0x49, 0x49 }, 3, STRING_DATA, false },
{ { 0x42, 0x49 }, 2, IMM_DATA, false },
{ { 0x6a }, 1, IMM_DATA, false },
{ { 0x41 }, 1, IMM_DATA, false },
{ { 0x4e, 0x42, 0x67, 0x6b }, 4, IMM_DATA, false },
{ { 0x71 }, 1, IMM_DATA, false },
{ { 0x68, 0x6b, 0x69, 0x47, 0x39, 0x77 }, 6, STRING_DATA, false },
{ { 0x30 }, 1, STRING_DATA, true },
{ { 0x42 }, 1, IMM_DATA, false },
{ { 0x41 }, 1, IMM_DATA, false },
{ { 0x51, 0x45, 0x46, 0x41, 0x41, 0x4f, 0x43 }, 7, STRING_DATA, false },
{ { 0x41, 0x51, 0x38, 0x41, 0x4d, 0x49 }, 6, STRING_DATA, false },
{ { 0x49, 0x42 }, 2, STRING_DATA, false },
{ { 0x43, 0x67, 0x4b, 0x43 }, 4, IMM_DATA, false },
{ { 0x41, 0x51 }, 2, STRING_DATA, false },
{ { 0x45, 0x41, 0x77, 0x31 }, 4, IMM_DATA, false },
{ { 0x64, 0x71, 0x46, 0x33 }, 4, IMM_DATA, false },
{ { 0x53 }, 1, STRING_DATA, true },
{ { 0x6b, 0x43, 0x61, 0x41, 0x41, 0x6d }, 6, STRING_DATA, false },
{ { 0x4d, 0x7a, 0x73, 0x38 }, 4, IMM_DATA, false },
{ { 0x38, 0x39, 0x49, 0x71 }, 4, IMM_DATA, false },
{ { 0x64 }, 1, IMM_DATA, false },
{ { 0x57 }, 1, IMM_DATA, false },
{ { 0x39, 0x4d, 0x32, 0x64 }, 4, IMM_DATA, false },
{ { 0x49, 0x64, 0x68 }, 3, STRING_DATA, false },
{ { 0x33, 0x6a }, 2, IMM_DATA, false },
{ { 0x47, 0x39, 0x79, 0x50 }, 4, IMM_DATA, false },
{ { 0x63, 0x6d }, 2, IMM_DATA, false },
{ { 0x4c }, 1, IMM_DATA, false },
{ { 0x6e, 0x6d, 0x4a }, 3, STRING_DATA, false },
{ { 0x69, 0x47, 0x70, 0x42, 0x46, 0x34, 0x45 }, 7, STRING_DATA, false },
{ { 0x39, 0x56, 0x48, 0x53, 0x4d, 0x47 }, 6, STRING_DATA, false },
{ { 0x65, 0x38, 0x6f, 0x50, 0x41, 0x79, 0x32, 0x6b }, 8, STRING_DATA, false },
{ { 0x4a, 0x44 }, 2, STRING_DATA, false },
{ { 0x6d, 0x64 }, 2, IMM_DATA, false },
{ { 0x4e, 0x74, 0x34 }, 3, STRING_DATA, false },
{ { 0x42, 0x63, 0x45, 0x79, 0x67, 0x76 }, 6, STRING_DATA, false },
{ { 0x73, 0x73, 0x45, 0x66, 0x67, 0x69 }, 6, STRING_DATA, false },
{ { 0x6e, 0x76, 0x61, 0x35, 0x74 }, 5, STRING_DATA, false },
{ { 0x35, 0x6a, 0x6d, 0x33, 0x35, 0x32 }, 6, STRING_DATA, false },
{ { 0x55, 0x41 }, 2, IMM_DATA, false },
{ { 0x6f, 0x44, 0x6f, 0x73 }, 4, IMM_DATA, false },
{ { 0x55, 0x4a }, 2, IMM_DATA, false },
{ { 0x6b, 0x54, 0x58, 0x47, 0x51 }, 5, STRING_DATA, false },
{ { 0x68, 0x70, 0x41, 0x57, 0x4d, 0x46 }, 6, STRING_DATA, false },
{ { 0x34, 0x66, 0x42, 0x6d, 0x42 }, 5, STRING_DATA, false },
{ { 0x70, 0x4f, 0x33, 0x45 }, 4, IMM_DATA, false },
{ { 0x65, 0x64 }, 2, IMM_DATA, false },
{ { 0x47 }, 1, IMM_DATA, false },
{ { 0x36, 0x32, 0x72, 0x4f, 0x73, 0x71 }, 6, STRING_DATA, false },
{ { 0x4d }, 1, IMM_DATA, false },
{ { 0x42, 0x67, 0x6d, 0x53 }, 4, STRING_DATA, false },
{ { 0x64 }, 1, IMM_DATA, false },
{ { 0x41, 0x79, 0x78, 0x43, 0x53 }, 5, STRING_DATA, false },
{ { 0x50 }, 1, IMM_DATA, false },
{ { 0x42, 0x52, 0x4a, 0x49, 0x4f }, 5, STRING_DATA, false },
{ { 0x46, 0x52, 0x30, 0x51, 0x67, 0x5a, 0x46, 0x62 }, 8, STRING_DATA, false },
{ { 0x52 }, 1, IMM_DATA, false },
{ { 0x6e, 0x55, 0x30, 0x66 }, 4, STRING_DATA, false },
{ { 0x72, 0x6a, 0x33, 0x34 }, 4, IMM_DATA, false },
{ { 0x66 }, 1, STRING_DATA, true },
{ { 0x69, 0x56, 0x6d, 0x67 }, 4, IMM_DATA, false },
{ { 0x59, 0x69, 0x4c, 0x75 }, 4, STRING_DATA, false },
{ { 0x5a, 0x53, 0x41, 0x6d }, 4, IMM_DATA, false },
{ { 0x49, 0x62 }, 2, IMM_DATA, false },
{ { 0x73 }, 1, IMM_DATA, false },
{ { 0x38, 0x5a, 0x78, 0x69 }, 4, IMM_DATA, false },
{ { 0x48 }, 1, IMM_DATA, false },
{ { 0x50, 0x64, 0x70, 0x31 }, 4, IMM_DATA, false },
{ { 0x6f, 0x44 }, 2, IMM_DATA, false },
{ { 0x34 }, 1, IMM_DATA, false },
{ { 0x74, 0x55, 0x70, 0x76, 0x73, 0x46 }, 6, STRING_DATA, false },
{ { 0x63, 0x69, 0x34, 0x51, 0x4a, 0x74 }, 6, STRING_DATA, false },
{ { 0x59, 0x4e, 0x6a, 0x4e, 0x6e, 0x47, 0x55 }, 7, STRING_DATA, false },
{ { 0x32, 0x57, 0x50, 0x48 }, 4, STRING_DATA, false },
{ { 0x36, 0x72, 0x76, 0x43, 0x68, 0x47, 0x6c }, 7, STRING_DATA, false },
{ { 0x31, 0x49, 0x52, 0x4b, 0x72, 0x78, 0x4d, 0x74 }, 8, STRING_DATA, false },
{ { 0x71, 0x4c, 0x69, 0x65, 0x6c }, 5, STRING_DATA, false },
{ { 0x73, 0x76, 0x61, 0x6a, 0x55, 0x6a, 0x79, 0x72 }, 8, STRING_DATA, false },
{ { 0x67 }, 1, STRING_DATA, true },
{ { 0x4f, 0x43, 0x36, 0x4e, 0x6d, 0x79, 0x6d, 0x59 }, 8, STRING_DATA, false },
{ { 0x4d }, 1, IMM_DATA, false },
{ { 0x76, 0x5a, 0x4e }, 3, STRING_DATA, false },
{ { 0x45, 0x52, 0x33, 0x68, 0x74 }, 5, STRING_DATA, false },
{ { 0x46 }, 1, IMM_DATA, false },
{ { 0x45, 0x74, 0x4c, 0x31 }, 4, STRING_DATA, false },
{ { 0x65, 0x51, 0x62, 0x43, 0x79 }, 5, STRING_DATA, false },
{ { 0x54, 0x66, 0x44, 0x6d, 0x74, 0x59, 0x79, 0x51 }, 8, STRING_DATA, false },
{ { 0x31, 0x57, 0x74, 0x34 }, 4, STRING_DATA, false },
{ { 0x4f }, 1, IMM_DATA, false },
{ { 0x74, 0x31, 0x32, 0x6c, 0x78, 0x66 }, 6, STRING_DATA, false },
{ { 0x30 }, 1, IMM_DATA, false },
{ { 0x77, 0x56, 0x49, 0x52, 0x35 }, 5, STRING_DATA, false },
{ { 0x6d }, 1, IMM_DATA, false },
{ { 0x63, 0x47, 0x4e, 0x37 }, 4, STRING_DATA, false },
{ { 0x58, 0x43, 0x58, 0x4a }, 4, STRING_DATA, false },
{ { 0x52, 0x48, 0x4f, 0x46 }, 4, IMM_DATA, false },
{ { 0x48, 0x53 }, 2, IMM_DATA, false },
{ { 0x66 }, 1, IMM_DATA, false },
{ { 0x31, 0x67, 0x7a, 0x58, 0x57 }, 5, STRING_DATA, false },
{ { 0x61 }, 1, IMM_DATA, false },
{ { 0x62 }, 1, IMM_DATA, false },
{ { 0x52, 0x53 }, 2, STRING_DATA, false },
{ { 0x76, 0x6d, 0x74, 0x31, 0x6e }, 5, STRING_DATA, false },
{ { 0x72, 0x6c }, 2, STRING_DATA, true },
{ { 0x37, 0x73, 0x57 }, 3, STRING_DATA, false },
{ { 0x36, 0x63, 0x6a }, 3, STRING_DATA, false },
{ { 0x78, 0x6c, 0x6a, 0x75, 0x75, 0x51, 0x61 }, 7, STRING_DATA, false },
{ { 0x77, 0x49, 0x44, 0x41 }, 4, STRING_DATA, false },
{ { 0x51, 0x41 }, 2, IMM_DATA, false },
{ { 0x42 }, 1, IMM_DATA, false }
};
[[nodiscard]]
bool PatchSolution3::IsPrintable(const void* p, size_t s) noexcept {
auto pb = reinterpret_cast<const uint8_t*>(p);
for (size_t i = 0; i < s; ++i) {
if (isprint(pb[i]) == false) {
return false;
}
}
return true;
}
[[nodiscard]]
CapstoneContext PatchSolution3::GetJumpedBranch(const CapstoneContext& NotJumpedBranch, const cs_insn* lpJxxInsn) const {
CapstoneContext JumpedBranch;
JumpedBranch.lpMachineCode = _Image.RvaToPointer<const void*>(
static_cast<uintptr_t>(lpJxxInsn->detail->x86.operands[0].imm)
);
JumpedBranch.cbMachineCode = NotJumpedBranch.cbMachineCode - (
reinterpret_cast<const uint8_t*>(JumpedBranch.lpMachineCode) -
reinterpret_cast<const uint8_t*>(NotJumpedBranch.lpMachineCode)
);
JumpedBranch.Address = lpJxxInsn->detail->x86.operands[0].imm;
return JumpedBranch;
}
[[nodiscard]]
CapstoneContext PatchSolution3::SelectBranch(const CapstoneContext& NotJumpedBranch, const CapstoneContext& JumpedBranch, size_t KeywordIdx) const {
CapstoneContext A = NotJumpedBranch;
CapstoneContext B = JumpedBranch;
int WeightA = 0;
int WeightB = 0;
auto Disassembler = _Engine.CreateDisassembler();
while (true) {
int WeightAPrev = WeightA;
int WeightBPrev = WeightB;
//
// process NotJumpedBranch
//
Disassembler.SetContext(A);
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// For all x86 mnemonics, only 'jcc' or 'jmp' starts with 'j' or 'J'.
// So it should be a new branch if we meet them.
//
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
try {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIdx));
} catch (nkg::Exception&) {
// If exception occurs, give up NotJumpedBranch
break;
}
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
return JumpedBranch;
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
//
// if match pattern, but keyword doesn't match,
// NotJumpedBranch must not be what we want
//
if (CheckIfFound(lpInsn, KeywordIdx) == false) {
return JumpedBranch;
}
//
// If keyword is succeeded to match
// Add WeightA and stop processing NotJumpedBranch
//
++WeightA;
break;
}
}
A = Disassembler.GetContext();
//
// process JumpedBranch
//
Disassembler.SetContext(B);
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
//
// For all x86 mnemonics, only 'jcc' or 'jmp' starts with 'j' or 'J'.
// So it should be a new branch if we meet them.
//
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
try {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIdx));
} catch (nkg::Exception&) {
// If exception occurs, give up JumpedBranch
break;
}
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
return NotJumpedBranch;
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
//
// if match pattern, but keyword doesn't match,
// JumpedBranch must not be what we want
//
if (CheckIfFound(lpInsn, KeywordIdx) == false) {
return NotJumpedBranch;
}
//
// If keyword is succeeded to match
// Add WeightB and stop processing JumpedBranch
//
++WeightB;
break;
}
}
B = Disassembler.GetContext();
//
// If this happens, it means neither of two branch is our target
if (WeightAPrev == WeightA && WeightBPrev == WeightB) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Branch is not selected."));
}
if (WeightA != WeightB)
return WeightA > WeightB ? NotJumpedBranch : JumpedBranch;
else
++KeywordIdx;
}
}
[[nodiscard]]
bool PatchSolution3::CheckKey(const RSACipher& Cipher) const noexcept {
//
// Brute-force search, cchString should be 1 or 2
//
auto SearchString = [](const void* lpRange, size_t cbRange, const char* lpString, size_t cchString) -> const char* {
const char* p = reinterpret_cast<const char*>(lpRange);
for (size_t i = 0; i < cbRange; ++i) {
if (p[i] == lpString[0]) {
bool match = true;
__try {
for (size_t j = 1; j < cchString; ++j) {
if (p[i + j] != lpString[j]) {
match = false;
break;
}
}
} __except (EXCEPTION_EXECUTE_HANDLER) {
match = false;
}
if (match && p[i + cchString] == '\x00')
return address_offset_cast<const char*>(lpRange, i);
}
}
return nullptr;
};
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
if (szPublicKey.length() != 0x188) {
return false;
}
size_t PublicKeyReadCursor = 0;
auto SectionHeader_rdata = _Image.ImageSectionHeader(".rdata");
auto SectionView_rdata = _Image.ImageSectionView(SectionHeader_rdata);
for (size_t i = 0; i < _countof(_Patch); PublicKeyReadCursor += Keyword[i].Size, ++i) {
if (Keyword[i].NotRecommendedToModify) {
_Patch[i].lpReplaceString = nullptr;
const char* lpReplaceString = nullptr;
const void* lpSearchRange = _Patch[i].lpOriginalString;
size_t cbSearchRange = SectionHeader_rdata->SizeOfRawData - address_delta(_Patch[i].lpOriginalString, SectionView_rdata);
for (size_t offset = 0;;) {
lpReplaceString = SearchString(
address_offset(lpSearchRange, offset),
cbSearchRange - offset,
szPublicKey.c_str() + PublicKeyReadCursor,
Keyword[i].Size
);
if (lpReplaceString == nullptr) {
return false;
}
if (_Image.IsRvaRangeInRelocTable(_Image.PointerToRva(lpReplaceString), Keyword[i].Size + 1)) {
//
// Damn it!
// ReplaceString will be modified during relocation
// We have to find another one
//
++offset;
} else {
//
// ReplaceString won't be modified during relocation
// which can be used to act as a part of public key string
//
break;
}
}
_Patch[i].lpReplaceString = const_cast<char*>(lpReplaceString);
}
}
return true;
}
void PatchSolution3::MakePatch(const RSACipher& Cipher) const {
for (size_t i = 0; i < _countof(_Patch); ++i) {
if (_Patch[i].lpPatch == nullptr) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("PatchSolution3 has not been ready yet."));
}
}
auto szPublicKey = Cipher.ExportKeyString<RSAKeyType::PublicKey, RSAKeyFormat::PEM>();
for (auto pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----BEGIN PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----BEGIN PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("-----END PUBLIC KEY-----"); pos != std::string::npos; pos = szPublicKey.find("-----END PUBLIC KEY-----", pos)) {
szPublicKey.erase(pos, literal_length("-----END PUBLIC KEY-----"));
}
for (auto pos = szPublicKey.find("\n"); pos != std::string::npos; pos = szPublicKey.find("\n", pos)) {
szPublicKey.erase(pos, literal_length("\n"));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PatchSolution3 *"));
_putts(TEXT("*******************************************************"));
size_t readptr = 0;
for (size_t i = 0; i < _countof(_Patch); readptr += Keyword[i].Size, ++i) {
_tprintf_s(TEXT("[*] +%.8zx: "), address_delta(_Patch[i].lpPatch, _Image.ImageBase()));
PrintBytes(_Patch[i].lpPatch, _Patch[i].cbPatch);
_tprintf_s(TEXT(" ---> "));
if (Keyword[i].NotRecommendedToModify) {
auto offset = _Patch[i].lpReplaceString - _Patch[i].lpOriginalString;
uint64_t disp = 0;
memcpy(&disp, _Patch[i].lpPatch, _Patch[i].cbPatch);
disp += offset;
memcpy(_Patch[i].lpPatch, &disp, _Patch[i].cbPatch);
} else {
memcpy(_Patch[i].lpPatch, szPublicKey.c_str() + readptr, Keyword[i].Size);
}
PrintBytes(_Patch[i].lpPatch, _Patch[i].cbPatch);
_tprintf_s(TEXT("\n"));
}
_putts(TEXT(""));
return;
}
}
+247
View File
@@ -0,0 +1,247 @@
#include "PatchSolutions.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\PatchSolution3-i386.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
PatchSolution3::PatchSolution3(const ImageInterpreter& Image) :
_Image(Image),
_Engine(CS_ARCH_X86, CS_MODE_32),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
PatchSolution3::PatchSolution3(const ImageInterpreter* lpImage) :
_Image(*lpImage),
_Engine(CS_ARCH_X86, CS_MODE_32),
_Patch{}
{
_Engine.Option(CS_OPT_DETAIL, CS_OPT_ON);
}
[[nodiscard]]
bool PatchSolution3::CheckIfMatchPattern(const cs_insn* lpInsn) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// except pattern "mov [ebp - 0x4], IMM"
// 2. push IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// 3. push offset MEM (MEM must point to a non-empty printable string) // for KeywordType::STRING_DATA
//
if (_stricmp(lpInsn->mnemonic, "mov") == 0) {
// filter the case "mov [ebp - 0x4], IMM"
// because IMM may consist of printable chars in that case, which will mislead us.
//
// Here I use "> -0x30" to intensify condition, instead of "== -0x4"
if (lpInsn->detail->x86.operands[0].type == X86_OP_MEM &&
lpInsn->detail->x86.operands[0].mem.base == X86_REG_EBP &&
lpInsn->detail->x86.operands[0].mem.disp > -0x30)
{
return false;
}
if (lpInsn->detail->x86.operands[1].type != X86_OP_IMM) {
return false;
}
auto pbImmValue = lpInsn->bytes + lpInsn->detail->x86.encoding.imm_offset;
auto cbImmValue = lpInsn->detail->x86.encoding.imm_size;
// each bytes of imm must be printable;
return IsPrintable(pbImmValue, cbImmValue);
} else if (_stricmp(lpInsn->mnemonic, "push") == 0) {
if (lpInsn->detail->x86.operands[0].type != X86_OP_IMM) {
return false;
}
// test if match pattern 2
auto pbImmValue = lpInsn->bytes + lpInsn->detail->x86.encoding.imm_offset;
auto cbImmValue = lpInsn->detail->x86.encoding.imm_size;
if (IsPrintable(pbImmValue, cbImmValue)) {
return true;
}
// test if match pattern 3
auto StringRva = static_cast<uintptr_t>(
lpInsn->detail->x86.operands[0].imm - _Image.ImageNtHeaders()->OptionalHeader.ImageBase
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
auto StringLength = strlen(StringPtr);
// StringPtr must have at least one char
// every char in StringPtr must be printable, otherwise pattern mismatches
return StringLength && IsPrintable(StringPtr, StringLength);
} catch (nkg::Exception&) {
// If not found, pattern mismatches
return false;
}
} else {
return false;
}
}
[[nodiscard]]
bool PatchSolution3::CheckIfFound(const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
// the instruction we're interested in has one of the following patterns:
// 1. mov PTR [MEM], IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// except pattern "mov [ebp - 0x4], IMM"
// 2. push IMM (IMM must consist of printable chars) // for KeywordType::IMM_DATA
// 3. push offset MEM (MEM must point to a non-empty printable string) // for KeywordType::STRING_DATA
//
auto& op_count = lpInsn->detail->x86.op_count;
auto& operands = lpInsn->detail->x86.operands;
if (op_count < 1 || operands[op_count - 1].type != X86_OP_IMM) {
return false;
}
if (Keyword[KeywordIdx].Type == IMM_DATA) {
static_assert(sizeof(operands[op_count - 1].imm) == sizeof(Keyword[KeywordIdx].Value));
return
operands[op_count - 1].imm == *reinterpret_cast<const int64_t*>(Keyword[KeywordIdx].Value) &&
lpInsn->detail->x86.encoding.imm_size == Keyword[KeywordIdx].Size;
} else if (Keyword[KeywordIdx].Type == STRING_DATA) {
auto StringRva = static_cast<uintptr_t>(
operands[op_count - 1].imm - _Image.ImageNtHeaders()->OptionalHeader.ImageBase
);
try {
auto StringPtr = _Image.RvaToPointer<const char*>(StringRva);
return
strncmp(StringPtr, reinterpret_cast<const char*>(Keyword[KeywordIdx].Value), Keyword[KeywordIdx].Size) == 0 &&
StringPtr[Keyword[KeywordIdx].Size] == '\x00';
} catch (nkg::Exception&) {
return false;
}
} else {
return false;
}
}
[[nodiscard]]
PatchSolution3::PatchInfo PatchSolution3::CreatePatchPoint(const void* lpOpcode, const cs_insn* lpInsn, size_t KeywordIdx) const noexcept {
PatchInfo NewPatch;
NewPatch.OpcodeRva = lpInsn->address;
NewPatch.lpOpcode = const_cast<void*>(lpOpcode);
if (Keyword[KeywordIdx].Type == IMM_DATA) {
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.imm_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.imm_size;
NewPatch.lpOriginalString = nullptr;
} else {
auto StringRva = static_cast<uintptr_t>(
lpInsn->detail->x86.operands[0].imm - _Image.ImageNtHeaders()->OptionalHeader.ImageBase
);
NewPatch.lpOriginalString = _Image.RvaToPointer<char*>(StringRva);
if (Keyword[KeywordIdx].NotRecommendedToModify) {
NewPatch.lpPatch = address_offset(NewPatch.lpOpcode, lpInsn->detail->x86.encoding.imm_offset);
NewPatch.cbPatch = lpInsn->detail->x86.encoding.imm_size;
} else {
NewPatch.lpPatch = reinterpret_cast<uint8_t*>(NewPatch.lpOriginalString);
NewPatch.cbPatch = Keyword[KeywordIdx].Size;
}
}
NewPatch.lpReplaceString = nullptr;
return NewPatch;
}
[[nodiscard]]
bool PatchSolution3::FindPatchOffset() noexcept {
try {
static const uint8_t HeaderOfTargetFunction[] = {
0x55, // push ebp
0x8B, 0xEC, // mov ebp, esp
0x6A, 0xFF // push 0xffffffff
};
PatchInfo Patch[_countof(_Patch)] = {};
const uint8_t* lpTargetFunction = nullptr;
auto lptargetFunctionHint = _Image.SearchSection<const uint8_t*>(".text", [&lpTargetFunction](const uint8_t* p) {
__try {
if (*reinterpret_cast<const uint32_t*>(p) == 0x6b67424e) {
auto i = p - 0x1B0;
for (; i < p; ++i) {
if (memcmp(i, HeaderOfTargetFunction, sizeof(HeaderOfTargetFunction)) == 0) {
lpTargetFunction = i;
return true;
}
}
}
return false;
} __except (EXCEPTION_EXECUTE_HANDLER) {
return false;
}
});
size_t KeywordIndex = 0;
CapstoneDisassembler Disassembler = _Engine.CreateDisassembler();
Disassembler.SetContext(CapstoneContext{ lpTargetFunction, 0x9014, _Image.PointerToRva(lpTargetFunction) });
while (Disassembler.Next()) {
auto lpInsn = Disassembler.GetInstruction();
if (lpInsn->mnemonic[0] == 'j' || lpInsn->mnemonic[0] == 'J') {
auto JumpedBranch = GetJumpedBranch(Disassembler.GetContext(), lpInsn);
if (_stricmp(lpInsn->mnemonic, "jmp") == 0) {
Disassembler.SetContext(JumpedBranch);
} else {
Disassembler.SetContext(SelectBranch(Disassembler.GetContext(), JumpedBranch, KeywordIndex));
}
} else if (_stricmp(lpInsn->mnemonic, "ret") == 0) {
return false;
} else {
if (CheckIfMatchPattern(lpInsn) == false) {
continue;
}
if (CheckIfFound(lpInsn, KeywordIndex) == false) {
return false;
}
Patch[KeywordIndex] = CreatePatchPoint(Disassembler.GetInstructionContext().lpMachineCode, lpInsn, KeywordIndex);
++KeywordIndex;
}
if (KeywordIndex == _countof(Patch)) {
break;
}
}
if (KeywordIndex != _countof(Patch)) {
throw Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Some patches are not found."));
}
LOG_SUCCESS(0, "PatchSolution3 ...... Ready to apply");
for (size_t i = 0; i < _countof(Patch); ++i) {
_Patch[i] = Patch[i];
LOG_HINT(4, "[%3zu] Instruction RVA = 0x%.8llx, Patch Offset = +0x%.8zx", i, _Patch[i].OpcodeRva, address_delta(_Patch[i].lpPatch, _Image.ImageBase()));
}
return true;
} catch (nkg::Exception&) {
memset(_Patch, 0, sizeof(_Patch));
LOG_FAILURE(0, "PatchSolution3 ...... Omitted");
return false;
}
}
}
+201
View File
@@ -0,0 +1,201 @@
#pragma once
#include <RSACipher.hpp>
#include "ImageInterpreter.hpp"
#include "CapstoneDisassembler.hpp"
#include "Misc.hpp"
namespace nkg {
class PatchSolution {
protected:
static constexpr size_t InvalidOffset = -1;
public:
[[nodiscard]]
virtual bool FindPatchOffset() noexcept = 0;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept = 0;
virtual void MakePatch(const RSACipher& Cipher) const = 0;
virtual ~PatchSolution() = default;
};
//
// PatchSolution0 will replace the RSA public key stored in navicat.exe
//
class PatchSolution0 final : public PatchSolution {
private:
static const char Keyword[461];
const ImageInterpreter& _Image;
size_t _PatchOffset;
public:
PatchSolution0(const ImageInterpreter& Image) noexcept :
_Image(Image),
_PatchOffset(InvalidOffset) {}
PatchSolution0(const ImageInterpreter* lpImage) noexcept :
_Image(*lpImage),
_PatchOffset(InvalidOffset) {}
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution1 will replace the RSA public key stored in libcc.dll
//
class PatchSolution1 final : public PatchSolution {
private:
static const char Keyword0[160 + 1];
static const char Keyword1[4 + 1];
static const char Keyword2[742 + 1];
static const char Keyword3[4 + 1];
static const char Keyword4[5 + 1];
const ImageInterpreter& _Image;
size_t _PatchOffset[5];
size_t _PatchSize[5];
public:
PatchSolution1(const ImageInterpreter& Image) noexcept :
_Image(Image),
_PatchOffset{ InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset },
_PatchSize{} {}
PatchSolution1(const ImageInterpreter* lpImage) noexcept :
_Image(*lpImage),
_PatchOffset{ InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset , InvalidOffset },
_PatchSize{} {}
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution2 will replace the RSA public key stored in libcc.dll
//
class PatchSolution2 final : public PatchSolution {
private:
static const char KeywordMeta[0x188 + 1];
static const uint8_t Keyword[0x188][5];
const ImageInterpreter& _Image;
size_t _PatchOffset[0x188];
public:
PatchSolution2(const ImageInterpreter& Image) noexcept :
_Image(Image),
_PatchOffset{}
{
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
}
PatchSolution2(const ImageInterpreter* lpImage) noexcept :
_Image(*lpImage),
_PatchOffset{}
{
for (size_t i = 0; i < _countof(_PatchOffset); ++i) {
_PatchOffset[i] = InvalidOffset;
}
}
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
//
// PatchSolution3 will replace the RSA public key stored in libcc.dll
//
class PatchSolution3 final : public PatchSolution {
private:
using KeywordValueType = uint8_t[8];
using KeywordSizeType = size_t;
enum KeywordTypeEnum { IMM_DATA, STRING_DATA };
struct KeywordInfo {
KeywordValueType Value;
KeywordSizeType Size;
KeywordTypeEnum Type;
bool NotRecommendedToModify;
};
struct PatchInfo {
uint64_t OpcodeRva;
void* lpOpcode;
void* lpPatch;
size_t cbPatch;
char* lpOriginalString;
char* lpReplaceString;
};
static const KeywordInfo Keyword[111];
const ImageInterpreter& _Image;
CapstoneEngine _Engine;
mutable PatchInfo _Patch[111];
[[nodiscard]]
static bool IsPrintable(const void* p, size_t s) noexcept;
[[nodiscard]]
bool CheckIfMatchPattern(const cs_insn* lpInsn) const noexcept;
[[nodiscard]]
bool CheckIfFound(const cs_insn* lpInsn, size_t KeywordIdx) const noexcept;
[[nodiscard]]
PatchInfo CreatePatchPoint(const void* lpOpcode, const cs_insn* lpInsn, size_t KeywordIdx) const noexcept;
[[nodiscard]]
CapstoneContext GetJumpedBranch(const CapstoneContext& Bifurcation, const cs_insn* lpJxxInsn) const;
[[nodiscard]]
CapstoneContext SelectBranch(const CapstoneContext& NotJumpedBranch, const CapstoneContext& JumpedBranch, size_t KeywordIdx) const;
public:
PatchSolution3(const ImageInterpreter& Image);
PatchSolution3(const ImageInterpreter* lpImage);
[[nodiscard]]
virtual bool FindPatchOffset() noexcept override;
[[nodiscard]]
virtual bool CheckKey(const RSACipher& Cipher) const noexcept override;
virtual void MakePatch(const RSACipher& Cipher) const override;
};
}
-266
View File
@@ -1,266 +0,0 @@
#pragma once
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <string>
#ifdef _DEBUG
#pragma comment(lib, "libcryptoMTd.lib")
#else
#pragma comment(lib, "libcryptoMT.lib")
#endif
#pragma comment(lib, "WS2_32.lib") // some symbol are used in OpenSSL static lib
#pragma comment(lib, "Crypt32.lib") // some symbol are used in OpenSSL static lib
class RSACipher {
private:
RSA * _RsaObj;
RSACipher() : _RsaObj(nullptr) {}
RSACipher(RSA* lpRsa) : _RsaObj(lpRsa) {}
RSACipher(const RSACipher&) = delete;
RSACipher(RSACipher&&) = delete;
RSACipher& operator=(const RSACipher&) = delete;
RSACipher& operator=(RSACipher&&) = delete;
public:
enum class KeyType {
PrivateKey,
PublicKey
};
enum class KeyFormat {
NotSpecified,
PEM,
PKCS1
};
~RSACipher() {
if (_RsaObj)
RSA_free(_RsaObj);
_RsaObj = nullptr;
}
static RSACipher* Create() {
RSACipher* aCipher = new RSACipher(RSA_new());
if (aCipher->_RsaObj == nullptr) {
delete aCipher;
aCipher = nullptr;
}
return aCipher;
}
bool GenerateKey(int bits, unsigned int e = RSA_F4) {
bool bSuccess = false;
BIGNUM* bn_e = nullptr;
bn_e = BN_new();
if (bn_e == nullptr)
goto ON_RSACipher_GenerateKey0_ERROR;
if (!BN_set_word(bn_e, e))
goto ON_RSACipher_GenerateKey0_ERROR;
if (!RSA_generate_key_ex(_RsaObj, bits, bn_e, nullptr))
goto ON_RSACipher_GenerateKey0_ERROR;
bSuccess = true;
ON_RSACipher_GenerateKey0_ERROR:
if (bn_e)
BN_free(bn_e);
return bSuccess;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
bool ExportKeyToFile(const std::string& filename) {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
bool bSuccess = false;
BIO* bio_file = nullptr;
bio_file = BIO_new_file(filename.c_str(), "w");
if (bio_file == nullptr)
goto ON_RSACipher_ExportKeyToFile_0_ERROR;
if (_Type == KeyType::PrivateKey) {
bSuccess = PEM_write_bio_RSAPrivateKey(bio_file, _RsaObj, nullptr, nullptr, 0, nullptr, nullptr) ? true : false;
} else {
if (_Format == KeyFormat::PEM)
bSuccess = PEM_write_bio_RSA_PUBKEY(bio_file, _RsaObj) ? true : false;
else if (_Format == KeyFormat::PKCS1)
bSuccess = PEM_write_bio_RSAPublicKey(bio_file, _RsaObj) ? true : false;
}
ON_RSACipher_ExportKeyToFile_0_ERROR:
return bSuccess;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
std::string ExportKeyString() {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
std::string KeyString;
BIO* bio_mem = nullptr;
int len = 0;
const char* lpdata = nullptr;
bio_mem = BIO_new(BIO_s_mem());
if (bio_mem == nullptr)
goto ON_RSACipher_ExportKeyString_0_ERROR;
if (_Type == KeyType::PrivateKey) {
if (!PEM_write_bio_RSAPrivateKey(bio_mem, _RsaObj, nullptr, nullptr, 0, nullptr, nullptr))
goto ON_RSACipher_ExportKeyString_0_ERROR;
} else {
if (_Format == KeyFormat::PEM) {
if (!PEM_write_bio_RSA_PUBKEY(bio_mem, _RsaObj))
goto ON_RSACipher_ExportKeyString_0_ERROR;
} else if (_Format == KeyFormat::PKCS1) {
if (!PEM_write_bio_RSAPublicKey(bio_mem, _RsaObj))
goto ON_RSACipher_ExportKeyString_0_ERROR;
}
}
len = BIO_get_mem_data(bio_mem, &lpdata);
KeyString.resize(len);
memcpy(KeyString.data(), lpdata, len);
ON_RSACipher_ExportKeyString_0_ERROR:
if (bio_mem)
BIO_free_all(bio_mem);
return KeyString;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
bool ImportKeyFromFile(const std::string& filename) {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
bool bSuccess = false;
BIO* bio_file = nullptr;
RSA* _newRsaObj = nullptr;
bio_file = BIO_new_file(filename.c_str(), "r");
if (bio_file == nullptr)
goto ON_RSACipher_ImportKeyFromFile_0_ERROR;
if (_Type == KeyType::PrivateKey) {
_newRsaObj = PEM_read_bio_RSAPrivateKey(bio_file, nullptr, nullptr, nullptr);
} else {
if (_Format == KeyFormat::PEM)
_newRsaObj = PEM_read_bio_RSA_PUBKEY(bio_file, nullptr, nullptr, nullptr);
else if (_Format == KeyFormat::PKCS1)
_newRsaObj = PEM_read_bio_RSAPublicKey(bio_file, nullptr, nullptr, nullptr);
}
if (_newRsaObj) {
RSA_free(_RsaObj);
_RsaObj = _newRsaObj;
bSuccess = true;
}
ON_RSACipher_ImportKeyFromFile_0_ERROR:
if (bio_file)
BIO_free_all(bio_file);
return bSuccess;
}
template<KeyType _Type, KeyFormat _Format = KeyFormat::NotSpecified>
bool ImportKeyString(const std::string& KeyString) {
static_assert(
_Type == KeyType::PrivateKey || (_Format == KeyFormat::PEM || _Format == KeyFormat::PKCS1),
"Not supported format."
);
bool bSuccess = false;
BIO* bio_mem = nullptr;
RSA* _newRsaObj = nullptr;
bio_mem = BIO_new(BIO_s_mem());
if (bio_mem == nullptr)
goto ON_RSACipher_ImportKeyString_0_ERROR;
BIO_puts(bio_mem, KeyString.c_str());
if (_Type == KeyType::PrivateKey) {
_newRsaObj = PEM_read_bio_RSAPrivateKey(bio_mem, nullptr, nullptr, nullptr);
} else {
if (_Format == KeyFormat::PEM)
_newRsaObj = PEM_read_bio_RSA_PUBKEY(bio_mem, nullptr, nullptr, nullptr);
else if (_Format == KeyFormat::PKCS1)
_newRsaObj = PEM_read_bio_RSAPublicKey(bio_mem, nullptr, nullptr, nullptr);
}
if (_newRsaObj) {
RSA_free(_RsaObj);
_RsaObj = _newRsaObj;
bSuccess = true;
}
ON_RSACipher_ImportKeyString_0_ERROR:
if (bio_mem)
BIO_free_all(bio_mem);
return bSuccess;
}
template<KeyType _Type = KeyType::PublicKey>
int Encrypt(const void* from, int len, void* to, int padding) {
int write_bytes = 0;
if (_Type == KeyType::PrivateKey) {
write_bytes = RSA_private_encrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
} else {
write_bytes = RSA_public_encrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
}
if (write_bytes == -1)
write_bytes = 0;
return write_bytes;
}
template<KeyType _Type = KeyType::PrivateKey>
int Decrypt(const void* from, int len, void* to, int padding) {
int write_bytes = 0;
if (_Type == KeyType::PrivateKey) {
write_bytes = RSA_private_decrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
} else {
write_bytes = RSA_public_decrypt(len,
reinterpret_cast<const unsigned char*>(from),
reinterpret_cast<unsigned char*>(to),
_RsaObj,
padding);
}
if (write_bytes == -1)
write_bytes = 0;
return write_bytes;
}
};
@@ -0,0 +1,33 @@
#pragma once
#include <capstone/capstone.h>
struct CapstoneHandleTraits {
using HandleType = csh;
static inline const HandleType InvalidValue = NULL;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(HandleType& Handle) noexcept {
cs_close(&Handle);
}
};
struct CapstoneInsnTraits {
using HandleType = cs_insn*;
static inline const HandleType InvalidValue = nullptr;
[[nodiscard]]
static bool IsValid(const HandleType& Handle) noexcept {
return Handle != InvalidValue;
}
static void Releasor(const HandleType& Handle) noexcept {
cs_free(Handle, 1);
}
};
-262
View File
@@ -1,262 +0,0 @@
#include "def.hpp"
// The following APIs are in version.lib
// GetFileVersionInfoSize
// GetFileVersionInfo
// VerQueryValue
// #pragma comment(lib, "version.lib")
namespace Patcher {
const char Solution0::Keyword[461] =
"-----BEGIN PUBLIC KEY-----\r\n"
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I\r\n"
"qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv\r\n"
"a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF\r\n"
"R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2\r\n"
"WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt\r\n"
"YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ\r\n"
"awIDAQAB\r\n"
"-----END PUBLIC KEY-----\r\n";
BOOL Solution0::SetPath(const std::Tstring& Path) {
DWORD Attr;
Attr = GetFileAttributes(Path.c_str());
if (Attr == INVALID_FILE_ATTRIBUTES) {
if (GetLastError() == ERROR_INVALID_NAME || GetLastError() == ERROR_FILE_NOT_FOUND)
REPORT_ERROR("ERROR: Invalid path. Are you sure the path you specified is correct?");
else
REPORT_ERROR_WITH_CODE("ERROR: GetFileAttributes failed.", GetLastError());
return FALSE;
}
if ((Attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
REPORT_ERROR("ERROR: Path is not a directory.");
return FALSE;
}
ReleaseFile();
InstallationPath = Path;
if (InstallationPath.back() != TEXT('\\') && InstallationPath.back() != TEXT('/'))
InstallationPath.push_back(TEXT('/')); // for Linux compatible
return TRUE;
}
// Solution0 does not have any requirements for RSA-2048 key
BOOL Solution0::CheckKey(RSACipher* cipher) const {
return TRUE;
}
DWORD Solution0::TryFile(const std::Tstring& Name) {
std::Tstring MainAppFullName = InstallationPath + Name;
HANDLE hFile;
hFile = CreateFile(MainAppFullName.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
nullptr, // default SA
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
return GetLastError();
ReleaseFile();
MainAppHandle = hFile;
MainAppName = Name;
return ERROR_SUCCESS;
}
DWORD Solution0::MapFile() {
DWORD dwLastError = ERROR_SUCCESS;
HANDLE hMapping = NULL;
PVOID lpMapView = nullptr;
hMapping = CreateFileMapping(MainAppHandle,
nullptr, // default SA
PAGE_READWRITE,
0, 0, // map all
nullptr); // we don't need a name
if (hMapping == NULL) {
dwLastError = GetLastError();
goto ON_Solution0_MapFile_ERROR;
}
lpMapView = MapViewOfFile(hMapping,
FILE_MAP_READ | FILE_MAP_WRITE,
0, 0, 0); // map all
if (lpMapView == nullptr) {
dwLastError = GetLastError();
goto ON_Solution0_MapFile_ERROR;
}
ReleaseMap();
MainAppMappingView = lpMapView;
lpMapView = nullptr;
MainAppMappingHandle = hMapping;
hMapping = NULL;
ON_Solution0_MapFile_ERROR:
if (hMapping)
CloseHandle(hMapping);
return dwLastError;
}
BOOL Solution0::FindPatchOffset() {
BOOL bFound = FALSE;
DWORD dwFileSize = 0;
uint8_t* lpFileContent = reinterpret_cast<uint8_t*>(MainAppMappingView);
dwFileSize = GetFileSize(MainAppHandle, nullptr);
for (DWORD i = 0; i < dwFileSize; ++i) {
if (memcmp(lpFileContent + i, Keyword, KeywordLength) == 0) {
PatchOffset = i;
bFound = TRUE;
break;
}
}
if (bFound)
_tprintf_s(TEXT("MESSAGE: [Solution0] Keyword has been found: offset = +0x%08lx.\n"), PatchOffset);
return bFound;
}
DWORD Solution0::BackupFile() {
std::Tstring TargetFileFullName = InstallationPath + MainAppName;
std::Tstring BackupFileFullName = InstallationPath + MainAppName + TEXT(".backup");
if (!CopyFile(TargetFileFullName.c_str(), BackupFileFullName.c_str(), TRUE))
return GetLastError();
else
return ERROR_SUCCESS;
}
BOOL Solution0::MakePatch(RSACipher* cipher) {
BOOL bSuccess = FALSE;
uint8_t* lpFileContent = reinterpret_cast<uint8_t*>(MainAppMappingView);
std::string RSAPublicKeyPEM;
RSAPublicKeyPEM = cipher->ExportKeyString<RSACipher::KeyType::PublicKey, RSACipher::KeyFormat::PEM>();
if (RSAPublicKeyPEM.empty()) {
REPORT_ERROR("ERROR: cipher->ExportKeyString failed.");
goto ON_Do_ERROR;
}
// lambda function, replace '\n' to '\r\n'
[](std::string& str, const std::string& OldSub, const std::string& NewSub) {
std::string::size_type pos = 0;
std::string::size_type srclen = OldSub.size();
std::string::size_type dstlen = NewSub.size();
while ((pos = str.find(OldSub, pos)) != std::string::npos) {
str.replace(pos, srclen, NewSub);
pos += dstlen;
}
} (RSAPublicKeyPEM, "\n", "\r\n");
if (RSAPublicKeyPEM.length() != KeywordLength) {
REPORT_ERROR("ERROR: Public key length does not match.");
goto ON_Do_ERROR;
}
_tprintf_s(TEXT("@%s+0x%08X\nPrevious:\n"), MainAppName.c_str(), PatchOffset);
Helper::PrintMemory(lpFileContent + PatchOffset,
lpFileContent + PatchOffset + KeywordLength,
lpFileContent);
memcpy(lpFileContent + PatchOffset, RSAPublicKeyPEM.c_str(), KeywordLength);
PRINT_MESSAGE("After:");
Helper::PrintMemory(lpFileContent + PatchOffset,
lpFileContent + PatchOffset + KeywordLength,
lpFileContent);
PRINT_MESSAGE("");
bSuccess = TRUE;
ON_Do_ERROR:
return bSuccess;
}
// DWORD Solution0::GetMainAppVersion(LPDWORD lpMajorVer, LPDWORD lpMinorVer) {
// BOOL bSuccess = FALSE;
// DWORD dwLastError = ERROR_SUCCESS;
// std::Tstring TargetFileFullName = InstallationPath + MainAppName;
//
// DWORD dwSize = 0;
// PVOID lpData = NULL;
// VS_FIXEDFILEINFO* lpVersionInfo = NULL;
// UINT VersionInfoSize = 0;
//
// dwSize = GetFileVersionInfoSize(TargetFileFullName.c_str(),
// &dwSize); // MSDN doesn't say it can be NULL.
// // so I use dwSize to receive this deprecated value
// if (dwSize == 0) {
// dwLastError = GetLastError();
// REPORT_ERROR_WITH_CODE("ERROR: GetFileVersionInfoSize failed.", dwLastError);
// goto ON_Solution0_GetMainAppVersion_ERROR;
// }
//
// lpData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
// if (lpData == nullptr) {
// dwLastError = GetLastError();
// REPORT_ERROR_WITH_CODE("ERROR: HeapAlloc failed.", dwLastError);
// goto ON_Solution0_GetMainAppVersion_ERROR;
// }
//
// if (!GetFileVersionInfo(TargetFileFullName.c_str(), NULL, dwSize, lpData)) {
// dwLastError = GetLastError();
// REPORT_ERROR_WITH_CODE("ERROR: GetFileVersionInfo failed.", dwLastError);
// goto ON_Solution0_GetMainAppVersion_ERROR;
// }
//
// if (!VerQueryValue(lpData, TEXT("\\"), reinterpret_cast<LPVOID*>(&lpVersionInfo), &VersionInfoSize)) {
// dwLastError = GetLastError();
// REPORT_ERROR_WITH_CODE("ERROR: VerQueryValue failed.", dwLastError);
// goto ON_Solution0_GetMainAppVersion_ERROR;
// }
//
// *lpMajorVer = lpVersionInfo->dwProductVersionMS;
// *lpMinorVer = lpVersionInfo->dwProductVersionLS;
//
// bSuccess = TRUE;
// ON_Solution0_GetMainAppVersion_ERROR:
// if (lpData)
// HeapFree(GetProcessHeap(), NULL, lpData);
// return bSuccess;
// }
const std::Tstring& Solution0::GetMainAppName() {
return MainAppName;
}
void Solution0::ReleaseFile() {
ReleaseMap();
if (MainAppHandle != INVALID_HANDLE_VALUE && MainAppHandle) {
CloseHandle(MainAppHandle);
MainAppHandle = INVALID_HANDLE_VALUE;
}
}
void Solution0::ReleaseMap() {
if (MainAppMappingView) {
UnmapViewOfFile(MainAppMappingView);
MainAppMappingView = nullptr;
}
if (MainAppMappingHandle) {
CloseHandle(MainAppMappingHandle);
MainAppMappingHandle = NULL;
}
}
Solution0::~Solution0() {
ReleaseFile();
}
}
-452
View File
@@ -1,452 +0,0 @@
#include "def.hpp"
namespace Helper {
std::string EncryptPublicKey(const std::string& public_key);
static PIMAGE_SECTION_HEADER ImageSectionHeader(PVOID lpBase, LPCSTR lpSectionName) {
IMAGE_DOS_HEADER* pFileHeader = NULL;
IMAGE_NT_HEADERS* pNtHeader = NULL;
IMAGE_SECTION_HEADER* pSectionHeaders = NULL;
pFileHeader = (IMAGE_DOS_HEADER*)lpBase;
if (pFileHeader->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
pNtHeader = (IMAGE_NT_HEADERS*)((BYTE*)lpBase + pFileHeader->e_lfanew);
if (pNtHeader->Signature != IMAGE_NT_SIGNATURE)
return NULL;
pSectionHeaders = (IMAGE_SECTION_HEADER*)((BYTE*)pNtHeader +
offsetof(IMAGE_NT_HEADERS, OptionalHeader) +
pNtHeader->FileHeader.SizeOfOptionalHeader);
for (WORD i = 0; i < pNtHeader->FileHeader.NumberOfSections; ++i)
if (_stricmp((const char*)pSectionHeaders[i].Name, lpSectionName) == 0)
return pSectionHeaders + i;
return NULL;
}
}
namespace Patcher {
const char* Solution1::Keywords[5] = {
"D75125B70767B94145B47C1CB3C0755E"
"7CCB8825C5DCE0C58ACF944E08280140"
"9A02472FAFFD1CD77864BB821AE36766"
"FEEDE6A24F12662954168BFA314BD950"
"32B9D82445355ED7BC0B880887D650F5",
"\xfe\xea\xbc\x01",
"E1CED09B9C2186BF71A70C0FE2F1E0AE"
"F3BD6B75277AAB20DFAF3D110F75912B"
"FB63AC50EC4C48689D1502715243A79F"
"39FF2DE2BF15CE438FF885745ED54573"
"850E8A9F40EE2FF505EB7476F95ADB78"
"3B28CA374FAC4632892AB82FB3BF4715"
"FCFE6E82D03731FC3762B6AAC3DF1C3B"
"C646FE9CD3C62663A97EE72DB932A301"
"312B4A7633100C8CC357262C39A2B3A6"
"4B224F5276D5EDBDF0804DC3AC4B8351"
"62BB1969EAEBADC43D2511D6E0239287"
"81B167A48273B953378D3D2080CC0677"
"7E8A2364F0234B81064C5C739A8DA28D"
"C5889072BF37685CBC94C2D31D0179AD"
"86D8E3AA8090D4F0B281BE37E0143746"
"E6049CCC06899401264FA471C016A96C"
"79815B55BBC26B43052609D9D175FBCD"
"E455392F10E51EC162F51CF732E6BB39"
"1F56BBFD8D957DF3D4C55B71CEFD54B1"
"9C16D458757373E698D7E693A8FC3981"
"5A8BF03BA05EA8C8778D38F9873D62B4"
"460F41ACF997C30E7C3AF025FA171B5F"
"5AD4D6B15E95C27F6B35AD61875E5505"
"449B4E",
"\x59\x08\x01\x00",
"92933"
};
const int Solution1::KeywordsLength[5] = {
160,
4,
742,
4,
5
};
BOOL Solution1::SetPath(const std::Tstring& Path) {
DWORD Attr;
Attr = GetFileAttributes(Path.c_str());
if (Attr == INVALID_FILE_ATTRIBUTES) {
if (GetLastError() == ERROR_INVALID_NAME || GetLastError() == ERROR_FILE_NOT_FOUND)
REPORT_ERROR("ERROR: Invalid path. Are you sure the path you specified is correct?");
else
REPORT_ERROR_WITH_CODE("ERROR: GetFileAttributes failed.", GetLastError());
return FALSE;
}
if ((Attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
REPORT_ERROR("ERROR: Path is not a directory.");
return FALSE;
}
ReleaseFile();
InstallationPath = Path;
if (InstallationPath.back() != TEXT('\\') && InstallationPath.back() != TEXT('/'))
InstallationPath.push_back(TEXT('/')); // for Linux compatible
return TRUE;
}
BOOL Solution1::CheckKey(RSACipher* cipher) const {
BOOL bOk = FALSE;
std::string RSAPublicKeyPEM;
RSAPublicKeyPEM = cipher->ExportKeyString<RSACipher::KeyType::PublicKey, RSACipher::KeyFormat::PEM>();
if (RSAPublicKeyPEM.empty()) {
_tprintf_s(TEXT("@%s LINE: %u\n"), TEXT(__FUNCTION__), __LINE__);
_tprintf_s(TEXT("ERROR: cipher->ExportKeyString failed.\n"));
return FALSE;
}
[](std::string& str, const std::string& OldSub, const std::string& NewSub) {
std::string::size_type pos = 0;
std::string::size_type srclen = OldSub.size();
std::string::size_type dstlen = NewSub.size();
while ((pos = str.find(OldSub, pos)) != std::string::npos) {
str.replace(pos, srclen, NewSub);
pos += dstlen;
}
} (RSAPublicKeyPEM, "\n", "\r\n"); // replace '\n' to '\r\n'
std::string encrypted_pem_text = Helper::EncryptPublicKey(RSAPublicKeyPEM);
if (encrypted_pem_text[160] > '9' || encrypted_pem_text[160] < '1')
return FALSE;
for (int i = 1; i < 8; ++i)
if (encrypted_pem_text[160 + i] > '9' || encrypted_pem_text[160 + i] < '0')
return FALSE;
if (encrypted_pem_text[910] > '9' || encrypted_pem_text[910] < '1')
return FALSE;
for (int i = 1; i < 5; ++i)
if (encrypted_pem_text[910 + i] > '9' || encrypted_pem_text[910 + i] < '0')
return FALSE;
return TRUE;
}
DWORD Solution1::TryFile(const std::Tstring& Name) {
std::Tstring MainAppFullName = InstallationPath + Name;
HANDLE hFile;
hFile = CreateFile(MainAppFullName.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
nullptr, // default SA
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
return GetLastError();
ReleaseFile();
LibccHandle = hFile;
LibccName = Name;
return ERROR_SUCCESS;
}
DWORD Solution1::MapFile() {
DWORD dwLastError = ERROR_SUCCESS;
HANDLE hMapping = NULL;
PVOID lpMapView = nullptr;
hMapping = CreateFileMapping(LibccHandle,
nullptr, // default SA
PAGE_READWRITE,
0, 0, // map all
nullptr); // we don't need a name
if (hMapping == NULL) {
dwLastError = GetLastError();
goto ON_Solution0_MapFile_ERROR;
}
lpMapView = MapViewOfFile(hMapping,
FILE_MAP_READ | FILE_MAP_WRITE,
0, 0, 0); // map all
if (lpMapView == nullptr) {
dwLastError = GetLastError();
goto ON_Solution0_MapFile_ERROR;
}
ReleaseMap();
LibccMappingView = lpMapView;
lpMapView = nullptr;
LibccMappingHandle = hMapping;
hMapping = NULL;
ON_Solution0_MapFile_ERROR:
if (hMapping)
CloseHandle(hMapping);
return dwLastError;
}
BOOL Solution1::FindPatchOffset() {
IMAGE_SECTION_HEADER* textSection = nullptr;
IMAGE_SECTION_HEADER* rdataSection = nullptr;
uint8_t* lpFileContent = reinterpret_cast<uint8_t*>(LibccMappingView);
off_t Offsets[5] = { -1, -1, -1, -1, -1 };
textSection = Helper::ImageSectionHeader(lpFileContent, ".text");
if (textSection == nullptr) {
// REPORT_ERROR("ERROR: Cannot find .text section.");
return FALSE;
}
rdataSection = Helper::ImageSectionHeader(lpFileContent, ".rdata");
if (textSection == nullptr) {
// REPORT_ERROR("ERROR: Cannot find .rdata section.");
return FALSE;
}
// -------------------------
// try to search Keywords[0]
// -------------------------
for (DWORD i = 0; i < rdataSection->SizeOfRawData; ++i) {
if (memcmp(lpFileContent + rdataSection->PointerToRawData + i, Keywords[0], KeywordsLength[0]) == 0) {
Offsets[0] = rdataSection->PointerToRawData + i;
break;
}
}
if (Offsets[0] == -1) {
// REPORT_ERROR("ERROR: Cannot find Keywords[0].");
return FALSE;
}
// -------------------------
// try to search Keywords[2]
// -------------------------
for (DWORD i = 0; i < rdataSection->SizeOfRawData; ++i) {
if (memcmp(lpFileContent + rdataSection->PointerToRawData + i, Keywords[2], KeywordsLength[2]) == 0) {
Offsets[2] = rdataSection->PointerToRawData + i;
break;
}
}
if (Offsets[2] == -1) {
// REPORT_ERROR("ERROR: Cannot find Keywords[2].");
return FALSE;
}
// -------------------------
// try to search Keywords[4]
// -------------------------
for (DWORD i = 0; i < rdataSection->SizeOfRawData; ++i) {
if (memcmp((uint8_t*)lpFileContent + rdataSection->PointerToRawData + i, Keywords[4], KeywordsLength[4]) == 0) {
Offsets[4] = rdataSection->PointerToRawData + i;
break;
}
}
if (Offsets[4] == -1) {
// REPORT_ERROR("ERROR: Cannot find Keywords[4].");
return FALSE;
}
// -------------------------
// try to search Keywords[1] and Keywords[3]
// -------------------------
for (DWORD i = 0; i < textSection->SizeOfRawData; ++i) {
if (memcmp(lpFileContent + textSection->PointerToRawData + i, Keywords[1], KeywordsLength[1]) == 0) {
// Keywords[3] must be close to Keywords[1]
for (DWORD j = i - 64; j < i + 64; ++j) {
if (memcmp(lpFileContent + textSection->PointerToRawData + j, Keywords[3], KeywordsLength[3]) == 0) {
Offsets[1] = textSection->PointerToRawData + i;
Offsets[3] = textSection->PointerToRawData + j;
break;
}
}
// Offsets[1] and Offsets[3] are set synchronously
// so check Offsets[1] is enough
if (Offsets[1] != -1)
break;
}
}
if (Offsets[1] == -1) {
// REPORT_ERROR("ERROR: Cannot find Keywords[1] and Keywords[3].");
return FALSE;
}
PatchOffsets[0] = Offsets[0];
PatchOffsets[1] = Offsets[1];
PatchOffsets[2] = Offsets[2];
PatchOffsets[3] = Offsets[3];
PatchOffsets[4] = Offsets[4];
_tprintf_s(TEXT("MESSAGE: [Solution1] Keywords[0] has been found: offset = +0x%08lx.\n"), PatchOffsets[0]);
_tprintf_s(TEXT("MESSAGE: [Solution1] Keywords[1] has been found: offset = +0x%08lx.\n"), PatchOffsets[1]);
_tprintf_s(TEXT("MESSAGE: [Solution1] Keywords[2] has been found: offset = +0x%08lx.\n"), PatchOffsets[2]);
_tprintf_s(TEXT("MESSAGE: [Solution1] Keywords[3] has been found: offset = +0x%08lx.\n"), PatchOffsets[3]);
_tprintf_s(TEXT("MESSAGE: [Solution1] Keywords[4] has been found: offset = +0x%08lx.\n"), PatchOffsets[4]);
return TRUE;
}
DWORD Solution1::BackupFile() {
std::Tstring TargetFileFullName = InstallationPath + LibccName;
std::Tstring BackupFileFullName = InstallationPath + LibccName + TEXT(".backup");
if (!CopyFile(TargetFileFullName.c_str(), BackupFileFullName.c_str(), TRUE))
return GetLastError();
else
return ERROR_SUCCESS;
}
BOOL Solution1::MakePatch(RSACipher* cipher) {
std::string RSAPublicKeyPEM;
std::string encrypted_pem_pubkey;
uint8_t* lpFileContent = reinterpret_cast<uint8_t*>(LibccMappingView);
RSAPublicKeyPEM = cipher->ExportKeyString<RSACipher::KeyType::PublicKey, RSACipher::KeyFormat::PEM>();
if (RSAPublicKeyPEM.empty()) {
REPORT_ERROR("ERROR: cipher->ExportKeyString failed.");
return FALSE;
}
[](std::string& str, const std::string& OldSub, const std::string& NewSub) {
std::string::size_type pos = 0;
std::string::size_type srclen = OldSub.size();
std::string::size_type dstlen = NewSub.size();
while ((pos = str.find(OldSub, pos)) != std::string::npos) {
str.replace(pos, srclen, NewSub);
pos += dstlen;
}
} (RSAPublicKeyPEM, "\n", "\r\n"); // replace '\n' to '\r\n'
encrypted_pem_pubkey = Helper::EncryptPublicKey(RSAPublicKeyPEM);
// split encrypted_pem_pubkey to 5 part: |160 chars|8 chars|742 chars|5 chars|5 chars|
// | |
// \ / \ /
// imm1 imm3
std::string encrypted_pem_pubkey0(encrypted_pem_pubkey.begin(), encrypted_pem_pubkey.begin() + 160);
std::string encrypted_pem_pubkey1(encrypted_pem_pubkey.begin() + 160, encrypted_pem_pubkey.begin() + 160 + 8);
std::string encrypted_pem_pubkey2(encrypted_pem_pubkey.begin() + 160 + 8, encrypted_pem_pubkey.begin() + 160 + 8 + 742);
std::string encrypted_pem_pubkey3(encrypted_pem_pubkey.begin() + 160 + 8 + 742, encrypted_pem_pubkey.begin() + 160 + 8 + 742 + 5);
std::string encrypted_pem_pubkey4(encrypted_pem_pubkey.begin() + 160 + 8 + 742 + 5, encrypted_pem_pubkey.end());
uint32_t imm1 = std::stoul(encrypted_pem_pubkey1.c_str());
uint32_t imm3 = std::stoul(encrypted_pem_pubkey3.c_str());
// ----------------------------------
// process PatchOffsets[0]
// ----------------------------------
_tprintf_s(TEXT("@libcc.dll+0x%08X\nPrevious:\n"), PatchOffsets[0]);
Helper::PrintMemory(lpFileContent + PatchOffsets[0],
lpFileContent + PatchOffsets[0] + KeywordsLength[0],
lpFileContent);
memcpy(lpFileContent + PatchOffsets[0], encrypted_pem_pubkey0.c_str(), KeywordsLength[0]);
PRINT_MESSAGE("After:");
Helper::PrintMemory(lpFileContent + PatchOffsets[0],
lpFileContent + PatchOffsets[0] + KeywordsLength[0],
lpFileContent);
PRINT_MESSAGE("");
// ----------------------------------
// process PatchOffsets[1]
// ----------------------------------
_tprintf_s(TEXT("@libcc.dll+0x%08X\nPrevious:\n"), PatchOffsets[1]);
Helper::PrintMemory(lpFileContent + PatchOffsets[1],
lpFileContent + PatchOffsets[1] + KeywordsLength[1],
lpFileContent);
memcpy(lpFileContent + PatchOffsets[1], &imm1, KeywordsLength[1]);
PRINT_MESSAGE("After:");
Helper::PrintMemory(lpFileContent + PatchOffsets[1],
lpFileContent + PatchOffsets[1] + KeywordsLength[1],
lpFileContent);
PRINT_MESSAGE("");
// ----------------------------------
// process PatchOffsets[2]
// ----------------------------------
_tprintf_s(TEXT("@libcc.dll+0x%08X\nPrevious:\n"), PatchOffsets[2]);
Helper::PrintMemory(lpFileContent + PatchOffsets[2],
lpFileContent + PatchOffsets[2] + KeywordsLength[2],
lpFileContent);
memcpy(lpFileContent + PatchOffsets[2], encrypted_pem_pubkey2.c_str(), KeywordsLength[2]);
PRINT_MESSAGE("After:");
Helper::PrintMemory(lpFileContent + PatchOffsets[2],
lpFileContent + PatchOffsets[2] + KeywordsLength[2],
lpFileContent);
PRINT_MESSAGE("");
// ----------------------------------
// process PatchOffsets[3]
// ----------------------------------
_tprintf_s(TEXT("@libcc.dll+0x%08X\nPrevious:\n"), PatchOffsets[3]);
Helper::PrintMemory(lpFileContent + PatchOffsets[3],
lpFileContent + PatchOffsets[3] + KeywordsLength[3],
lpFileContent);
memcpy(lpFileContent + PatchOffsets[3], &imm3, KeywordsLength[3]);
PRINT_MESSAGE("After:");
Helper::PrintMemory(lpFileContent + PatchOffsets[3],
lpFileContent + PatchOffsets[3] + KeywordsLength[3],
lpFileContent);
PRINT_MESSAGE("");
// ----------------------------------
// process PatchOffsets[4]
// ----------------------------------
_tprintf_s(TEXT("@libcc.dll+0x%08X\nPrevious:\n"), PatchOffsets[4]);
Helper::PrintMemory(lpFileContent + PatchOffsets[4],
lpFileContent + PatchOffsets[4] + KeywordsLength[4],
lpFileContent);
memcpy(lpFileContent + PatchOffsets[4], encrypted_pem_pubkey4.c_str(), KeywordsLength[4]);
PRINT_MESSAGE("After:");
Helper::PrintMemory(lpFileContent + PatchOffsets[4],
lpFileContent + PatchOffsets[4] + KeywordsLength[4],
lpFileContent);
PRINT_MESSAGE("");
return TRUE;
}
void Solution1::ReleaseFile() {
ReleaseMap();
if (LibccHandle != INVALID_HANDLE_VALUE && LibccHandle) {
CloseHandle(LibccHandle);
LibccHandle = INVALID_HANDLE_VALUE;
}
}
void Solution1::ReleaseMap() {
if (LibccMappingView) {
UnmapViewOfFile(LibccMappingView);
LibccMappingView = nullptr;
}
if (LibccMappingHandle) {
CloseHandle(LibccMappingHandle);
LibccMappingHandle = NULL;
}
}
Solution1::~Solution1() {
ReleaseFile();
}
}
+426 -234
View File
@@ -1,254 +1,446 @@
#include "def.hpp"
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
static void help() {
PRINT_MESSAGE("Usage:");
PRINT_MESSAGE(" navicat-patcher.exe <Navicat installation path> [RSA-2048 PEM file]");
#include <Exception.hpp>
#include <ExceptionWin32.hpp>
#include <ResourceOwned.hpp>
#include <ResourceTraitsWin32.hpp>
#include "ImageInterpreter.hpp"
#include "PatchSolutions.hpp"
#include "Misc.hpp"
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE
#define NKG_CURRENT_SOURCE_FILE() TEXT(".\\navicat-patcher\\_tmain.cpp")
#define NKG_CURRENT_SOURCE_LINE() __LINE__
static void Welcome() {
_putts(TEXT("***************************************************"));
_putts(TEXT("* Navicat Patcher by @DoubleLabyrinth *"));
_putts(TEXT("* Version: 4.0 *"));
_putts(TEXT("***************************************************"));
_putts(TEXT(""));
_putts(TEXT("Press Enter to continue or Ctrl + C to abort."));
auto c = _gettchar();
while (c != TEXT('\n') && _gettchar() != TEXT('\n')) {}
}
static BOOL LoadKey(RSACipher* cipher, LPTSTR filename, Patcher::Solution0* pSolution0, Patcher::Solution1* pSolution1) {
if (filename) {
std::string PrivateKeyFileName;
static void Help() {
_putts(TEXT("***************************************************"));
_putts(TEXT("* Navicat Patcher by @DoubleLabyrinth *"));
_putts(TEXT("* Version: 4.0 *"));
_putts(TEXT("***************************************************"));
_putts(TEXT(""));
_putts(TEXT("Usage:"));
_putts(TEXT(" navicat-patcher.exe [-dry-run] <Navicat Installation Path> [RSA-2048 PEM File Path]"));
_putts(TEXT(""));
_putts(TEXT(" [-dry-run] Run patcher without applying any patches."));
_putts(TEXT(" This parameter is optional."));
_putts(TEXT(""));
_putts(TEXT(" <Navicat Installation Path> The folder path where Navicat is installed."));
_putts(TEXT(" This parameter must be specified."));
_putts(TEXT(""));
_putts(TEXT(" [RSA-2048 PEM File Path] The path to an RSA-2048 private key file."));
_putts(TEXT(" This parameter is optional."));
_putts(TEXT(" If not specified, an RSA-2048 private key file"));
_putts(TEXT(" named \"RegPrivateKey.pem\" will be generated."));
_putts(TEXT(""));
_putts(TEXT("Example:"));
_putts(TEXT(" navicat-patcher.exe \"C:\\Program Files\\PremiumSoft\\Navicat Premium 12\""));
}
if (!Helper::ConvertToUTF8(filename, PrivateKeyFileName)) {
REPORT_ERROR("ERROR: ConvertToUTF8 failed.");
return FALSE;
static bool ParseCommandLine(int argc, PTSTR argv[], bool& bDryRun, std::xstring& NavInstallPath, std::xstring& RsaPrivateKeyPath) {
if (argc == 2) {
bDryRun = false;
NavInstallPath = argv[1];
RsaPrivateKeyPath.clear();
return true;
} else if (argc == 3) {
if (_tcsicmp(argv[1], TEXT("-dry-run")) == 0) {
bDryRun = true;
NavInstallPath = argv[2];
RsaPrivateKeyPath.clear();
return true;
} else {
bDryRun = false;
NavInstallPath = argv[1];
RsaPrivateKeyPath = argv[2];
return true;
}
if (!cipher->ImportKeyFromFile<RSACipher::KeyType::PrivateKey, RSACipher::KeyFormat::PEM>(PrivateKeyFileName)) {
REPORT_ERROR("ERROR: cipher->ImportKeyFromFile failed.");
return FALSE;
} else if (argc == 4) {
if (_tcsicmp(argv[1], TEXT("-dry-run")) == 0) {
bDryRun = true;
NavInstallPath = argv[2];
RsaPrivateKeyPath = argv[3];
return true;
} else {
return false;
}
if (pSolution0 && !pSolution0->CheckKey(cipher) ||
pSolution1 && !pSolution1->CheckKey(cipher)) {
REPORT_ERROR("ERROR: The RSA private key you provide cannot be used.");
return FALSE;
}
} else {
PRINT_MESSAGE("MESSAGE: Generating new RSA private key, it may take a long time.");
return false;
}
}
static void SelectPatchSolutions(
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution0,
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution1,
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution2,
ResourceOwned<CppObjectTraits<nkg::PatchSolution>>& lpSolution3)
{
// if RSA public is detected in libcc.dll, don't patch main application to keep digital signature valid.
if ((lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) && lpSolution0.IsValid()) {
LOG_HINT(0, "PatchSolution0 is suppressed in order to keep digital signature valid.");
lpSolution0.Release();
}
}
static void NavicatBackupDetect(const std::xstring& FilePath) {
if (std::xstring BackupPath = FilePath + TEXT(".backup"); nkg::IsValidFilePath(BackupPath.c_str()) == true) {
while (true) {
LOG_SELECT(0, "Previous backup %s detected. Delete? (y/n)", BackupPath.c_str());
auto select = _gettchar();
while (select != TEXT('\n') && _gettchar() != TEXT('\n')) {}
if (select == TEXT('Y') || select == TEXT('y')) {
if (!DeleteFile(BackupPath.c_str())) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to delete backup file."));
} else {
break;
}
} else if (select == TEXT('N') || select == TEXT('n')) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Backup file still existed. Patch abort!"));
} else {
continue;
}
}
_putts(TEXT(""));
}
}
static void NavicatBackupMake(const std::xstring& FilePath) {
std::xstring BackupPath = FilePath + TEXT(".backup");
if (CopyFile(FilePath.c_str(), BackupPath.c_str(), TRUE) == FALSE) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CopyFile failed."));
}
}
static void LoadKey(
nkg::RSACipher& Cipher, const std::xstring& KeyFilePath,
nkg::PatchSolution* pSolution0,
nkg::PatchSolution* pSolution1,
nkg::PatchSolution* pSolution2,
nkg::PatchSolution* pSolution3)
{
if (KeyFilePath.empty() == false) {
LOG_HINT(0, "Import RSA-2048 key from %s", KeyFilePath.c_str());
Cipher.ImportKeyFromFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(KeyFilePath);
if (pSolution0 && !pSolution0->CheckKey(Cipher) ||
pSolution1 && !pSolution1->CheckKey(Cipher) ||
pSolution2 && !pSolution2->CheckKey(Cipher) ||
pSolution3 && !pSolution3->CheckKey(Cipher))
{
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("The RSA private key you provide cannot be used."));
}
} else {
LOG_HINT(0, "Generating new RSA private key, it may take a long time...");
do {
cipher->GenerateKey(2048);
} while (pSolution0 && !pSolution0->CheckKey(cipher) ||
pSolution1 && !pSolution1->CheckKey(cipher)); // re-generate RSA key if one of CheckKey return FALSE
if (!cipher->ExportKeyToFile<RSACipher::KeyType::PrivateKey, RSACipher::KeyFormat::NotSpecified>("RegPrivateKey.pem")) {
REPORT_ERROR("ERROR: Failed to save RSA private key.");
return FALSE;
}
PRINT_MESSAGE("MESSAGE: New RSA private key has been saved to RegPrivateKey.pem.");
Cipher.GenerateKey(2048);
} while (pSolution0 && !pSolution0->CheckKey(Cipher) ||
pSolution1 && !pSolution1->CheckKey(Cipher) ||
pSolution2 && !pSolution2->CheckKey(Cipher) ||
pSolution3 && !pSolution3->CheckKey(Cipher)); // re-generate RSA key if one of 'CheckKey's return false
}
std::string PublicKeyString = cipher->ExportKeyString<RSACipher::KeyType::PublicKey, RSACipher::KeyFormat::PEM>();
if (PublicKeyString.empty()) {
REPORT_ERROR("ERROR: cipher->ExportKeyString failed.");
return FALSE;
}
PRINT_MESSAGE("Your RSA public key:");
PRINT_LPCSTR(PublicKeyString.c_str());
return TRUE;
LOG_HINT(0, "Your RSA public key:\n%hs", Cipher.ExportKeyString<nkg::RSAKeyType::PublicKey, nkg::RSAKeyFormat::PEM>().c_str());
}
int _tmain(int argc, TCHAR* argv[]) {
if (argc != 2 && argc != 3) {
help();
return 0;
}
int _tmain(int argc, PTSTR argv[]) {
bool bDryRun;
std::xstring NavInstallPath;
std::xstring RsaPrivateKeyPath;
RSACipher* cipher = nullptr;
Patcher::Solution0* pSolution0 = nullptr;
Patcher::Solution1* pSolution1 = nullptr;
DWORD ErrorCode;
cipher = RSACipher::Create();
if (cipher == nullptr) {
REPORT_ERROR("ERROR: RSACipher::Create failed.");
goto ON_tmain_ERROR;
}
pSolution0 = new Patcher::Solution0();
pSolution1 = new Patcher::Solution1();
if (!pSolution0->SetPath(argv[1])) {
PRINT_MESSAGE("The path you specified:");
PRINT_LPCTSTR(argv[1]);
goto ON_tmain_ERROR;
}
if (!pSolution1->SetPath(argv[1])) {
PRINT_MESSAGE("The path you specified:");
PRINT_LPCTSTR(argv[1]);
goto ON_tmain_ERROR;
}
FindMainApp:
ErrorCode = pSolution0->TryFile(TEXT("Navicat.exe"));
if (ErrorCode == ERROR_SUCCESS) {
PRINT_MESSAGE("MESSAGE: Navicat.exe has been found.");
goto FindLibcc;
}else if (ErrorCode == ERROR_ACCESS_DENIED) {
PRINT_MESSAGE("ERROR: Cannot open Navicat.exe for ERROR_ACCESS_DENIED.");
PRINT_MESSAGE("Please re-run with Administrator privilege.");
goto ON_tmain_ERROR;
}
if (ErrorCode != ERROR_FILE_NOT_FOUND) {
REPORT_ERROR_WITH_CODE("ERROR: Cannot open Navicat.exe.", ErrorCode);
goto ON_tmain_ERROR;
}
ErrorCode = pSolution0->TryFile(TEXT("Modeler.exe"));
if (ErrorCode == ERROR_SUCCESS) {
PRINT_MESSAGE("MESSAGE: Modeler.exe has been found.");
goto FindLibcc;
}
if (ErrorCode == ERROR_ACCESS_DENIED) {
PRINT_MESSAGE("ERROR: Cannot open Modeler.exe for ERROR_ACCESS_DENIED.");
PRINT_MESSAGE("Please re-run with Administrator privilege.");
goto ON_tmain_ERROR;
}
if (ErrorCode != ERROR_FILE_NOT_FOUND) {
REPORT_ERROR_WITH_CODE("ERROR: Cannot open Modeler.exe.", ErrorCode);
goto ON_tmain_ERROR;
}
ErrorCode = pSolution0->TryFile(TEXT("Rviewer.exe"));
if (ErrorCode == ERROR_SUCCESS) {
PRINT_MESSAGE("MESSAGE: Rviewer.exe has been found.");
goto FindLibcc;
}
if (ErrorCode == ERROR_ACCESS_DENIED) {
PRINT_MESSAGE("ERROR: Cannot open Rviewer.exe for ERROR_ACCESS_DENIED.");
PRINT_MESSAGE("Please re-run with Administrator privilege.");
goto ON_tmain_ERROR;
}
if (ErrorCode != ERROR_FILE_NOT_FOUND) {
REPORT_ERROR_WITH_CODE("ERROR: Cannot open Rviewer.exe.", ErrorCode);
goto ON_tmain_ERROR;
}
PRINT_MESSAGE("ERROR: Cannot find main application. Are you sure the path you specified is correct?");
PRINT_MESSAGE("The path you specified:");
PRINT_LPCTSTR(argv[1]);
goto ON_tmain_ERROR;
FindLibcc:
ErrorCode = pSolution1->TryFile(TEXT("libcc.dll"));
if (ErrorCode == ERROR_SUCCESS) {
PRINT_MESSAGE("MESSAGE: libcc.dll has been found.");
} else if (ErrorCode == ERROR_FILE_NOT_FOUND) {
PRINT_MESSAGE("MESSAGE: libcc.dll is not found. Solution1 will be omitted.");
delete pSolution1;
pSolution1 = nullptr;
} else if (ErrorCode == ERROR_ACCESS_DENIED) {
PRINT_MESSAGE("ERROR: Cannot open libcc.dll for ERROR_ACCESS_DENIED.");
PRINT_MESSAGE("Please re-run with Administrator privilege.");
goto ON_tmain_ERROR;
if (ParseCommandLine(argc, argv, bDryRun, NavInstallPath, RsaPrivateKeyPath) == false) {
Help();
return -1;
} else {
REPORT_ERROR_WITH_CODE("ERROR: Cannot open libcc.dll.", ErrorCode);
goto ON_tmain_ERROR;
}
Welcome();
SearchPublicKey:
PRINT_MESSAGE("");
ErrorCode = pSolution0->MapFile();
if (ErrorCode != ERROR_SUCCESS) {
_tprintf_s(TEXT("@%s LINE: %u\n"), TEXT(__FUNCTION__), __LINE__);
_tprintf_s(TEXT("ERROR: Cannot map %s. CODE: 0x%08X\n"),
pSolution0->GetMainAppName().c_str(),
ErrorCode);
goto ON_tmain_ERROR;
}
if (!pSolution0->FindPatchOffset()) {
_tprintf_s(TEXT("@%s LINE: %u\n"), TEXT(__FUNCTION__), __LINE__);
_tprintf_s(TEXT("ERROR: Cannot find RSA public key in %s.\n"),
pSolution0->GetMainAppName().c_str());
goto ON_tmain_ERROR;
}
try {
if (nkg::IsValidDirectoryPath(NavInstallPath.c_str()) == false) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Navicat installation path doesn't point to a directory."))
.AddHint(TEXT("Are you sure the path you specified is correct?"))
.AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
}
if (pSolution1) {
ErrorCode = pSolution1->MapFile();
if (ErrorCode != ERROR_SUCCESS) {
REPORT_ERROR_WITH_CODE("ERROR: Cannot map libcc.dll.", ErrorCode);
goto ON_tmain_ERROR;
}
if (!pSolution1->FindPatchOffset()) {
PRINT_MESSAGE("MESSAGE: Cannot find RSA public key in libcc.dll. Solution1 will be omitted.");
delete pSolution1;
pSolution1 = nullptr;
if (RsaPrivateKeyPath.empty() == false && nkg::IsValidFilePath(RsaPrivateKeyPath.c_str()) == false) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("RSA key file path doesn't point to a file."))
.AddHint(TEXT("Are you sure the path you specified is correct?"))
.AddHint(std::xstring::format(TEXT("The path you specified: %s"), RsaPrivateKeyPath.c_str()));
}
while (NavInstallPath.back() == TEXT('\\') || NavInstallPath.back() == TEXT('/')) {
NavInstallPath.pop_back();
}
NavInstallPath.push_back(nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\'));
nkg::RSACipher Cipher;
std::xstring MainExePath;
ResourceOwned hMainExe(FileHandleTraits{});
ResourceOwned hMainExeMapping(GenericHandleTraits{});
ResourceOwned lpMainExeMapping(MapViewHandleTraits{});
ResourceOwned lpMainExeInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
std::xstring LibccDllPath;
ResourceOwned hLibccDll(FileHandleTraits{});
ResourceOwned hLibccDllMapping(GenericHandleTraits{});
ResourceOwned lpLibccDllMapping(MapViewHandleTraits{});
ResourceOwned lpLibccDllInterpreter(CppObjectTraits<nkg::ImageInterpreter>{});
ResourceOwned lpSolution0(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution1(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution2(CppObjectTraits<nkg::PatchSolution>{});
ResourceOwned lpSolution3(CppObjectTraits<nkg::PatchSolution>{});
//
// Open main application
//
do {
MainExePath = NavInstallPath + TEXT("Navicat.exe");
hMainExe.TakeOver(
CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hMainExe.IsValid()) {
LOG_SUCCESS(0, "Try to open Navicat.exe ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open Navicat.exe ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Navicat.exe"));
}
MainExePath = NavInstallPath + TEXT("Modeler.exe");
hMainExe.TakeOver(
CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hMainExe.IsValid()) {
LOG_SUCCESS(0, "Try to open Modeler.exe ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open Modeler.exe ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Modeler.exe"));
}
MainExePath = NavInstallPath + TEXT("Rviewer.exe");
hMainExe.TakeOver(
CreateFile(MainExePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hMainExe.IsValid()) {
LOG_SUCCESS(0, "Try to open Rviewer.exe ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open Rviewer.exe ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open Rviewer.exe"));
}
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("Main application is not found."))
.AddHint(TEXT("Are you sure you specified a valid Navicat installation path?"))
.AddHint(std::xstring::format(TEXT("The path you specified: %s"), NavInstallPath.c_str()));
} while (false);
//
// Open libcc.dll, if have
//
do {
LibccDllPath = NavInstallPath + TEXT("libcc.dll");
hLibccDll.TakeOver(
CreateFile(LibccDllPath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL)
);
if (hLibccDll.IsValid()) {
LOG_SUCCESS(0, "Try to open libcc.dll ... Ok!");
break;
} else if (GetLastError() == ERROR_FILE_NOT_FOUND) {
LOG_FAILURE(0, "Try to open libcc.dll ... Not found!");
} else {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("Failed to open libcc.dll"));
}
} while (false);
_putts(TEXT(""));
//
// Map main application
//
hMainExeMapping.TakeOver(CreateFileMapping(hMainExe, NULL, PAGE_READWRITE, 0, 0, NULL));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
}
lpMainExeMapping.TakeOver(MapViewOfFile(hMainExeMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
}
lpMainExeInterpreter.TakeOver(
new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpMainExeMapping))
);
lpSolution0.TakeOver(new nkg::PatchSolution0(lpMainExeInterpreter));
//
// Map libcc.dll, if have
//
if (hLibccDll.IsValid()) {
hLibccDllMapping.TakeOver(CreateFileMapping(hLibccDll, NULL, PAGE_READWRITE, 0, 0, NULL));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("CreateFileMapping failed."));
}
lpLibccDllMapping.TakeOver(MapViewOfFile(hLibccDllMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (hMainExeMapping.IsValid() == false) {
throw nkg::Win32Error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), TEXT("MapViewOfFile failed."));
}
lpLibccDllInterpreter.TakeOver(
new nkg::ImageInterpreter(nkg::ImageInterpreter::ParseImage(lpLibccDllMapping))
);
lpSolution1.TakeOver(new nkg::PatchSolution1(lpLibccDllInterpreter));
lpSolution2.TakeOver(new nkg::PatchSolution2(lpLibccDllInterpreter));
lpSolution3.TakeOver(new nkg::PatchSolution3(lpLibccDllInterpreter));
}
//
// Finding patch offsets
//
if (lpSolution0->FindPatchOffset() == false) {
lpSolution0.Release();
}
if (lpSolution1.IsValid() && lpSolution1->FindPatchOffset() == false) {
lpSolution1.Release();
}
if (lpSolution2.IsValid() && lpSolution2->FindPatchOffset() == false) {
lpSolution2.Release();
}
if (lpSolution3.IsValid() && lpSolution3->FindPatchOffset() == false) {
lpSolution3.Release();
}
_putts(TEXT(""));
//
// decide which solutions will be applied
//
SelectPatchSolutions(lpSolution0, lpSolution1, lpSolution2, lpSolution3);
if (lpSolution0.IsValid() == false && lpSolution1.IsValid() == false && lpSolution2.IsValid() == false && lpSolution3.IsValid() == false) {
throw nkg::Exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), TEXT("No patch applied. Patch abort!"))
.AddHint(TEXT("Are you sure your Navicat has not been patched/modified before?"));
}
_putts(TEXT(""));
//
// detecting backups
//
if (lpSolution0.IsValid()) {
NavicatBackupDetect(MainExePath);
}
if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) {
NavicatBackupDetect(LibccDllPath);
}
//
// Loading key
//
LoadKey(Cipher, RsaPrivateKeyPath, lpSolution0, lpSolution1, lpSolution2, lpSolution3);
if (bDryRun == false) {
//
// Saving private key if not given
//
if (RsaPrivateKeyPath.empty()) {
Cipher.ExportKeyToFile<nkg::RSAKeyType::PrivateKey, nkg::RSAKeyFormat::PEM>(std::xstring{ std::xstring_extension{}, "RegPrivateKey.pem" });
}
//
// Making backups
//
if (lpSolution0.IsValid()) {
NavicatBackupMake(MainExePath);
}
if (lpSolution1.IsValid() || lpSolution2.IsValid() || lpSolution3.IsValid()) {
NavicatBackupMake(LibccDllPath);
}
//
// Making patch. No way to go back here :-)
//
if (lpSolution0.IsValid()) {
lpSolution0->MakePatch(Cipher);
}
if (lpSolution1.IsValid()) {
lpSolution1->MakePatch(Cipher);
}
if (lpSolution2.IsValid()) {
lpSolution2->MakePatch(Cipher);
}
if (lpSolution3.IsValid()) {
lpSolution3->MakePatch(Cipher);
}
if (RsaPrivateKeyPath.empty()) {
LOG_HINT(
0,
"New RSA-2048 private key has been saved to\n%s%cRegPrivateKey.pem",
nkg::GetCurrentWorkingDirectory().c_str(),
nkg::IsWineEnvironment() ? TEXT('/') : TEXT('\\')
);
_putts(TEXT(""));
}
_putts(TEXT("*******************************************************"));
_putts(TEXT("* PATCH HAS BEEN DONE SUCCESSFULLY! *"));
_putts(TEXT("* HAVE FUN AND ENJOY~ *"));
_putts(TEXT("*******************************************************"));
} else {
_putts(TEXT("*******************************************************"));
_putts(TEXT("* DRY-RUN MODE ENABLE! *"));
_putts(TEXT("* NO PATCH WILL BE APPLIED! *"));
_putts(TEXT("*******************************************************"));
}
return 0;
} catch (nkg::Exception& e) {
LOG_FAILURE(0, "%s:%zu ->", e.File(), e.Line());
LOG_FAILURE(4, "%s", e.Message());
if (e.HasErrorCode()) {
LOG_HINT(4, "%s (0x%zx)", e.ErrorString(), e.ErrorCode());
}
for (auto& Hint : e.Hints()) {
LOG_HINT(4, "Hint: %s", Hint.c_str());
}
return -1;
}
}
}
LoadingKey:
PRINT_MESSAGE("");
if (!LoadKey(cipher, argc == 3 ? argv[2] : nullptr, pSolution0, pSolution1))
goto ON_tmain_ERROR;
BackupFiles:
PRINT_MESSAGE("");
ErrorCode = pSolution0->BackupFile();
if (ErrorCode == ERROR_SUCCESS) {
_tprintf_s(TEXT("MESSAGE: %s has been backed up successfully.\n"),
pSolution0->GetMainAppName().c_str());
} else if (ErrorCode == ERROR_ACCESS_DENIED) {
_tprintf_s(TEXT("ERROR: Cannot back up %s for ERROR_ACCESS_DENIED.\n"),
pSolution0->GetMainAppName().c_str());
_tprintf_s(TEXT("Please re-run with Administrator privilege.\n"));
goto ON_tmain_ERROR;
} else if (ErrorCode == ERROR_FILE_EXISTS) {
_tprintf_s(TEXT("ERROR: The backup of %s has been found.\n"),
pSolution0->GetMainAppName().c_str());
_tprintf_s(TEXT("Please remove %s.backup in Navicat installation path if you're sure %s has not been patched.\n"),
pSolution0->GetMainAppName().c_str(),
pSolution0->GetMainAppName().c_str());
_tprintf_s(TEXT("Otherwise please restore %s by %s.backup and remove %s.backup then try again.\n"),
pSolution0->GetMainAppName().c_str(),
pSolution0->GetMainAppName().c_str(),
pSolution0->GetMainAppName().c_str());
goto ON_tmain_ERROR;
} else {
_tprintf_s(TEXT("ERROR: Cannot back up %s. CODE: 0x%08X\n"),
pSolution0->GetMainAppName().c_str(),
ErrorCode);
goto ON_tmain_ERROR;
}
if (pSolution1) {
ErrorCode = pSolution1->BackupFile();
if (ErrorCode == ERROR_SUCCESS) {
PRINT_MESSAGE("MESSAGE: libcc.dll has been backed up successfully.");
} else if (ErrorCode == ERROR_ACCESS_DENIED) {
PRINT_MESSAGE("ERROR: Cannot back up libcc.dll for ERROR_ACCESS_DENIED.");
PRINT_MESSAGE("Please re-run with Administrator privilege.");
goto ON_tmain_ERROR;
} else if (ErrorCode == ERROR_FILE_EXISTS) {
PRINT_MESSAGE("ERROR: The backup of libcc.dll has been found.");
PRINT_MESSAGE("Please remove libcc.dll.backup in Navicat installation path if you're sure libcc.dll has not been patched.");
PRINT_MESSAGE("Otherwise please restore libcc.dll by libcc.dll.backup and remove libcc.dll.backup then try again.");
goto ON_tmain_ERROR;
} else {
REPORT_ERROR_WITH_CODE("ERROR: Cannot back up libcc.dll.", ErrorCode);
goto ON_tmain_ERROR;
}
}
MakingPatch:
PRINT_MESSAGE("");
if (!pSolution0->MakePatch(cipher))
goto ON_tmain_ERROR;
if (pSolution1 && !pSolution1->MakePatch(cipher))
goto ON_tmain_ERROR;
PRINT_MESSAGE("Solution0 has been done successfully.");
if (pSolution1)
PRINT_MESSAGE("Solution1 has been done successfully.");
ON_tmain_ERROR:
delete pSolution1;
delete pSolution0;
delete cipher;
return 0;
}
-170
View File
@@ -1,170 +0,0 @@
#pragma once
#include <tchar.h>
#include <windows.h>
#include <string>
#include "RSACipher.hpp"
#ifdef UNICODE
namespace std { typedef wstring Tstring; }
#else
namespace std { typedef string Tstring; }
#endif
namespace Helper {
std::string EncryptPublicKey(const std::string& PublicKeyString);
bool ConvertToUTF8(LPCSTR from, std::string& to);
bool ConvertToUTF8(LPCWSTR from, std::string& to);
bool ConvertToUTF8(std::string& str);
void ErrorReport(LPCTSTR at, UINT line, LPCTSTR msg);
void ErrorReport(LPCTSTR at, UINT line, LPCTSTR msg, DWORD err_code);
void PrintMemory(const void* a, const void* b, const void* base);
}
#define REPORT_ERROR(msg) Helper::ErrorReport(TEXT(__FUNCTION__), __LINE__, TEXT(msg))
#define REPORT_ERROR_WITH_CODE(msg, err_code) Helper::ErrorReport(TEXT(__FUNCTION__), __LINE__, TEXT(msg), (err_code))
#define PRINT_MESSAGE(msg) _tprintf_s(TEXT("%s\n"), TEXT(msg))
#define PRINT_LPCTSTR(msg) _tprintf_s(TEXT("%s\n"), (msg))
#define PRINT_LPCSTR(msg) printf_s("%s\n", (msg))
#define PRINT_LPCWSTR(msg) wprintf_s(L"%s\n", (msg))
namespace Patcher {
// Solution0 will replace the RSA public key stored in main application.
class Solution0 {
private:
static const char Keyword[461];
static constexpr int KeywordLength = 460;
std::Tstring InstallationPath;
std::Tstring MainAppName;
HANDLE MainAppHandle;
HANDLE MainAppMappingHandle;
PVOID MainAppMappingView;
off_t PatchOffset;
public:
Solution0() : InstallationPath(),
MainAppName(),
MainAppHandle(INVALID_HANDLE_VALUE),
MainAppMappingHandle(NULL),
MainAppMappingView(nullptr),
PatchOffset(-1) {}
BOOL SetPath(const std::Tstring& Path);
// Solution0 does not have any requirements for RSA-2048 key
BOOL CheckKey(RSACipher* cipher) const;
// Return error code
// It may return
// ERROR_SUCCESS (target has been set successfully)
// ERROR_FILE_NOT_FOUND (try another name)
// ERROR_ACCESS_DENIED (you need Administrator privilege)
// ...
DWORD TryFile(const std::Tstring& MainAppName);
// Return error code
// It may return
// ERROR_SUCCESS (target has been mapped successfully)
// ...
DWORD MapFile();
// Return TRUE if found, other return FALSE
BOOL FindPatchOffset();
// Return error code
// It may return
// ERROR_SUCCESS (file has been backed up successfully)
// ERROR_FILE_EXISTS (you should remove backup file first)
// ERROR_ACCESS_DENIED (you need Administrator privilege)
// ...
DWORD BackupFile();
// Make a patch based on RSA private key
// Return TRUE if success, otherwise return FALSE
BOOL MakePatch(RSACipher* cipher);
// Return error code
// Return ERROR_SUCCESS if success
// DWORD GetMainAppVersion(LPDWORD lpMajorVer, LPDWORD lpMinorVer);
const std::Tstring& GetMainAppName();
// Close handle returned by CreateFile with a implicit call towards ReleaseMap
void ReleaseFile();
// Unmap view returned by MapViewOfFile and
// close handle returned by CreateFileMapping
void ReleaseMap();
~Solution0();
};
// Solution0 will replace the RSA public key stored in libcc.dll
class Solution1 {
private:
static const char* Keywords[5];
static const int KeywordsLength[5];
std::Tstring InstallationPath;
std::Tstring LibccName;
HANDLE LibccHandle;
HANDLE LibccMappingHandle;
PVOID LibccMappingView;
off_t PatchOffsets[5];
public:
Solution1() : InstallationPath(),
LibccName(),
LibccHandle(INVALID_HANDLE_VALUE),
LibccMappingHandle(NULL),
LibccMappingView(nullptr),
PatchOffsets{-1, -1, -1, -1, -1} {}
BOOL SetPath(const std::Tstring& Path);
// Solution0 does not have any requirements for RSA-2048 key
BOOL CheckKey(RSACipher* cipher) const;
// Return error code
// It may return
// ERROR_SUCCESS (target has been set successfully)
// ERROR_FILE_NOT_FOUND (try another name)
// ERROR_ACCESS_DENIED (you need Administrator privilege)
// ...
DWORD TryFile(const std::Tstring& MainAppName);
// Return error code
// It may return
// ERROR_SUCCESS (target has been mapped successfully)
// ...
DWORD MapFile();
// Return TRUE if found, other return FALSE
BOOL FindPatchOffset();
// Return error code
// It may return
// ERROR_SUCCESS (file has been backed up successfully)
// ERROR_FILE_EXISTS (you should remove backup file first)
// ERROR_ACCESS_DENIED (you need Administrator privilege)
// ...
DWORD BackupFile();
// Make a patch based on RSA private key
// Return TRUE if success, otherwise return FALSE
BOOL MakePatch(RSACipher* cipher);
// Close handle returned by CreateFile with a implicit call towards ReleaseMap
void ReleaseFile();
// Unmap view returned by MapViewOfFile and
// close handle returned by CreateFileMapping
void ReleaseMap();
~Solution1();
};
}
+65 -41
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<?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>
@@ -19,42 +19,50 @@
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{30BE8CAB-6137-4441-9F64-599D0A6EEA0C}</ProjectGuid>
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{7EE03EF3-D58D-4B53-913D-4A4DC8A29E34}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>navicatpatcher</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
<VcpkgTriplet Condition="'$(Platform)'=='Win32'">x86-windows-static</VcpkgTriplet>
<VcpkgTriplet Condition="'$(Platform)'=='x64'">x64-windows-static</VcpkgTriplet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v140_xp</PlatformToolset>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<SpectreMitigation>false</SpectreMitigation>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
<Import Project="..\common\common.vcxitems" Label="Shared" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
@@ -71,38 +79,33 @@
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(SolutionDir)openssl-lib\include;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib;$(LibraryPath)</LibraryPath>
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<IncludePath>$(SolutionDir)openssl-lib\include64;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib64;$(LibraryPath)</LibraryPath>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>$(SolutionDir)openssl-lib\include;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib;$(LibraryPath)</LibraryPath>
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<IncludePath>$(SolutionDir)openssl-lib\include64;$(IncludePath)</IncludePath>
<LibraryPath>$(SolutionDir)openssl-lib\lib64;$(LibraryPath)</LibraryPath>
<IntDir>$(SolutionDir)obj\$(Platform)-$(Configuration)\$(ProjectName)\</IntDir>
<OutDir>$(SolutionDir)bin\$(Platform)-$(Configuration)\</OutDir>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -111,14 +114,13 @@
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -128,15 +130,14 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -148,15 +149,14 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalOptions>/std:c++latest</AdditionalOptions>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -166,15 +166,39 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Helper.cpp" />
<ClCompile Include="Solution0.cpp" />
<ClCompile Include="Solution1.cpp" />
<ClCompile Include="CapstoneDisassembler.cpp" />
<ClCompile Include="ImageInterpreter.cpp" />
<ClCompile Include="Misc.cpp" />
<ClCompile Include="PatchSolution0.cpp" />
<ClCompile Include="PatchSolution1.cpp" />
<ClCompile Include="PatchSolution2-generic.cpp" />
<ClCompile Include="PatchSolution2-i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution2-amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution3-amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="PatchSolution3-generic.cpp" />
<ClCompile Include="PatchSolution3-i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="_tmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="def.hpp" />
<ClInclude Include="CapstoneDisassembler.hpp" />
<ClInclude Include="ExceptionCapstone.hpp" />
<ClInclude Include="ImageInterpreter.hpp" />
<ClInclude Include="Misc.hpp" />
<ClInclude Include="NavicatCrypto.hpp" />
<ClInclude Include="RSACipher.hpp" />
<ClInclude Include="PatchSolutions.hpp" />
<ClInclude Include="ResourceTraitsCapstone.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
+46 -10
View File
@@ -7,7 +7,7 @@
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
@@ -18,25 +18,61 @@
<ClCompile Include="_tmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Solution0.cpp">
<ClCompile Include="ImageInterpreter.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Solution1.cpp">
<ClCompile Include="PatchSolution0.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Helper.cpp">
<ClCompile Include="PatchSolution1.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution2-i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution2-amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution3-amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution3-i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Misc.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution2-generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="PatchSolution3-generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CapstoneDisassembler.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="def.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="RSACipher.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="NavicatCrypto.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ImageInterpreter.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="CapstoneDisassembler.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ResourceTraitsCapstone.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ExceptionCapstone.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="PatchSolutions.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Misc.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>
@@ -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>
-2
View File
@@ -1,2 +0,0 @@
Please https://www.openssl.org/community/thanks.html for the current
acknowledgements.
-21
View File
@@ -1,21 +0,0 @@
Andy Polyakov
Ben Laurie
Bodo Möller
Emilia Käsper
Eric Young
Geoff Thorpe
Holger Reif
Kurt Roeckx
Lutz Jänicke
Mark J. Cox
Matt Caswell
Nils Larsch
Paul C. Sutton
Ralf S. Engelschall
Rich Salz
Richard Levitte
Stephen Henson
Steve Marquess
Tim Hudson
Ulf Möller
Viktor Dukhovni
File diff suppressed because it is too large Load Diff
-54
View File
@@ -1,54 +0,0 @@
HOW TO CONTRIBUTE PATCHES TO OpenSSL
------------------------------------
(Please visit https://www.openssl.org/community/getting-started.html for
other ideas about how to contribute.)
Development is coordinated on the openssl-dev mailing list (see the
above link or https://mta.openssl.org for information on subscribing).
If you are unsure as to whether a feature will be useful for the general
OpenSSL community you might want to discuss it on the openssl-dev mailing
list first. Someone may be already working on the same thing or there
may be a good reason as to why that feature isn't implemented.
To submit a patch, make a pull request on GitHub. If you think the patch
could use feedback from the community, please start a thread on openssl-dev
to discuss it.
Having addressed the following items before the PR will help make the
acceptance and review process faster:
1. Anything other than trivial contributions will require a contributor
licensing agreement, giving us permission to use your code. See
https://www.openssl.org/policies/cla.html for details.
2. All source files should start with the following text (with
appropriate comment characters at the start of each line and the
year(s) updated):
Copyright 20xx-20yy The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
https://www.openssl.org/source/license.html
3. Patches should be as current as possible; expect to have to rebase
often. We do not accept merge commits; You will be asked to remove
them before a patch is considered acceptable.
4. Patches should follow our coding style (see
https://www.openssl.org/policies/codingstyle.html) and compile without
warnings. Where gcc or clang is available you should use the
--strict-warnings Configure option. OpenSSL compiles on many varied
platforms: try to ensure you only use portable features.
Clean builds via Travis and AppVeyor are expected, and done whenever
a PR is created or updated.
5. When at all possible, patches should include tests. These can
either be added to an existing test, or completely new. Please see
test/README for information on the test framework.
6. New features or changed functionality must include
documentation. Please look at the "pod" files in doc/apps, doc/crypto
and doc/ssl for examples of our style.
-2
View File
@@ -1,2 +0,0 @@
The FAQ is now maintained on the web:
https://www.openssl.org/docs/faq.html
-125
View File
@@ -1,125 +0,0 @@
LICENSE ISSUES
==============
The OpenSSL toolkit stays under a double license, i.e. both the conditions of
the OpenSSL License and the original SSLeay license apply to the toolkit.
See below for the actual license texts.
OpenSSL License
---------------
/* ====================================================================
* Copyright (c) 1998-2017 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
Original SSLeay License
-----------------------
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
-856
View File
@@ -1,856 +0,0 @@
NEWS
====
This file gives a brief overview of the major changes between each OpenSSL
release. For more details please read the CHANGES file.
Major changes between OpenSSL 1.1.0e and OpenSSL 1.1.0f [25 May 2017]
o config now recognises 64-bit mingw and chooses mingw64 instead of mingw
Major changes between OpenSSL 1.1.0d and OpenSSL 1.1.0e [16 Feb 2017]
o Encrypt-Then-Mac renegotiation crash (CVE-2017-3733)
Major changes between OpenSSL 1.1.0c and OpenSSL 1.1.0d [26 Jan 2017]
o Truncated packet could crash via OOB read (CVE-2017-3731)
o Bad (EC)DHE parameters cause a client crash (CVE-2017-3730)
o BN_mod_exp may produce incorrect results on x86_64 (CVE-2017-3732)
Major changes between OpenSSL 1.1.0b and OpenSSL 1.1.0c [10 Nov 2016]
o ChaCha20/Poly1305 heap-buffer-overflow (CVE-2016-7054)
o CMS Null dereference (CVE-2016-7053)
o Montgomery multiplication may produce incorrect results (CVE-2016-7055)
Major changes between OpenSSL 1.1.0a and OpenSSL 1.1.0b [26 Sep 2016]
o Fix Use After Free for large message sizes (CVE-2016-6309)
Major changes between OpenSSL 1.1.0 and OpenSSL 1.1.0a [22 Sep 2016]
o OCSP Status Request extension unbounded memory growth (CVE-2016-6304)
o SSL_peek() hang on empty record (CVE-2016-6305)
o Excessive allocation of memory in tls_get_message_header()
(CVE-2016-6307)
o Excessive allocation of memory in dtls1_preprocess_fragment()
(CVE-2016-6308)
Major changes between OpenSSL 1.0.2h and OpenSSL 1.1.0 [25 Aug 2016]
o Copyright text was shrunk to a boilerplate that points to the license
o "shared" builds are now the default when possible
o Added support for "pipelining"
o Added the AFALG engine
o New threading API implemented
o Support for ChaCha20 and Poly1305 added to libcrypto and libssl
o Support for extended master secret
o CCM ciphersuites
o Reworked test suite, now based on perl, Test::Harness and Test::More
o *Most* libcrypto and libssl public structures were made opaque,
including:
BIGNUM and associated types, EC_KEY and EC_KEY_METHOD,
DH and DH_METHOD, DSA and DSA_METHOD, RSA and RSA_METHOD,
BIO and BIO_METHOD, EVP_MD_CTX, EVP_MD, EVP_CIPHER_CTX,
EVP_CIPHER, EVP_PKEY and associated types, HMAC_CTX,
X509, X509_CRL, X509_OBJECT, X509_STORE_CTX, X509_STORE,
X509_LOOKUP, X509_LOOKUP_METHOD
o libssl internal structures made opaque
o SSLv2 support removed
o Kerberos ciphersuite support removed
o RC4 removed from DEFAULT ciphersuites in libssl
o 40 and 56 bit cipher support removed from libssl
o All public header files moved to include/openssl, no more symlinking
o SSL/TLS state machine, version negotiation and record layer rewritten
o EC revision: now operations use new EC_KEY_METHOD.
o Support for OCB mode added to libcrypto
o Support for asynchronous crypto operations added to libcrypto and libssl
o Deprecated interfaces can now be disabled at build time either
relative to the latest release via the "no-deprecated" Configure
argument, or via the "--api=1.1.0|1.0.0|0.9.8" option.
o Application software can be compiled with -DOPENSSL_API_COMPAT=version
to ensure that features deprecated in that version are not exposed.
o Support for RFC6698/RFC7671 DANE TLSA peer authentication
o Change of Configure to use --prefix as the main installation
directory location rather than --openssldir. The latter becomes
the directory for certs, private key and openssl.cnf exclusively.
o Reworked BIO networking library, with full support for IPv6.
o New "unified" build system
o New security levels
o Support for scrypt algorithm
o Support for X25519
o Extended SSL_CONF support using configuration files
o KDF algorithm support. Implement TLS PRF as a KDF.
o Support for Certificate Transparency
o HKDF support.
Major changes between OpenSSL 1.0.2g and OpenSSL 1.0.2h [3 May 2016]
o Prevent padding oracle in AES-NI CBC MAC check (CVE-2016-2107)
o Fix EVP_EncodeUpdate overflow (CVE-2016-2105)
o Fix EVP_EncryptUpdate overflow (CVE-2016-2106)
o Prevent ASN.1 BIO excessive memory allocation (CVE-2016-2109)
o EBCDIC overread (CVE-2016-2176)
o Modify behavior of ALPN to invoke callback after SNI/servername
callback, such that updates to the SSL_CTX affect ALPN.
o Remove LOW from the DEFAULT cipher list. This removes singles DES from
the default.
o Only remove the SSLv2 methods with the no-ssl2-method option.
Major changes between OpenSSL 1.0.2f and OpenSSL 1.0.2g [1 Mar 2016]
o Disable weak ciphers in SSLv3 and up in default builds of OpenSSL.
o Disable SSLv2 default build, default negotiation and weak ciphers
(CVE-2016-0800)
o Fix a double-free in DSA code (CVE-2016-0705)
o Disable SRP fake user seed to address a server memory leak
(CVE-2016-0798)
o Fix BN_hex2bn/BN_dec2bn NULL pointer deref/heap corruption
(CVE-2016-0797)
o Fix memory issues in BIO_*printf functions (CVE-2016-0799)
o Fix side channel attack on modular exponentiation (CVE-2016-0702)
Major changes between OpenSSL 1.0.2e and OpenSSL 1.0.2f [28 Jan 2016]
o DH small subgroups (CVE-2016-0701)
o SSLv2 doesn't block disabled ciphers (CVE-2015-3197)
Major changes between OpenSSL 1.0.2d and OpenSSL 1.0.2e [3 Dec 2015]
o BN_mod_exp may produce incorrect results on x86_64 (CVE-2015-3193)
o Certificate verify crash with missing PSS parameter (CVE-2015-3194)
o X509_ATTRIBUTE memory leak (CVE-2015-3195)
o Rewrite EVP_DecodeUpdate (base64 decoding) to fix several bugs
o In DSA_generate_parameters_ex, if the provided seed is too short,
return an error
Major changes between OpenSSL 1.0.2c and OpenSSL 1.0.2d [9 Jul 2015]
o Alternate chains certificate forgery (CVE-2015-1793)
o Race condition handling PSK identify hint (CVE-2015-3196)
Major changes between OpenSSL 1.0.2b and OpenSSL 1.0.2c [12 Jun 2015]
o Fix HMAC ABI incompatibility
Major changes between OpenSSL 1.0.2a and OpenSSL 1.0.2b [11 Jun 2015]
o Malformed ECParameters causes infinite loop (CVE-2015-1788)
o Exploitable out-of-bounds read in X509_cmp_time (CVE-2015-1789)
o PKCS7 crash with missing EnvelopedContent (CVE-2015-1790)
o CMS verify infinite loop with unknown hash function (CVE-2015-1792)
o Race condition handling NewSessionTicket (CVE-2015-1791)
Major changes between OpenSSL 1.0.2 and OpenSSL 1.0.2a [19 Mar 2015]
o OpenSSL 1.0.2 ClientHello sigalgs DoS fix (CVE-2015-0291)
o Multiblock corrupted pointer fix (CVE-2015-0290)
o Segmentation fault in DTLSv1_listen fix (CVE-2015-0207)
o Segmentation fault in ASN1_TYPE_cmp fix (CVE-2015-0286)
o Segmentation fault for invalid PSS parameters fix (CVE-2015-0208)
o ASN.1 structure reuse memory corruption fix (CVE-2015-0287)
o PKCS7 NULL pointer dereferences fix (CVE-2015-0289)
o DoS via reachable assert in SSLv2 servers fix (CVE-2015-0293)
o Empty CKE with client auth and DHE fix (CVE-2015-1787)
o Handshake with unseeded PRNG fix (CVE-2015-0285)
o Use After Free following d2i_ECPrivatekey error fix (CVE-2015-0209)
o X509_to_X509_REQ NULL pointer deref fix (CVE-2015-0288)
o Removed the export ciphers from the DEFAULT ciphers
Major changes between OpenSSL 1.0.1l and OpenSSL 1.0.2 [22 Jan 2015]:
o Suite B support for TLS 1.2 and DTLS 1.2
o Support for DTLS 1.2
o TLS automatic EC curve selection.
o API to set TLS supported signature algorithms and curves
o SSL_CONF configuration API.
o TLS Brainpool support.
o ALPN support.
o CMS support for RSA-PSS, RSA-OAEP, ECDH and X9.42 DH.
Major changes between OpenSSL 1.0.1k and OpenSSL 1.0.1l [15 Jan 2015]
o Build fixes for the Windows and OpenVMS platforms
Major changes between OpenSSL 1.0.1j and OpenSSL 1.0.1k [8 Jan 2015]
o Fix for CVE-2014-3571
o Fix for CVE-2015-0206
o Fix for CVE-2014-3569
o Fix for CVE-2014-3572
o Fix for CVE-2015-0204
o Fix for CVE-2015-0205
o Fix for CVE-2014-8275
o Fix for CVE-2014-3570
Major changes between OpenSSL 1.0.1i and OpenSSL 1.0.1j [15 Oct 2014]
o Fix for CVE-2014-3513
o Fix for CVE-2014-3567
o Mitigation for CVE-2014-3566 (SSL protocol vulnerability)
o Fix for CVE-2014-3568
Major changes between OpenSSL 1.0.1h and OpenSSL 1.0.1i [6 Aug 2014]
o Fix for CVE-2014-3512
o Fix for CVE-2014-3511
o Fix for CVE-2014-3510
o Fix for CVE-2014-3507
o Fix for CVE-2014-3506
o Fix for CVE-2014-3505
o Fix for CVE-2014-3509
o Fix for CVE-2014-5139
o Fix for CVE-2014-3508
Major changes between OpenSSL 1.0.1g and OpenSSL 1.0.1h [5 Jun 2014]
o Fix for CVE-2014-0224
o Fix for CVE-2014-0221
o Fix for CVE-2014-0198
o Fix for CVE-2014-0195
o Fix for CVE-2014-3470
o Fix for CVE-2010-5298
Major changes between OpenSSL 1.0.1f and OpenSSL 1.0.1g [7 Apr 2014]
o Fix for CVE-2014-0160
o Add TLS padding extension workaround for broken servers.
o Fix for CVE-2014-0076
Major changes between OpenSSL 1.0.1e and OpenSSL 1.0.1f [6 Jan 2014]
o Don't include gmt_unix_time in TLS server and client random values
o Fix for TLS record tampering bug CVE-2013-4353
o Fix for TLS version checking bug CVE-2013-6449
o Fix for DTLS retransmission bug CVE-2013-6450
Major changes between OpenSSL 1.0.1d and OpenSSL 1.0.1e [11 Feb 2013]:
o Corrected fix for CVE-2013-0169
Major changes between OpenSSL 1.0.1c and OpenSSL 1.0.1d [4 Feb 2013]:
o Fix renegotiation in TLS 1.1, 1.2 by using the correct TLS version.
o Include the fips configuration module.
o Fix OCSP bad key DoS attack CVE-2013-0166
o Fix for SSL/TLS/DTLS CBC plaintext recovery attack CVE-2013-0169
o Fix for TLS AESNI record handling flaw CVE-2012-2686
Major changes between OpenSSL 1.0.1b and OpenSSL 1.0.1c [10 May 2012]:
o Fix TLS/DTLS record length checking bug CVE-2012-2333
o Don't attempt to use non-FIPS composite ciphers in FIPS mode.
Major changes between OpenSSL 1.0.1a and OpenSSL 1.0.1b [26 Apr 2012]:
o Fix compilation error on non-x86 platforms.
o Make FIPS capable OpenSSL ciphers work in non-FIPS mode.
o Fix SSL_OP_NO_TLSv1_1 clash with SSL_OP_ALL in OpenSSL 1.0.0
Major changes between OpenSSL 1.0.1 and OpenSSL 1.0.1a [19 Apr 2012]:
o Fix for ASN1 overflow bug CVE-2012-2110
o Workarounds for some servers that hang on long client hellos.
o Fix SEGV in AES code.
Major changes between OpenSSL 1.0.0h and OpenSSL 1.0.1 [14 Mar 2012]:
o TLS/DTLS heartbeat support.
o SCTP support.
o RFC 5705 TLS key material exporter.
o RFC 5764 DTLS-SRTP negotiation.
o Next Protocol Negotiation.
o PSS signatures in certificates, requests and CRLs.
o Support for password based recipient info for CMS.
o Support TLS v1.2 and TLS v1.1.
o Preliminary FIPS capability for unvalidated 2.0 FIPS module.
o SRP support.
Major changes between OpenSSL 1.0.0g and OpenSSL 1.0.0h [12 Mar 2012]:
o Fix for CMS/PKCS#7 MMA CVE-2012-0884
o Corrected fix for CVE-2011-4619
o Various DTLS fixes.
Major changes between OpenSSL 1.0.0f and OpenSSL 1.0.0g [18 Jan 2012]:
o Fix for DTLS DoS issue CVE-2012-0050
Major changes between OpenSSL 1.0.0e and OpenSSL 1.0.0f [4 Jan 2012]:
o Fix for DTLS plaintext recovery attack CVE-2011-4108
o Clear block padding bytes of SSL 3.0 records CVE-2011-4576
o Only allow one SGC handshake restart for SSL/TLS CVE-2011-4619
o Check parameters are not NULL in GOST ENGINE CVE-2012-0027
o Check for malformed RFC3779 data CVE-2011-4577
Major changes between OpenSSL 1.0.0d and OpenSSL 1.0.0e [6 Sep 2011]:
o Fix for CRL vulnerability issue CVE-2011-3207
o Fix for ECDH crashes CVE-2011-3210
o Protection against EC timing attacks.
o Support ECDH ciphersuites for certificates using SHA2 algorithms.
o Various DTLS fixes.
Major changes between OpenSSL 1.0.0c and OpenSSL 1.0.0d [8 Feb 2011]:
o Fix for security issue CVE-2011-0014
Major changes between OpenSSL 1.0.0b and OpenSSL 1.0.0c [2 Dec 2010]:
o Fix for security issue CVE-2010-4180
o Fix for CVE-2010-4252
o Fix mishandling of absent EC point format extension.
o Fix various platform compilation issues.
o Corrected fix for security issue CVE-2010-3864.
Major changes between OpenSSL 1.0.0a and OpenSSL 1.0.0b [16 Nov 2010]:
o Fix for security issue CVE-2010-3864.
o Fix for CVE-2010-2939
o Fix WIN32 build system for GOST ENGINE.
Major changes between OpenSSL 1.0.0 and OpenSSL 1.0.0a [1 Jun 2010]:
o Fix for security issue CVE-2010-1633.
o GOST MAC and CFB fixes.
Major changes between OpenSSL 0.9.8n and OpenSSL 1.0.0 [29 Mar 2010]:
o RFC3280 path validation: sufficient to process PKITS tests.
o Integrated support for PVK files and keyblobs.
o Change default private key format to PKCS#8.
o CMS support: able to process all examples in RFC4134
o Streaming ASN1 encode support for PKCS#7 and CMS.
o Multiple signer and signer add support for PKCS#7 and CMS.
o ASN1 printing support.
o Whirlpool hash algorithm added.
o RFC3161 time stamp support.
o New generalised public key API supporting ENGINE based algorithms.
o New generalised public key API utilities.
o New ENGINE supporting GOST algorithms.
o SSL/TLS GOST ciphersuite support.
o PKCS#7 and CMS GOST support.
o RFC4279 PSK ciphersuite support.
o Supported points format extension for ECC ciphersuites.
o ecdsa-with-SHA224/256/384/512 signature types.
o dsa-with-SHA224 and dsa-with-SHA256 signature types.
o Opaque PRF Input TLS extension support.
o Updated time routines to avoid OS limitations.
Major changes between OpenSSL 0.9.8m and OpenSSL 0.9.8n [24 Mar 2010]:
o CFB cipher definition fixes.
o Fix security issues CVE-2010-0740 and CVE-2010-0433.
Major changes between OpenSSL 0.9.8l and OpenSSL 0.9.8m [25 Feb 2010]:
o Cipher definition fixes.
o Workaround for slow RAND_poll() on some WIN32 versions.
o Remove MD2 from algorithm tables.
o SPKAC handling fixes.
o Support for RFC5746 TLS renegotiation extension.
o Compression memory leak fixed.
o Compression session resumption fixed.
o Ticket and SNI coexistence fixes.
o Many fixes to DTLS handling.
Major changes between OpenSSL 0.9.8k and OpenSSL 0.9.8l [5 Nov 2009]:
o Temporary work around for CVE-2009-3555: disable renegotiation.
Major changes between OpenSSL 0.9.8j and OpenSSL 0.9.8k [25 Mar 2009]:
o Fix various build issues.
o Fix security issues (CVE-2009-0590, CVE-2009-0591, CVE-2009-0789)
Major changes between OpenSSL 0.9.8i and OpenSSL 0.9.8j [7 Jan 2009]:
o Fix security issue (CVE-2008-5077)
o Merge FIPS 140-2 branch code.
Major changes between OpenSSL 0.9.8g and OpenSSL 0.9.8h [28 May 2008]:
o CryptoAPI ENGINE support.
o Various precautionary measures.
o Fix for bugs affecting certificate request creation.
o Support for local machine keyset attribute in PKCS#12 files.
Major changes between OpenSSL 0.9.8f and OpenSSL 0.9.8g [19 Oct 2007]:
o Backport of CMS functionality to 0.9.8.
o Fixes for bugs introduced with 0.9.8f.
Major changes between OpenSSL 0.9.8e and OpenSSL 0.9.8f [11 Oct 2007]:
o Add gcc 4.2 support.
o Add support for AES and SSE2 assembly language optimization
for VC++ build.
o Support for RFC4507bis and server name extensions if explicitly
selected at compile time.
o DTLS improvements.
o RFC4507bis support.
o TLS Extensions support.
Major changes between OpenSSL 0.9.8d and OpenSSL 0.9.8e [23 Feb 2007]:
o Various ciphersuite selection fixes.
o RFC3779 support.
Major changes between OpenSSL 0.9.8c and OpenSSL 0.9.8d [28 Sep 2006]:
o Introduce limits to prevent malicious key DoS (CVE-2006-2940)
o Fix security issues (CVE-2006-2937, CVE-2006-3737, CVE-2006-4343)
o Changes to ciphersuite selection algorithm
Major changes between OpenSSL 0.9.8b and OpenSSL 0.9.8c [5 Sep 2006]:
o Fix Daniel Bleichenbacher forged signature attack, CVE-2006-4339
o New cipher Camellia
Major changes between OpenSSL 0.9.8a and OpenSSL 0.9.8b [4 May 2006]:
o Cipher string fixes.
o Fixes for VC++ 2005.
o Updated ECC cipher suite support.
o New functions EVP_CIPHER_CTX_new() and EVP_CIPHER_CTX_free().
o Zlib compression usage fixes.
o Built in dynamic engine compilation support on Win32.
o Fixes auto dynamic engine loading in Win32.
Major changes between OpenSSL 0.9.8 and OpenSSL 0.9.8a [11 Oct 2005]:
o Fix potential SSL 2.0 rollback, CVE-2005-2969
o Extended Windows CE support
Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.8 [5 Jul 2005]:
o Major work on the BIGNUM library for higher efficiency and to
make operations more streamlined and less contradictory. This
is the result of a major audit of the BIGNUM library.
o Addition of BIGNUM functions for fields GF(2^m) and NIST
curves, to support the Elliptic Crypto functions.
o Major work on Elliptic Crypto; ECDH and ECDSA added, including
the use through EVP, X509 and ENGINE.
o New ASN.1 mini-compiler that's usable through the OpenSSL
configuration file.
o Added support for ASN.1 indefinite length constructed encoding.
o New PKCS#12 'medium level' API to manipulate PKCS#12 files.
o Complete rework of shared library construction and linking
programs with shared or static libraries, through a separate
Makefile.shared.
o Rework of the passing of parameters from one Makefile to another.
o Changed ENGINE framework to load dynamic engine modules
automatically from specifically given directories.
o New structure and ASN.1 functions for CertificatePair.
o Changed the ZLIB compression method to be stateful.
o Changed the key-generation and primality testing "progress"
mechanism to take a structure that contains the ticker
function and an argument.
o New engine module: GMP (performs private key exponentiation).
o New engine module: VIA PadLOck ACE extension in VIA C3
Nehemiah processors.
o Added support for IPv6 addresses in certificate extensions.
See RFC 1884, section 2.2.
o Added support for certificate policy mappings, policy
constraints and name constraints.
o Added support for multi-valued AVAs in the OpenSSL
configuration file.
o Added support for multiple certificates with the same subject
in the 'openssl ca' index file.
o Make it possible to create self-signed certificates using
'openssl ca -selfsign'.
o Make it possible to generate a serial number file with
'openssl ca -create_serial'.
o New binary search functions with extended functionality.
o New BUF functions.
o New STORE structure and library to provide an interface to all
sorts of data repositories. Supports storage of public and
private keys, certificates, CRLs, numbers and arbitrary blobs.
This library is unfortunately unfinished and unused within
OpenSSL.
o New control functions for the error stack.
o Changed the PKCS#7 library to support one-pass S/MIME
processing.
o Added the possibility to compile without old deprecated
functionality with the OPENSSL_NO_DEPRECATED macro or the
'no-deprecated' argument to the config and Configure scripts.
o Constification of all ASN.1 conversion functions, and other
affected functions.
o Improved platform support for PowerPC.
o New FIPS 180-2 algorithms (SHA-224, -256, -384 and -512).
o New X509_VERIFY_PARAM structure to support parametrisation
of X.509 path validation.
o Major overhaul of RC4 performance on Intel P4, IA-64 and
AMD64.
o Changed the Configure script to have some algorithms disabled
by default. Those can be explicitly enabled with the new
argument form 'enable-xxx'.
o Change the default digest in 'openssl' commands from MD5 to
SHA-1.
o Added support for DTLS.
o New BIGNUM blinding.
o Added support for the RSA-PSS encryption scheme
o Added support for the RSA X.931 padding.
o Added support for BSD sockets on NetWare.
o Added support for files larger than 2GB.
o Added initial support for Win64.
o Added alternate pkg-config files.
Major changes between OpenSSL 0.9.7l and OpenSSL 0.9.7m [23 Feb 2007]:
o FIPS 1.1.1 module linking.
o Various ciphersuite selection fixes.
Major changes between OpenSSL 0.9.7k and OpenSSL 0.9.7l [28 Sep 2006]:
o Introduce limits to prevent malicious key DoS (CVE-2006-2940)
o Fix security issues (CVE-2006-2937, CVE-2006-3737, CVE-2006-4343)
Major changes between OpenSSL 0.9.7j and OpenSSL 0.9.7k [5 Sep 2006]:
o Fix Daniel Bleichenbacher forged signature attack, CVE-2006-4339
Major changes between OpenSSL 0.9.7i and OpenSSL 0.9.7j [4 May 2006]:
o Visual C++ 2005 fixes.
o Update Windows build system for FIPS.
Major changes between OpenSSL 0.9.7h and OpenSSL 0.9.7i [14 Oct 2005]:
o Give EVP_MAX_MD_SIZE it's old value, except for a FIPS build.
Major changes between OpenSSL 0.9.7g and OpenSSL 0.9.7h [11 Oct 2005]:
o Fix SSL 2.0 Rollback, CVE-2005-2969
o Allow use of fixed-length exponent on DSA signing
o Default fixed-window RSA, DSA, DH private-key operations
Major changes between OpenSSL 0.9.7f and OpenSSL 0.9.7g [11 Apr 2005]:
o More compilation issues fixed.
o Adaptation to more modern Kerberos API.
o Enhanced or corrected configuration for Solaris64, Mingw and Cygwin.
o Enhanced x86_64 assembler BIGNUM module.
o More constification.
o Added processing of proxy certificates (RFC 3820).
Major changes between OpenSSL 0.9.7e and OpenSSL 0.9.7f [22 Mar 2005]:
o Several compilation issues fixed.
o Many memory allocation failure checks added.
o Improved comparison of X509 Name type.
o Mandatory basic checks on certificates.
o Performance improvements.
Major changes between OpenSSL 0.9.7d and OpenSSL 0.9.7e [25 Oct 2004]:
o Fix race condition in CRL checking code.
o Fixes to PKCS#7 (S/MIME) code.
Major changes between OpenSSL 0.9.7c and OpenSSL 0.9.7d [17 Mar 2004]:
o Security: Fix Kerberos ciphersuite SSL/TLS handshaking bug
o Security: Fix null-pointer assignment in do_change_cipher_spec()
o Allow multiple active certificates with same subject in CA index
o Multiple X509 verification fixes
o Speed up HMAC and other operations
Major changes between OpenSSL 0.9.7b and OpenSSL 0.9.7c [30 Sep 2003]:
o Security: fix various ASN1 parsing bugs.
o New -ignore_err option to OCSP utility.
o Various interop and bug fixes in S/MIME code.
o SSL/TLS protocol fix for unrequested client certificates.
Major changes between OpenSSL 0.9.7a and OpenSSL 0.9.7b [10 Apr 2003]:
o Security: counter the Klima-Pokorny-Rosa extension of
Bleichbacher's attack
o Security: make RSA blinding default.
o Configuration: Irix fixes, AIX fixes, better mingw support.
o Support for new platforms: linux-ia64-ecc.
o Build: shared library support fixes.
o ASN.1: treat domainComponent correctly.
o Documentation: fixes and additions.
Major changes between OpenSSL 0.9.7 and OpenSSL 0.9.7a [19 Feb 2003]:
o Security: Important security related bugfixes.
o Enhanced compatibility with MIT Kerberos.
o Can be built without the ENGINE framework.
o IA32 assembler enhancements.
o Support for new platforms: FreeBSD/IA64 and FreeBSD/Sparc64.
o Configuration: the no-err option now works properly.
o SSL/TLS: now handles manual certificate chain building.
o SSL/TLS: certain session ID malfunctions corrected.
Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.7 [30 Dec 2002]:
o New library section OCSP.
o Complete rewrite of ASN1 code.
o CRL checking in verify code and openssl utility.
o Extension copying in 'ca' utility.
o Flexible display options in 'ca' utility.
o Provisional support for international characters with UTF8.
o Support for external crypto devices ('engine') is no longer
a separate distribution.
o New elliptic curve library section.
o New AES (Rijndael) library section.
o Support for new platforms: Windows CE, Tandem OSS, A/UX, AIX 64-bit,
Linux x86_64, Linux 64-bit on Sparc v9
o Extended support for some platforms: VxWorks
o Enhanced support for shared libraries.
o Now only builds PIC code when shared library support is requested.
o Support for pkg-config.
o Lots of new manuals.
o Makes symbolic links to or copies of manuals to cover all described
functions.
o Change DES API to clean up the namespace (some applications link also
against libdes providing similar functions having the same name).
Provide macros for backward compatibility (will be removed in the
future).
o Unify handling of cryptographic algorithms (software and engine)
to be available via EVP routines for asymmetric and symmetric ciphers.
o NCONF: new configuration handling routines.
o Change API to use more 'const' modifiers to improve error checking
and help optimizers.
o Finally remove references to RSAref.
o Reworked parts of the BIGNUM code.
o Support for new engines: Broadcom ubsec, Accelerated Encryption
Processing, IBM 4758.
o A few new engines added in the demos area.
o Extended and corrected OID (object identifier) table.
o PRNG: query at more locations for a random device, automatic query for
EGD style random sources at several locations.
o SSL/TLS: allow optional cipher choice according to server's preference.
o SSL/TLS: allow server to explicitly set new session ids.
o SSL/TLS: support Kerberos cipher suites (RFC2712).
Only supports MIT Kerberos for now.
o SSL/TLS: allow more precise control of renegotiations and sessions.
o SSL/TLS: add callback to retrieve SSL/TLS messages.
o SSL/TLS: support AES cipher suites (RFC3268).
Major changes between OpenSSL 0.9.6j and OpenSSL 0.9.6k [30 Sep 2003]:
o Security: fix various ASN1 parsing bugs.
o SSL/TLS protocol fix for unrequested client certificates.
Major changes between OpenSSL 0.9.6i and OpenSSL 0.9.6j [10 Apr 2003]:
o Security: counter the Klima-Pokorny-Rosa extension of
Bleichbacher's attack
o Security: make RSA blinding default.
o Build: shared library support fixes.
Major changes between OpenSSL 0.9.6h and OpenSSL 0.9.6i [19 Feb 2003]:
o Important security related bugfixes.
Major changes between OpenSSL 0.9.6g and OpenSSL 0.9.6h [5 Dec 2002]:
o New configuration targets for Tandem OSS and A/UX.
o New OIDs for Microsoft attributes.
o Better handling of SSL session caching.
o Better comparison of distinguished names.
o Better handling of shared libraries in a mixed GNU/non-GNU environment.
o Support assembler code with Borland C.
o Fixes for length problems.
o Fixes for uninitialised variables.
o Fixes for memory leaks, some unusual crashes and some race conditions.
o Fixes for smaller building problems.
o Updates of manuals, FAQ and other instructive documents.
Major changes between OpenSSL 0.9.6f and OpenSSL 0.9.6g [9 Aug 2002]:
o Important building fixes on Unix.
Major changes between OpenSSL 0.9.6e and OpenSSL 0.9.6f [8 Aug 2002]:
o Various important bugfixes.
Major changes between OpenSSL 0.9.6d and OpenSSL 0.9.6e [30 Jul 2002]:
o Important security related bugfixes.
o Various SSL/TLS library bugfixes.
Major changes between OpenSSL 0.9.6c and OpenSSL 0.9.6d [9 May 2002]:
o Various SSL/TLS library bugfixes.
o Fix DH parameter generation for 'non-standard' generators.
Major changes between OpenSSL 0.9.6b and OpenSSL 0.9.6c [21 Dec 2001]:
o Various SSL/TLS library bugfixes.
o BIGNUM library fixes.
o RSA OAEP and random number generation fixes.
o Object identifiers corrected and added.
o Add assembler BN routines for IA64.
o Add support for OS/390 Unix, UnixWare with gcc, OpenUNIX 8,
MIPS Linux; shared library support for Irix, HP-UX.
o Add crypto accelerator support for AEP, Baltimore SureWare,
Broadcom and Cryptographic Appliance's keyserver
[in 0.9.6c-engine release].
Major changes between OpenSSL 0.9.6a and OpenSSL 0.9.6b [9 Jul 2001]:
o Security fix: PRNG improvements.
o Security fix: RSA OAEP check.
o Security fix: Reinsert and fix countermeasure to Bleichbacher's
attack.
o MIPS bug fix in BIGNUM.
o Bug fix in "openssl enc".
o Bug fix in X.509 printing routine.
o Bug fix in DSA verification routine and DSA S/MIME verification.
o Bug fix to make PRNG thread-safe.
o Bug fix in RAND_file_name().
o Bug fix in compatibility mode trust settings.
o Bug fix in blowfish EVP.
o Increase default size for BIO buffering filter.
o Compatibility fixes in some scripts.
Major changes between OpenSSL 0.9.6 and OpenSSL 0.9.6a [5 Apr 2001]:
o Security fix: change behavior of OpenSSL to avoid using
environment variables when running as root.
o Security fix: check the result of RSA-CRT to reduce the
possibility of deducing the private key from an incorrectly
calculated signature.
o Security fix: prevent Bleichenbacher's DSA attack.
o Security fix: Zero the premaster secret after deriving the
master secret in DH ciphersuites.
o Reimplement SSL_peek(), which had various problems.
o Compatibility fix: the function des_encrypt() renamed to
des_encrypt1() to avoid clashes with some Unixen libc.
o Bug fixes for Win32, HP/UX and Irix.
o Bug fixes in BIGNUM, SSL, PKCS#7, PKCS#12, X.509, CONF and
memory checking routines.
o Bug fixes for RSA operations in threaded environments.
o Bug fixes in misc. openssl applications.
o Remove a few potential memory leaks.
o Add tighter checks of BIGNUM routines.
o Shared library support has been reworked for generality.
o More documentation.
o New function BN_rand_range().
o Add "-rand" option to openssl s_client and s_server.
Major changes between OpenSSL 0.9.5a and OpenSSL 0.9.6 [10 Oct 2000]:
o Some documentation for BIO and SSL libraries.
o Enhanced chain verification using key identifiers.
o New sign and verify options to 'dgst' application.
o Support for DER and PEM encoded messages in 'smime' application.
o New 'rsautl' application, low level RSA utility.
o MD4 now included.
o Bugfix for SSL rollback padding check.
o Support for external crypto devices [1].
o Enhanced EVP interface.
[1] The support for external crypto devices is currently a separate
distribution. See the file README.ENGINE.
Major changes between OpenSSL 0.9.5 and OpenSSL 0.9.5a [1 Apr 2000]:
o Bug fixes for Win32, SuSE Linux, NeXTSTEP and FreeBSD 2.2.8
o Shared library support for HPUX and Solaris-gcc
o Support of Linux/IA64
o Assembler support for Mingw32
o New 'rand' application
o New way to check for existence of algorithms from scripts
Major changes between OpenSSL 0.9.4 and OpenSSL 0.9.5 [25 May 2000]:
o S/MIME support in new 'smime' command
o Documentation for the OpenSSL command line application
o Automation of 'req' application
o Fixes to make s_client, s_server work under Windows
o Support for multiple fieldnames in SPKACs
o New SPKAC command line utilty and associated library functions
o Options to allow passwords to be obtained from various sources
o New public key PEM format and options to handle it
o Many other fixes and enhancements to command line utilities
o Usable certificate chain verification
o Certificate purpose checking
o Certificate trust settings
o Support of authority information access extension
o Extensions in certificate requests
o Simplified X509 name and attribute routines
o Initial (incomplete) support for international character sets
o New DH_METHOD, DSA_METHOD and enhanced RSA_METHOD
o Read only memory BIOs and simplified creation function
o TLS/SSL protocol bugfixes: Accept TLS 'client hello' in SSL 3.0
record; allow fragmentation and interleaving of handshake and other
data
o TLS/SSL code now "tolerates" MS SGC
o Work around for Netscape client certificate hang bug
o RSA_NULL option that removes RSA patent code but keeps other
RSA functionality
o Memory leak detection now allows applications to add extra information
via a per-thread stack
o PRNG robustness improved
o EGD support
o BIGNUM library bug fixes
o Faster DSA parameter generation
o Enhanced support for Alpha Linux
o Experimental MacOS support
Major changes between OpenSSL 0.9.3 and OpenSSL 0.9.4 [9 Aug 1999]:
o Transparent support for PKCS#8 format private keys: these are used
by several software packages and are more secure than the standard
form
o PKCS#5 v2.0 implementation
o Password callbacks have a new void * argument for application data
o Avoid various memory leaks
o New pipe-like BIO that allows using the SSL library when actual I/O
must be handled by the application (BIO pair)
Major changes between OpenSSL 0.9.2b and OpenSSL 0.9.3 [24 May 1999]:
o Lots of enhancements and cleanups to the Configuration mechanism
o RSA OEAP related fixes
o Added `openssl ca -revoke' option for revoking a certificate
o Source cleanups: const correctness, type-safe stacks and ASN.1 SETs
o Source tree cleanups: removed lots of obsolete files
o Thawte SXNet, certificate policies and CRL distribution points
extension support
o Preliminary (experimental) S/MIME support
o Support for ASN.1 UTF8String and VisibleString
o Full integration of PKCS#12 code
o Sparc assembler bignum implementation, optimized hash functions
o Option to disable selected ciphers
Major changes between OpenSSL 0.9.1c and OpenSSL 0.9.2b [22 Mar 1999]:
o Fixed a security hole related to session resumption
o Fixed RSA encryption routines for the p < q case
o "ALL" in cipher lists now means "everything except NULL ciphers"
o Support for Triple-DES CBCM cipher
o Support of Optimal Asymmetric Encryption Padding (OAEP) for RSA
o First support for new TLSv1 ciphers
o Added a few new BIOs (syslog BIO, reliable BIO)
o Extended support for DSA certificate/keys.
o Extended support for Certificate Signing Requests (CSR)
o Initial support for X.509v3 extensions
o Extended support for compression inside the SSL record layer
o Overhauled Win32 builds
o Cleanups and fixes to the Big Number (BN) library
o Support for ASN.1 GeneralizedTime
o Splitted ASN.1 SETs from SEQUENCEs
o ASN1 and PEM support for Netscape Certificate Sequences
o Overhauled Perl interface
o Lots of source tree cleanups.
o Lots of memory leak fixes.
o Lots of bug fixes.
Major changes between SSLeay 0.9.0b and OpenSSL 0.9.1c [23 Dec 1998]:
o Integration of the popular NO_RSA/NO_DSA patches
o Initial support for compression inside the SSL record layer
o Added BIO proxy and filtering functionality
o Extended Big Number (BN) library
o Added RIPE MD160 message digest
o Addeed support for RC2/64bit cipher
o Extended ASN.1 parser routines
o Adjustations of the source tree for CVS
o Support for various new platforms
-139
View File
@@ -1,139 +0,0 @@
NOTES FOR THE WINDOWS PLATFORMS
===============================
Requirement details for native (Visual C++) builds
--------------------------------------------------
In addition to the requirements and instructions listed in INSTALL,
this are required as well:
- You need Perl. We recommend ActiveState Perl, available from
https://www.activestate.com/ActivePerl. Another viable alternative
appears to be Strawberry Perl, http://strawberryperl.com.
You also need the perl module Text::Template, available on CPAN.
Please read NOTES.PERL for more information.
- You need a C compiler. OpenSSL has been tested to build with these:
* Visual C++
- Netwide Assembler, a.k.a. NASM, available from http://www.nasm.us,
is required if you intend to utilize assembler modules. Note that NASM
is the only supported assembler. The Microsoft provided assembler is NOT
supported.
Visual C++ (native Windows)
---------------------------
Installation directories
The default installation directories are derived from environment
variables.
For VC-WIN32, the following defaults are use:
PREFIX: %ProgramFiles(86)%\OpenSSL
OPENSSLDIR: %CommonProgramFiles(86)%\SSL
For VC-WIN64, the following defaults are use:
PREFIX: %ProgramW6432%\OpenSSL
OPENSSLDIR: %CommonProgramW6432%\SSL
Should those environment variables not exist (on a pure Win32
installation for examples), these fallbacks are used:
PREFIX: %ProgramFiles%\OpenSSL
OPENSSLDIR: %CommonProgramFiles%\SSL
ALSO NOTE that those directories are usually write protected, even if
your account is in the Administrators group. To work around that,
start the command prompt by right-clicking on it and choosing "Run as
Administrator" before running 'nmake install'. The other solution
is, of course, to choose a different set of directories by using
--prefix and --openssldir when configuring.
GNU C (Cygwin)
--------------
Cygwin implements a Posix/Unix runtime system (cygwin1.dll) on top of the
Windows subsystem and provides a bash shell and GNU tools environment.
Consequently, a make of OpenSSL with Cygwin is virtually identical to the
Unix procedure.
To build OpenSSL using Cygwin, you need to:
* Install Cygwin (see https://cygwin.com/)
* Install Cygwin Perl and ensure it is in the path. Recall that
as least 5.10.0 is required.
* Run the Cygwin bash shell
Apart from that, follow the Unix instructions in INSTALL.
NOTE: "make test" and normal file operations may fail in directories
mounted as text (i.e. mount -t c:\somewhere /home) due to Cygwin
stripping of carriage returns. To avoid this ensure that a binary
mount is used, e.g. mount -b c:\somewhere /home.
It is also possible to create "conventional" Windows binaries that use
the Microsoft C runtime system (msvcrt.dll or crtdll.dll) using MinGW
development add-on for Cygwin. MinGW is supported even as a standalone
setup as described in the following section. In the context you should
recognize that binaries targeting Cygwin itself are not interchangeable
with "conventional" Windows binaries you generate with/for MinGW.
GNU C (MinGW/MSYS)
------------------
* Compiler and shell environment installation:
MinGW and MSYS are available from http://www.mingw.org/, both are
required. Run the installers and do whatever magic they say it takes
to start MSYS bash shell with GNU tools and matching Perl on its PATH.
"Matching Perl" refers to chosen "shell environment", i.e. if built
under MSYS, then Perl compiled for MSYS must be used.
Alternatively, one can use MSYS2 from https://msys2.github.io/,
which includes MingW (32-bit and 64-bit).
* It is also possible to cross-compile it on Linux by configuring
with './Configure --cross-compile-prefix=i386-mingw32- mingw ...'.
Other possible cross compile prefixes include x86_64-w64-mingw32-
and i686-w64-mingw32-.
Linking your application
------------------------
This section applies to non-Cygwin builds.
If you link with static OpenSSL libraries then you're expected to
additionally link your application with WS2_32.LIB, GDI32.LIB,
ADVAPI32.LIB, CRYPT32.LIB and USER32.LIB. Those developing
non-interactive service applications might feel concerned about
linking with GDI32.LIB and USER32.LIB, as they are justly associated
with interactive desktop, which is not available to service
processes. The toolkit is designed to detect in which context it's
currently executed, GUI, console app or service, and act accordingly,
namely whether or not to actually make GUI calls. Additionally those
who wish to /DELAYLOAD:GDI32.DLL and /DELAYLOAD:USER32.DLL and
actually keep them off service process should consider implementing
and exporting from .exe image in question own _OPENSSL_isservice not
relying on USER32.DLL. E.g., on Windows Vista and later you could:
__declspec(dllexport) __cdecl BOOL _OPENSSL_isservice(void)
{ DWORD sess;
if (ProcessIdToSessionId(GetCurrentProcessId(),&sess))
return sess==0;
return FALSE;
}
If you link with OpenSSL .DLLs, then you're expected to include into
your application code small "shim" snippet, which provides glue between
OpenSSL BIO layer and your compiler run-time. See the OPENSSL_Applink
manual page for further details.
-61
View File
@@ -1,61 +0,0 @@
NOTE: The OpenSSL Software Foundation has executed a sublicense agreement
entitled "Elliptic Curve Cryptography Patent License Agreement" with the
National Security Agency/ Central Security Service Commercial Solutions
Center (NCSC) dated 2010-11-04. That agreement permits implementation and
distribution of software containing features covered by any or all of the
following patents:
1.) U.S. Pat. No. 5,761,305 entitled "Key Agreement and Transport Protocol
with Implicit Signatures" issued on June 2, 1998;
2.) Can. Pat. Appl. Ser. No. 2176972 entitled "Key Agreement and Transport
Protocol with Implicit Signature and Reduced Bandwidth" filed on May
16, 1996;
3.) U.S. Pat. No. 5,889,865 entitled "Key Agreement and Transport Protocol
with Implicit Signatures" issued on March 30, 1999;
4.) U.S. Pat. No. 5,896,455 entitled "Key Agreement and Transport Protocol
with Implicit Signatures" issued on April 20, 1999;
5.) U.S. Pat. No. 5,933,504 entitled "Strengthened Public Key Protocol"
issued on August 3, 1999;
6.) Can. Pat. Appl. Ser. No. 2176866 entitled "Strengthened Public Key
Protocol" filed on May 17, 1996;
7.) E.P. Pat. Appl. Ser. No. 96201322.3 entitled "Strengthened Public Key
Protocol" filed on May 17, 1996;
8.) U.S. Pat. No. 5,999,626 entitled "Digital Signatures on a Smartcard"
issued on December 7, 1999;
9.) Can. Pat. Appl. Ser. No. 2202566 entitled "Digital Signatures on a
Smartcard" filed on April 14, 1997;
10.) E.P. Pat. Appl. No. 97106114.8 entitled "Digital Signatures on a
Smartcard" filed on April 15, 1997;
11.) U.S Pat. No. 6,122,736 entitled "Key Agreement and Transport Protocol
with Implicit Signatures" issued on September 19, 2000;
12.) Can. Pat. Appl. Ser. No. 2174261 entitled "Key Agreement and Transport
Protocol with Implicit Signatures" filed on April 16, 1996;
13.) E.P. Pat. Appl. Ser. No. 96105920.1 entitled "Key Agreement and
Transport Protocol with Implicit Signatures" filed on April 16, 1996;
14.) U.S. Pat. No. 6,141,420 entitled "Elliptic Curve Encryption Systems"
issued on October 31, 2000;
15.) Can. Pat. Appl. Ser. No. 2155038 entitled "Elliptic Curve Encryption
Systems" filed on July 31, 1995;
16.) E.P. Pat. Appl. Ser. No. 95926348.4 entitled "Elliptic Curve Encryption
Systems" filed on July 31, 1995;
17.) U.S. Pat. No. 6,336,188 entitled "Authenticated Key Agreement" issued
on January 1, 2002;
18.) U.S. Pat. No. 6,487,661 entitled "Key Agreement and Transport Protocol"
issued on November 26, 2002;
19.) Can. Pat. Appl. Ser. No. 2174260 entitled "Key Agreement and Transport
Protocol" filed on April 16, 1996;
20.) E.P. Pat. Appl. Ser. No. 96105921.9 entitled "Key Agreement and
Transport Protocol" filed on April 21, 1996;
21.) U.S. Pat. No. 6,563,928 entitled "Strengthened Public Key Protocol"
issued on May 13, 2003;
22.) U.S. Pat. No. 6,618,483 entitled "Elliptic Curve Encryption Systems"
issued September 9, 2003;
23.) U.S. Pat. Appl. Ser. No. 09/434,247 entitled "Digital Signatures on a
Smartcard" filed on November 5, 1999;
24.) U.S. Pat. Appl. Ser. No. 09/558,256 entitled "Key Agreement and
Transport Protocol with Implicit Signatures" filed on April 25, 2000;
25.) U.S. Pat. Appl. Ser. No. 09/942,492 entitled "Digital Signatures on a
Smartcard" filed on August 29, 2001 and published on July 18, 2002; and,
26.) U.S. Pat. Appl. Ser. No. 10/185,735 entitled "Strengthened Public Key
Protocol" filed on July 1, 2000.
-94
View File
@@ -1,94 +0,0 @@
OpenSSL 1.1.0f 25 May 2017
Copyright (c) 1998-2016 The OpenSSL Project
Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson
All rights reserved.
DESCRIPTION
-----------
The OpenSSL Project is a collaborative effort to develop a robust,
commercial-grade, fully featured, and Open Source toolkit implementing the
Transport Layer Security (TLS) protocols (including SSLv3) as well as a
full-strength general purpose cryptographic library.
OpenSSL is descended from the SSLeay library developed by Eric A. Young
and Tim J. Hudson. The OpenSSL toolkit is licensed under a dual-license (the
OpenSSL license plus the SSLeay license), which means that you are free to
get and use it for commercial and non-commercial purposes as long as you
fulfill the conditions of both licenses.
OVERVIEW
--------
The OpenSSL toolkit includes:
libssl (with platform specific naming):
Provides the client and server-side implementations for SSLv3 and TLS.
libcrypto (with platform specific naming):
Provides general cryptographic and X.509 support needed by SSL/TLS but
not logically part of it.
openssl:
A command line tool that can be used for:
Creation of key parameters
Creation of X.509 certificates, CSRs and CRLs
Calculation of message digests
Encryption and decryption
SSL/TLS client and server tests
Handling of S/MIME signed or encrypted mail
And more...
INSTALLATION
------------
See the appropriate file:
INSTALL Linux, Unix, Windows, OpenVMS, ...
NOTES.* INSTALL addendums for different platforms
SUPPORT
-------
See the OpenSSL website www.openssl.org for details on how to obtain
commercial technical support. Free community support is available through the
openssl-users email list (see
https://www.openssl.org/community/mailinglists.html for further details).
If you have any problems with OpenSSL then please take the following steps
first:
- Download the latest version from the repository
to see if the problem has already been addressed
- Configure with no-asm
- Remove compiler optimisation flags
If you wish to report a bug then please include the following information
and create an issue on GitHub:
- OpenSSL version: output of 'openssl version -a'
- Any "Configure" options that you selected during compilation of the
library if applicable (see INSTALL)
- OS Name, Version, Hardware platform
- Compiler Details (name, version)
- Application Details (name, version)
- Problem Description (steps that will reproduce the problem, if known)
- Stack Traceback (if the application dumps core)
Just because something doesn't work the way you expect does not mean it
is necessarily a bug in OpenSSL. Use the openssl-users email list for this type
of query.
HOW TO CONTRIBUTE TO OpenSSL
----------------------------
See CONTRIBUTING
LEGALITIES
----------
A number of nations restrict the use or export of cryptography. If you
are potentially subject to such restrictions you should seek competent
professional legal advice before attempting to develop or distribute
cryptographic code.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,16 +0,0 @@
/*
* Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is only used by HP C on VMS, and is included automatically
* after each header file from this directory
*/
/* restore state. Must correspond to the save in __decc_include_prologue.h */
#pragma names restore
@@ -1,20 +0,0 @@
/*
* Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is only used by HP C on VMS, and is included automatically
* after each header file from this directory
*/
/* save state */
#pragma names save
/* have the compiler shorten symbols larger than 31 chars to 23 chars
* followed by a 8 hex char CRC
*/
#pragma names as_is,shortened
-92
View File
@@ -1,92 +0,0 @@
/*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_AES_H
# define HEADER_AES_H
# include <openssl/opensslconf.h>
# include <stddef.h>
# ifdef __cplusplus
extern "C" {
# endif
# define AES_ENCRYPT 1
# define AES_DECRYPT 0
/*
* Because array size can't be a const in C, the following two are macros.
* Both sizes are in bytes.
*/
# define AES_MAXNR 14
# define AES_BLOCK_SIZE 16
/* This should be a hidden type, but EVP requires that the size be known */
struct aes_key_st {
# ifdef AES_LONG
unsigned long rd_key[4 * (AES_MAXNR + 1)];
# else
unsigned int rd_key[4 * (AES_MAXNR + 1)];
# endif
int rounds;
};
typedef struct aes_key_st AES_KEY;
const char *AES_options(void);
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key);
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key);
void AES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void AES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key);
void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key, const int enc);
void AES_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc);
void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc);
void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc);
void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc);
void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num);
/* NB: the IV is _two_ blocks long */
void AES_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc);
/* NB: the IV is _four_ blocks long */
void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
const AES_KEY *key2, const unsigned char *ivec,
const int enc);
int AES_wrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen);
int AES_unwrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen);
# ifdef __cplusplus
}
# endif
#endif
-138
View File
@@ -1,138 +0,0 @@
/*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#define APPLINK_STDIN 1
#define APPLINK_STDOUT 2
#define APPLINK_STDERR 3
#define APPLINK_FPRINTF 4
#define APPLINK_FGETS 5
#define APPLINK_FREAD 6
#define APPLINK_FWRITE 7
#define APPLINK_FSETMOD 8
#define APPLINK_FEOF 9
#define APPLINK_FCLOSE 10 /* should not be used */
#define APPLINK_FOPEN 11 /* solely for completeness */
#define APPLINK_FSEEK 12
#define APPLINK_FTELL 13
#define APPLINK_FFLUSH 14
#define APPLINK_FERROR 15
#define APPLINK_CLEARERR 16
#define APPLINK_FILENO 17 /* to be used with below */
#define APPLINK_OPEN 18 /* formally can't be used, as flags can vary */
#define APPLINK_READ 19
#define APPLINK_WRITE 20
#define APPLINK_LSEEK 21
#define APPLINK_CLOSE 22
#define APPLINK_MAX 22 /* always same as last macro */
#ifndef APPMACROS_ONLY
# include <stdio.h>
# include <io.h>
# include <fcntl.h>
static void *app_stdin(void)
{
return stdin;
}
static void *app_stdout(void)
{
return stdout;
}
static void *app_stderr(void)
{
return stderr;
}
static int app_feof(FILE *fp)
{
return feof(fp);
}
static int app_ferror(FILE *fp)
{
return ferror(fp);
}
static void app_clearerr(FILE *fp)
{
clearerr(fp);
}
static int app_fileno(FILE *fp)
{
return _fileno(fp);
}
static int app_fsetmod(FILE *fp, char mod)
{
return _setmode(_fileno(fp), mod == 'b' ? _O_BINARY : _O_TEXT);
}
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport)
void **
# if defined(__BORLANDC__)
/*
* __stdcall appears to be the only way to get the name
* decoration right with Borland C. Otherwise it works
* purely incidentally, as we pass no parameters.
*/
__stdcall
# else
__cdecl
# endif
OPENSSL_Applink(void)
{
static int once = 1;
static void *OPENSSL_ApplinkTable[APPLINK_MAX + 1] =
{ (void *)APPLINK_MAX };
if (once) {
OPENSSL_ApplinkTable[APPLINK_STDIN] = app_stdin;
OPENSSL_ApplinkTable[APPLINK_STDOUT] = app_stdout;
OPENSSL_ApplinkTable[APPLINK_STDERR] = app_stderr;
OPENSSL_ApplinkTable[APPLINK_FPRINTF] = fprintf;
OPENSSL_ApplinkTable[APPLINK_FGETS] = fgets;
OPENSSL_ApplinkTable[APPLINK_FREAD] = fread;
OPENSSL_ApplinkTable[APPLINK_FWRITE] = fwrite;
OPENSSL_ApplinkTable[APPLINK_FSETMOD] = app_fsetmod;
OPENSSL_ApplinkTable[APPLINK_FEOF] = app_feof;
OPENSSL_ApplinkTable[APPLINK_FCLOSE] = fclose;
OPENSSL_ApplinkTable[APPLINK_FOPEN] = fopen;
OPENSSL_ApplinkTable[APPLINK_FSEEK] = fseek;
OPENSSL_ApplinkTable[APPLINK_FTELL] = ftell;
OPENSSL_ApplinkTable[APPLINK_FFLUSH] = fflush;
OPENSSL_ApplinkTable[APPLINK_FERROR] = app_ferror;
OPENSSL_ApplinkTable[APPLINK_CLEARERR] = app_clearerr;
OPENSSL_ApplinkTable[APPLINK_FILENO] = app_fileno;
OPENSSL_ApplinkTable[APPLINK_OPEN] = _open;
OPENSSL_ApplinkTable[APPLINK_READ] = _read;
OPENSSL_ApplinkTable[APPLINK_WRITE] = _write;
OPENSSL_ApplinkTable[APPLINK_LSEEK] = _lseek;
OPENSSL_ApplinkTable[APPLINK_CLOSE] = _close;
once = 0;
}
return OPENSSL_ApplinkTable;
}
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large Load Diff
-10
View File
@@ -1,10 +0,0 @@
/*
* Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#error "This file is obsolete; please update your software."
-929
View File
@@ -1,929 +0,0 @@
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_ASN1T_H
# define HEADER_ASN1T_H
# include <stddef.h>
# include <openssl/e_os2.h>
# include <openssl/asn1.h>
# ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
# endif
/* ASN1 template defines, structures and functions */
#ifdef __cplusplus
extern "C" {
#endif
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */
# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)(iptr))
/* Macros for start and end of ASN1_ITEM definition */
# define ASN1_ITEM_start(itname) \
OPENSSL_GLOBAL const ASN1_ITEM itname##_it = {
# define static_ASN1_ITEM_start(itname) \
static const ASN1_ITEM itname##_it = {
# define ASN1_ITEM_end(itname) \
};
# else
/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */
# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)(iptr()))
/* Macros for start and end of ASN1_ITEM definition */
# define ASN1_ITEM_start(itname) \
const ASN1_ITEM * itname##_it(void) \
{ \
static const ASN1_ITEM local_it = {
# define static_ASN1_ITEM_start(itname) \
static ASN1_ITEM_start(itname)
# define ASN1_ITEM_end(itname) \
}; \
return &local_it; \
}
# endif
/* Macros to aid ASN1 template writing */
# define ASN1_ITEM_TEMPLATE(tname) \
static const ASN1_TEMPLATE tname##_item_tt
# define ASN1_ITEM_TEMPLATE_END(tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_PRIMITIVE,\
-1,\
&tname##_item_tt,\
0,\
NULL,\
0,\
#tname \
ASN1_ITEM_end(tname)
# define static_ASN1_ITEM_TEMPLATE_END(tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_PRIMITIVE,\
-1,\
&tname##_item_tt,\
0,\
NULL,\
0,\
#tname \
ASN1_ITEM_end(tname)
/* This is a ASN1 type which just embeds a template */
/*-
* This pair helps declare a SEQUENCE. We can do:
*
* ASN1_SEQUENCE(stname) = {
* ... SEQUENCE components ...
* } ASN1_SEQUENCE_END(stname)
*
* This will produce an ASN1_ITEM called stname_it
* for a structure called stname.
*
* If you want the same structure but a different
* name then use:
*
* ASN1_SEQUENCE(itname) = {
* ... SEQUENCE components ...
* } ASN1_SEQUENCE_END_name(stname, itname)
*
* This will create an item called itname_it using
* a structure called stname.
*/
# define ASN1_SEQUENCE(tname) \
static const ASN1_TEMPLATE tname##_seq_tt[]
# define ASN1_SEQUENCE_END(stname) ASN1_SEQUENCE_END_name(stname, stname)
# define static_ASN1_SEQUENCE_END(stname) static_ASN1_SEQUENCE_END_name(stname, stname)
# define ASN1_SEQUENCE_END_name(stname, tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define static_ASN1_SEQUENCE_END_name(stname, tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define ASN1_NDEF_SEQUENCE(tname) \
ASN1_SEQUENCE(tname)
# define ASN1_NDEF_SEQUENCE_cb(tname, cb) \
ASN1_SEQUENCE_cb(tname, cb)
# define ASN1_SEQUENCE_cb(tname, cb) \
static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0}; \
ASN1_SEQUENCE(tname)
# define ASN1_BROKEN_SEQUENCE(tname) \
static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_BROKEN, 0, 0, 0, 0}; \
ASN1_SEQUENCE(tname)
# define ASN1_SEQUENCE_ref(tname, cb) \
static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_REFCOUNT, offsetof(tname, references), offsetof(tname, lock), cb, 0}; \
ASN1_SEQUENCE(tname)
# define ASN1_SEQUENCE_enc(tname, enc, cb) \
static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_ENCODING, 0, 0, cb, offsetof(tname, enc)}; \
ASN1_SEQUENCE(tname)
# define ASN1_NDEF_SEQUENCE_END(tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_NDEF_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(tname),\
#tname \
ASN1_ITEM_end(tname)
# define static_ASN1_NDEF_SEQUENCE_END(tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_NDEF_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(tname),\
#tname \
ASN1_ITEM_end(tname)
# define ASN1_BROKEN_SEQUENCE_END(stname) ASN1_SEQUENCE_END_ref(stname, stname)
# define static_ASN1_BROKEN_SEQUENCE_END(stname) \
static_ASN1_SEQUENCE_END_ref(stname, stname)
# define ASN1_SEQUENCE_END_enc(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
# define ASN1_SEQUENCE_END_cb(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
# define static_ASN1_SEQUENCE_END_cb(stname, tname) static_ASN1_SEQUENCE_END_ref(stname, tname)
# define ASN1_SEQUENCE_END_ref(stname, tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define static_ASN1_SEQUENCE_END_ref(stname, tname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define ASN1_NDEF_SEQUENCE_END_cb(stname, tname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_NDEF_SEQUENCE,\
V_ASN1_SEQUENCE,\
tname##_seq_tt,\
sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
/*-
* This pair helps declare a CHOICE type. We can do:
*
* ASN1_CHOICE(chname) = {
* ... CHOICE options ...
* ASN1_CHOICE_END(chname)
*
* This will produce an ASN1_ITEM called chname_it
* for a structure called chname. The structure
* definition must look like this:
* typedef struct {
* int type;
* union {
* ASN1_SOMETHING *opt1;
* ASN1_SOMEOTHER *opt2;
* } value;
* } chname;
*
* the name of the selector must be 'type'.
* to use an alternative selector name use the
* ASN1_CHOICE_END_selector() version.
*/
# define ASN1_CHOICE(tname) \
static const ASN1_TEMPLATE tname##_ch_tt[]
# define ASN1_CHOICE_cb(tname, cb) \
static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0}; \
ASN1_CHOICE(tname)
# define ASN1_CHOICE_END(stname) ASN1_CHOICE_END_name(stname, stname)
# define static_ASN1_CHOICE_END(stname) static_ASN1_CHOICE_END_name(stname, stname)
# define ASN1_CHOICE_END_name(stname, tname) ASN1_CHOICE_END_selector(stname, tname, type)
# define static_ASN1_CHOICE_END_name(stname, tname) static_ASN1_CHOICE_END_selector(stname, tname, type)
# define ASN1_CHOICE_END_selector(stname, tname, selname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_CHOICE,\
offsetof(stname,selname) ,\
tname##_ch_tt,\
sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define static_ASN1_CHOICE_END_selector(stname, tname, selname) \
;\
static_ASN1_ITEM_start(tname) \
ASN1_ITYPE_CHOICE,\
offsetof(stname,selname) ,\
tname##_ch_tt,\
sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
NULL,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
# define ASN1_CHOICE_END_cb(stname, tname, selname) \
;\
ASN1_ITEM_start(tname) \
ASN1_ITYPE_CHOICE,\
offsetof(stname,selname) ,\
tname##_ch_tt,\
sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
&tname##_aux,\
sizeof(stname),\
#stname \
ASN1_ITEM_end(tname)
/* This helps with the template wrapper form of ASN1_ITEM */
# define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, type) { \
(flags), (tag), 0,\
#name, ASN1_ITEM_ref(type) }
/* These help with SEQUENCE or CHOICE components */
/* used to declare other types */
# define ASN1_EX_TYPE(flags, tag, stname, field, type) { \
(flags), (tag), offsetof(stname, field),\
#field, ASN1_ITEM_ref(type) }
/* implicit and explicit helper macros */
# define ASN1_IMP_EX(stname, field, type, tag, ex) \
ASN1_EX_TYPE(ASN1_TFLG_IMPLICIT | ex, tag, stname, field, type)
# define ASN1_EXP_EX(stname, field, type, tag, ex) \
ASN1_EX_TYPE(ASN1_TFLG_EXPLICIT | ex, tag, stname, field, type)
/* Any defined by macros: the field used is in the table itself */
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) }
# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, (const ASN1_ITEM *)&(tblname##_adb) }
# else
# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, tblname##_adb }
# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, tblname##_adb }
# endif
/* Plain simple type */
# define ASN1_SIMPLE(stname, field, type) ASN1_EX_TYPE(0,0, stname, field, type)
/* Embedded simple type */
# define ASN1_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_EMBED,0, stname, field, type)
/* OPTIONAL simple type */
# define ASN1_OPT(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL, 0, stname, field, type)
# define ASN1_OPT_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED, 0, stname, field, type)
/* IMPLICIT tagged simple type */
# define ASN1_IMP(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, 0)
# define ASN1_IMP_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
/* IMPLICIT tagged OPTIONAL simple type */
# define ASN1_IMP_OPT(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
# define ASN1_IMP_OPT_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
/* Same as above but EXPLICIT */
# define ASN1_EXP(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, 0)
# define ASN1_EXP_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
# define ASN1_EXP_OPT(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
# define ASN1_EXP_OPT_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
/* SEQUENCE OF type */
# define ASN1_SEQUENCE_OF(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, stname, field, type)
/* OPTIONAL SEQUENCE OF */
# define ASN1_SEQUENCE_OF_OPT(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
/* Same as above but for SET OF */
# define ASN1_SET_OF(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SET_OF, 0, stname, field, type)
# define ASN1_SET_OF_OPT(stname, field, type) \
ASN1_EX_TYPE(ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
/* Finally compound types of SEQUENCE, SET, IMPLICIT, EXPLICIT and OPTIONAL */
# define ASN1_IMP_SET_OF(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
# define ASN1_EXP_SET_OF(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
# define ASN1_IMP_SET_OF_OPT(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
# define ASN1_EXP_SET_OF_OPT(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
# define ASN1_IMP_SEQUENCE_OF(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
# define ASN1_IMP_SEQUENCE_OF_OPT(stname, field, type, tag) \
ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
# define ASN1_EXP_SEQUENCE_OF(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
# define ASN1_EXP_SEQUENCE_OF_OPT(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
/* EXPLICIT using indefinite length constructed form */
# define ASN1_NDEF_EXP(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_NDEF)
/* EXPLICIT OPTIONAL using indefinite length constructed form */
# define ASN1_NDEF_EXP_OPT(stname, field, type, tag) \
ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_NDEF)
/* Macros for the ASN1_ADB structure */
# define ASN1_ADB(name) \
static const ASN1_ADB_TABLE name##_adbtbl[]
# ifndef OPENSSL_EXPORT_VAR_AS_FUNCTION
# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \
;\
static const ASN1_ADB name##_adb = {\
flags,\
offsetof(name, field),\
adb_cb,\
name##_adbtbl,\
sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\
def,\
none\
}
# else
# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \
;\
static const ASN1_ITEM *name##_adb(void) \
{ \
static const ASN1_ADB internal_adb = \
{\
flags,\
offsetof(name, field),\
adb_cb,\
name##_adbtbl,\
sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\
def,\
none\
}; \
return (const ASN1_ITEM *) &internal_adb; \
} \
void dummy_function(void)
# endif
# define ADB_ENTRY(val, template) {val, template}
# define ASN1_ADB_TEMPLATE(name) \
static const ASN1_TEMPLATE name##_tt
/*
* This is the ASN1 template structure that defines a wrapper round the
* actual type. It determines the actual position of the field in the value
* structure, various flags such as OPTIONAL and the field name.
*/
struct ASN1_TEMPLATE_st {
unsigned long flags; /* Various flags */
long tag; /* tag, not used if no tagging */
unsigned long offset; /* Offset of this field in structure */
const char *field_name; /* Field name */
ASN1_ITEM_EXP *item; /* Relevant ASN1_ITEM or ASN1_ADB */
};
/* Macro to extract ASN1_ITEM and ASN1_ADB pointer from ASN1_TEMPLATE */
# define ASN1_TEMPLATE_item(t) (t->item_ptr)
# define ASN1_TEMPLATE_adb(t) (t->item_ptr)
typedef struct ASN1_ADB_TABLE_st ASN1_ADB_TABLE;
typedef struct ASN1_ADB_st ASN1_ADB;
struct ASN1_ADB_st {
unsigned long flags; /* Various flags */
unsigned long offset; /* Offset of selector field */
int (*adb_cb)(long *psel); /* Application callback */
const ASN1_ADB_TABLE *tbl; /* Table of possible types */
long tblcount; /* Number of entries in tbl */
const ASN1_TEMPLATE *default_tt; /* Type to use if no match */
const ASN1_TEMPLATE *null_tt; /* Type to use if selector is NULL */
};
struct ASN1_ADB_TABLE_st {
long value; /* NID for an object or value for an int */
const ASN1_TEMPLATE tt; /* item for this value */
};
/* template flags */
/* Field is optional */
# define ASN1_TFLG_OPTIONAL (0x1)
/* Field is a SET OF */
# define ASN1_TFLG_SET_OF (0x1 << 1)
/* Field is a SEQUENCE OF */
# define ASN1_TFLG_SEQUENCE_OF (0x2 << 1)
/*
* Special case: this refers to a SET OF that will be sorted into DER order
* when encoded *and* the corresponding STACK will be modified to match the
* new order.
*/
# define ASN1_TFLG_SET_ORDER (0x3 << 1)
/* Mask for SET OF or SEQUENCE OF */
# define ASN1_TFLG_SK_MASK (0x3 << 1)
/*
* These flags mean the tag should be taken from the tag field. If EXPLICIT
* then the underlying type is used for the inner tag.
*/
/* IMPLICIT tagging */
# define ASN1_TFLG_IMPTAG (0x1 << 3)
/* EXPLICIT tagging, inner tag from underlying type */
# define ASN1_TFLG_EXPTAG (0x2 << 3)
# define ASN1_TFLG_TAG_MASK (0x3 << 3)
/* context specific IMPLICIT */
# define ASN1_TFLG_IMPLICIT ASN1_TFLG_IMPTAG|ASN1_TFLG_CONTEXT
/* context specific EXPLICIT */
# define ASN1_TFLG_EXPLICIT ASN1_TFLG_EXPTAG|ASN1_TFLG_CONTEXT
/*
* If tagging is in force these determine the type of tag to use. Otherwise
* the tag is determined by the underlying type. These values reflect the
* actual octet format.
*/
/* Universal tag */
# define ASN1_TFLG_UNIVERSAL (0x0<<6)
/* Application tag */
# define ASN1_TFLG_APPLICATION (0x1<<6)
/* Context specific tag */
# define ASN1_TFLG_CONTEXT (0x2<<6)
/* Private tag */
# define ASN1_TFLG_PRIVATE (0x3<<6)
# define ASN1_TFLG_TAG_CLASS (0x3<<6)
/*
* These are for ANY DEFINED BY type. In this case the 'item' field points to
* an ASN1_ADB structure which contains a table of values to decode the
* relevant type
*/
# define ASN1_TFLG_ADB_MASK (0x3<<8)
# define ASN1_TFLG_ADB_OID (0x1<<8)
# define ASN1_TFLG_ADB_INT (0x1<<9)
/*
* This flag when present in a SEQUENCE OF, SET OF or EXPLICIT causes
* indefinite length constructed encoding to be used if required.
*/
# define ASN1_TFLG_NDEF (0x1<<11)
/* Field is embedded and not a pointer */
# define ASN1_TFLG_EMBED (0x1 << 12)
/* This is the actual ASN1 item itself */
struct ASN1_ITEM_st {
char itype; /* The item type, primitive, SEQUENCE, CHOICE
* or extern */
long utype; /* underlying type */
const ASN1_TEMPLATE *templates; /* If SEQUENCE or CHOICE this contains
* the contents */
long tcount; /* Number of templates if SEQUENCE or CHOICE */
const void *funcs; /* functions that handle this type */
long size; /* Structure size (usually) */
const char *sname; /* Structure name */
};
/*-
* These are values for the itype field and
* determine how the type is interpreted.
*
* For PRIMITIVE types the underlying type
* determines the behaviour if items is NULL.
*
* Otherwise templates must contain a single
* template and the type is treated in the
* same way as the type specified in the template.
*
* For SEQUENCE types the templates field points
* to the members, the size field is the
* structure size.
*
* For CHOICE types the templates field points
* to each possible member (typically a union)
* and the 'size' field is the offset of the
* selector.
*
* The 'funcs' field is used for application
* specific functions.
*
* The EXTERN type uses a new style d2i/i2d.
* The new style should be used where possible
* because it avoids things like the d2i IMPLICIT
* hack.
*
* MSTRING is a multiple string type, it is used
* for a CHOICE of character strings where the
* actual strings all occupy an ASN1_STRING
* structure. In this case the 'utype' field
* has a special meaning, it is used as a mask
* of acceptable types using the B_ASN1 constants.
*
* NDEF_SEQUENCE is the same as SEQUENCE except
* that it will use indefinite length constructed
* encoding if requested.
*
*/
# define ASN1_ITYPE_PRIMITIVE 0x0
# define ASN1_ITYPE_SEQUENCE 0x1
# define ASN1_ITYPE_CHOICE 0x2
# define ASN1_ITYPE_EXTERN 0x4
# define ASN1_ITYPE_MSTRING 0x5
# define ASN1_ITYPE_NDEF_SEQUENCE 0x6
/*
* Cache for ASN1 tag and length, so we don't keep re-reading it for things
* like CHOICE
*/
struct ASN1_TLC_st {
char valid; /* Values below are valid */
int ret; /* return value */
long plen; /* length */
int ptag; /* class value */
int pclass; /* class value */
int hdrlen; /* header length */
};
/* Typedefs for ASN1 function pointers */
typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
ASN1_TLC *ctx);
typedef int ASN1_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
typedef int ASN1_ex_print_func(BIO *out, ASN1_VALUE **pval,
int indent, const char *fname,
const ASN1_PCTX *pctx);
typedef int ASN1_primitive_i2c(ASN1_VALUE **pval, unsigned char *cont,
int *putype, const ASN1_ITEM *it);
typedef int ASN1_primitive_c2i(ASN1_VALUE **pval, const unsigned char *cont,
int len, int utype, char *free_cont,
const ASN1_ITEM *it);
typedef int ASN1_primitive_print(BIO *out, ASN1_VALUE **pval,
const ASN1_ITEM *it, int indent,
const ASN1_PCTX *pctx);
typedef struct ASN1_EXTERN_FUNCS_st {
void *app_data;
ASN1_ex_new_func *asn1_ex_new;
ASN1_ex_free_func *asn1_ex_free;
ASN1_ex_free_func *asn1_ex_clear;
ASN1_ex_d2i *asn1_ex_d2i;
ASN1_ex_i2d *asn1_ex_i2d;
ASN1_ex_print_func *asn1_ex_print;
} ASN1_EXTERN_FUNCS;
typedef struct ASN1_PRIMITIVE_FUNCS_st {
void *app_data;
unsigned long flags;
ASN1_ex_new_func *prim_new;
ASN1_ex_free_func *prim_free;
ASN1_ex_free_func *prim_clear;
ASN1_primitive_c2i *prim_c2i;
ASN1_primitive_i2c *prim_i2c;
ASN1_primitive_print *prim_print;
} ASN1_PRIMITIVE_FUNCS;
/*
* This is the ASN1_AUX structure: it handles various miscellaneous
* requirements. For example the use of reference counts and an informational
* callback. The "informational callback" is called at various points during
* the ASN1 encoding and decoding. It can be used to provide minor
* customisation of the structures used. This is most useful where the
* supplied routines *almost* do the right thing but need some extra help at
* a few points. If the callback returns zero then it is assumed a fatal
* error has occurred and the main operation should be abandoned. If major
* changes in the default behaviour are required then an external type is
* more appropriate.
*/
typedef int ASN1_aux_cb(int operation, ASN1_VALUE **in, const ASN1_ITEM *it,
void *exarg);
typedef struct ASN1_AUX_st {
void *app_data;
int flags;
int ref_offset; /* Offset of reference value */
int ref_lock; /* Lock type to use */
ASN1_aux_cb *asn1_cb;
int enc_offset; /* Offset of ASN1_ENCODING structure */
} ASN1_AUX;
/* For print related callbacks exarg points to this structure */
typedef struct ASN1_PRINT_ARG_st {
BIO *out;
int indent;
const ASN1_PCTX *pctx;
} ASN1_PRINT_ARG;
/* For streaming related callbacks exarg points to this structure */
typedef struct ASN1_STREAM_ARG_st {
/* BIO to stream through */
BIO *out;
/* BIO with filters appended */
BIO *ndef_bio;
/* Streaming I/O boundary */
unsigned char **boundary;
} ASN1_STREAM_ARG;
/* Flags in ASN1_AUX */
/* Use a reference count */
# define ASN1_AFLG_REFCOUNT 1
/* Save the encoding of structure (useful for signatures) */
# define ASN1_AFLG_ENCODING 2
/* The Sequence length is invalid */
# define ASN1_AFLG_BROKEN 4
/* operation values for asn1_cb */
# define ASN1_OP_NEW_PRE 0
# define ASN1_OP_NEW_POST 1
# define ASN1_OP_FREE_PRE 2
# define ASN1_OP_FREE_POST 3
# define ASN1_OP_D2I_PRE 4
# define ASN1_OP_D2I_POST 5
# define ASN1_OP_I2D_PRE 6
# define ASN1_OP_I2D_POST 7
# define ASN1_OP_PRINT_PRE 8
# define ASN1_OP_PRINT_POST 9
# define ASN1_OP_STREAM_PRE 10
# define ASN1_OP_STREAM_POST 11
# define ASN1_OP_DETACHED_PRE 12
# define ASN1_OP_DETACHED_POST 13
/* Macro to implement a primitive type */
# define IMPLEMENT_ASN1_TYPE(stname) IMPLEMENT_ASN1_TYPE_ex(stname, stname, 0)
# define IMPLEMENT_ASN1_TYPE_ex(itname, vname, ex) \
ASN1_ITEM_start(itname) \
ASN1_ITYPE_PRIMITIVE, V_##vname, NULL, 0, NULL, ex, #itname \
ASN1_ITEM_end(itname)
/* Macro to implement a multi string type */
# define IMPLEMENT_ASN1_MSTRING(itname, mask) \
ASN1_ITEM_start(itname) \
ASN1_ITYPE_MSTRING, mask, NULL, 0, NULL, sizeof(ASN1_STRING), #itname \
ASN1_ITEM_end(itname)
# define IMPLEMENT_EXTERN_ASN1(sname, tag, fptrs) \
ASN1_ITEM_start(sname) \
ASN1_ITYPE_EXTERN, \
tag, \
NULL, \
0, \
&fptrs, \
0, \
#sname \
ASN1_ITEM_end(sname)
/* Macro to implement standard functions in terms of ASN1_ITEM structures */
# define IMPLEMENT_ASN1_FUNCTIONS(stname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, stname, stname)
# define IMPLEMENT_ASN1_FUNCTIONS_name(stname, itname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, itname)
# define IMPLEMENT_ASN1_FUNCTIONS_ENCODE_name(stname, itname) \
IMPLEMENT_ASN1_FUNCTIONS_ENCODE_fname(stname, itname, itname)
# define IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(stname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(static, stname, stname, stname)
# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS(stname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, stname, stname)
# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(pre, stname, itname, fname) \
pre stname *fname##_new(void) \
{ \
return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
} \
pre void fname##_free(stname *a) \
{ \
ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
}
# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) \
stname *fname##_new(void) \
{ \
return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
} \
void fname##_free(stname *a) \
{ \
ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
}
# define IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname)
# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
stname *d2i_##fname(stname **a, const unsigned char **in, long len) \
{ \
return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\
} \
int i2d_##fname(stname *a, unsigned char **out) \
{ \
return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\
}
# define IMPLEMENT_ASN1_NDEF_FUNCTION(stname) \
int i2d_##stname##_NDEF(stname *a, unsigned char **out) \
{ \
return ASN1_item_ndef_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(stname));\
}
# define IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(stname) \
static stname *d2i_##stname(stname **a, \
const unsigned char **in, long len) \
{ \
return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, \
ASN1_ITEM_rptr(stname)); \
} \
static int i2d_##stname(stname *a, unsigned char **out) \
{ \
return ASN1_item_i2d((ASN1_VALUE *)a, out, \
ASN1_ITEM_rptr(stname)); \
}
/*
* This includes evil casts to remove const: they will go away when full ASN1
* constification is done.
*/
# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \
stname *d2i_##fname(stname **a, const unsigned char **in, long len) \
{ \
return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\
} \
int i2d_##fname(const stname *a, unsigned char **out) \
{ \
return ASN1_item_i2d((ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\
}
# define IMPLEMENT_ASN1_DUP_FUNCTION(stname) \
stname * stname##_dup(stname *x) \
{ \
return ASN1_item_dup(ASN1_ITEM_rptr(stname), x); \
}
# define IMPLEMENT_ASN1_PRINT_FUNCTION(stname) \
IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, stname, stname)
# define IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, itname, fname) \
int fname##_print_ctx(BIO *out, stname *x, int indent, \
const ASN1_PCTX *pctx) \
{ \
return ASN1_item_print(out, (ASN1_VALUE *)x, indent, \
ASN1_ITEM_rptr(itname), pctx); \
}
# define IMPLEMENT_ASN1_FUNCTIONS_const(name) \
IMPLEMENT_ASN1_FUNCTIONS_const_fname(name, name, name)
# define IMPLEMENT_ASN1_FUNCTIONS_const_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \
IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname)
/* external definitions for primitive types */
DECLARE_ASN1_ITEM(ASN1_BOOLEAN)
DECLARE_ASN1_ITEM(ASN1_TBOOLEAN)
DECLARE_ASN1_ITEM(ASN1_FBOOLEAN)
DECLARE_ASN1_ITEM(ASN1_SEQUENCE)
DECLARE_ASN1_ITEM(CBIGNUM)
DECLARE_ASN1_ITEM(BIGNUM)
DECLARE_ASN1_ITEM(LONG)
DECLARE_ASN1_ITEM(ZLONG)
DEFINE_STACK_OF(ASN1_VALUE)
/* Functions used internally by the ASN1 code */
int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass, char opt,
ASN1_TLC *ctx);
int ASN1_item_ex_i2d(ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
#ifdef __cplusplus
}
#endif
#endif
-98
View File
@@ -1,98 +0,0 @@
/*
* Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#ifndef HEADER_ASYNC_H
# define HEADER_ASYNC_H
#if defined(_WIN32)
# if defined(BASETYPES) || defined(_WINDEF_H)
/* application has to include <windows.h> to use this */
#define OSSL_ASYNC_FD HANDLE
#define OSSL_BAD_ASYNC_FD INVALID_HANDLE_VALUE
# endif
#else
#define OSSL_ASYNC_FD int
#define OSSL_BAD_ASYNC_FD -1
#endif
# ifdef __cplusplus
extern "C" {
# endif
typedef struct async_job_st ASYNC_JOB;
typedef struct async_wait_ctx_st ASYNC_WAIT_CTX;
#define ASYNC_ERR 0
#define ASYNC_NO_JOBS 1
#define ASYNC_PAUSE 2
#define ASYNC_FINISH 3
int ASYNC_init_thread(size_t max_size, size_t init_size);
void ASYNC_cleanup_thread(void);
#ifdef OSSL_ASYNC_FD
ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void);
void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx);
int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD fd,
void *custom_data,
void (*cleanup)(ASYNC_WAIT_CTX *, const void *,
OSSL_ASYNC_FD, void *));
int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD *fd, void **custom_data);
int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd,
size_t *numfds);
int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd,
size_t *numaddfds, OSSL_ASYNC_FD *delfd,
size_t *numdelfds);
int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key);
#endif
int ASYNC_is_capable(void);
int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *ctx, int *ret,
int (*func)(void *), void *args, size_t size);
int ASYNC_pause_job(void);
ASYNC_JOB *ASYNC_get_current_job(void);
ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job);
void ASYNC_block_pause(void);
void ASYNC_unblock_pause(void);
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
int ERR_load_ASYNC_strings(void);
/* Error codes for the ASYNC functions. */
/* Function codes. */
# define ASYNC_F_ASYNC_CTX_NEW 100
# define ASYNC_F_ASYNC_INIT_THREAD 101
# define ASYNC_F_ASYNC_JOB_NEW 102
# define ASYNC_F_ASYNC_PAUSE_JOB 103
# define ASYNC_F_ASYNC_START_FUNC 104
# define ASYNC_F_ASYNC_START_JOB 105
/* Reason codes. */
# define ASYNC_R_FAILED_TO_SET_POOL 101
# define ASYNC_R_FAILED_TO_SWAP_CONTEXT 102
# define ASYNC_R_INIT_FAILED 105
# define ASYNC_R_INVALID_POOL_SIZE 103
# ifdef __cplusplus
}
# endif
#endif
-850
View File
@@ -1,850 +0,0 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BIO_H
# define HEADER_BIO_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_STDIO
# include <stdio.h>
# endif
# include <stdarg.h>
# include <openssl/crypto.h>
# ifndef OPENSSL_NO_SCTP
# include <openssl/e_os2.h>
# endif
#ifdef __cplusplus
extern "C" {
#endif
/* There are the classes of BIOs */
# define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */
# define BIO_TYPE_FILTER 0x0200
# define BIO_TYPE_SOURCE_SINK 0x0400
/* These are the 'types' of BIOs */
# define BIO_TYPE_NONE 0
# define BIO_TYPE_MEM ( 1|BIO_TYPE_SOURCE_SINK)
# define BIO_TYPE_FILE ( 2|BIO_TYPE_SOURCE_SINK)
# define BIO_TYPE_FD ( 4|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_SOCKET ( 5|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_NULL ( 6|BIO_TYPE_SOURCE_SINK)
# define BIO_TYPE_SSL ( 7|BIO_TYPE_FILTER)
# define BIO_TYPE_MD ( 8|BIO_TYPE_FILTER)
# define BIO_TYPE_BUFFER ( 9|BIO_TYPE_FILTER)
# define BIO_TYPE_CIPHER (10|BIO_TYPE_FILTER)
# define BIO_TYPE_BASE64 (11|BIO_TYPE_FILTER)
# define BIO_TYPE_CONNECT (12|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_ACCEPT (13|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_NBIO_TEST (16|BIO_TYPE_FILTER)/* server proxy BIO */
# define BIO_TYPE_NULL_FILTER (17|BIO_TYPE_FILTER)
# define BIO_TYPE_BIO (19|BIO_TYPE_SOURCE_SINK)/* half a BIO pair */
# define BIO_TYPE_LINEBUFFER (20|BIO_TYPE_FILTER)
# define BIO_TYPE_DGRAM (21|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# define BIO_TYPE_ASN1 (22|BIO_TYPE_FILTER)
# define BIO_TYPE_COMP (23|BIO_TYPE_FILTER)
# ifndef OPENSSL_NO_SCTP
# define BIO_TYPE_DGRAM_SCTP (24|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
# endif
#define BIO_TYPE_START 128
/*
* BIO_FILENAME_READ|BIO_CLOSE to open or close on free.
* BIO_set_fp(in,stdin,BIO_NOCLOSE);
*/
# define BIO_NOCLOSE 0x00
# define BIO_CLOSE 0x01
/*
* These are used in the following macros and are passed to BIO_ctrl()
*/
# define BIO_CTRL_RESET 1/* opt - rewind/zero etc */
# define BIO_CTRL_EOF 2/* opt - are we at the eof */
# define BIO_CTRL_INFO 3/* opt - extra tit-bits */
# define BIO_CTRL_SET 4/* man - set the 'IO' type */
# define BIO_CTRL_GET 5/* man - get the 'IO' type */
# define BIO_CTRL_PUSH 6/* opt - internal, used to signify change */
# define BIO_CTRL_POP 7/* opt - internal, used to signify change */
# define BIO_CTRL_GET_CLOSE 8/* man - set the 'close' on free */
# define BIO_CTRL_SET_CLOSE 9/* man - set the 'close' on free */
# define BIO_CTRL_PENDING 10/* opt - is their more data buffered */
# define BIO_CTRL_FLUSH 11/* opt - 'flush' buffered output */
# define BIO_CTRL_DUP 12/* man - extra stuff for 'duped' BIO */
# define BIO_CTRL_WPENDING 13/* opt - number of bytes still to write */
# define BIO_CTRL_SET_CALLBACK 14/* opt - set callback function */
# define BIO_CTRL_GET_CALLBACK 15/* opt - set callback function */
# define BIO_CTRL_SET_FILENAME 30/* BIO_s_file special */
/* dgram BIO stuff */
# define BIO_CTRL_DGRAM_CONNECT 31/* BIO dgram special */
# define BIO_CTRL_DGRAM_SET_CONNECTED 32/* allow for an externally connected
* socket to be passed in */
# define BIO_CTRL_DGRAM_SET_RECV_TIMEOUT 33/* setsockopt, essentially */
# define BIO_CTRL_DGRAM_GET_RECV_TIMEOUT 34/* getsockopt, essentially */
# define BIO_CTRL_DGRAM_SET_SEND_TIMEOUT 35/* setsockopt, essentially */
# define BIO_CTRL_DGRAM_GET_SEND_TIMEOUT 36/* getsockopt, essentially */
# define BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP 37/* flag whether the last */
# define BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP 38/* I/O operation tiemd out */
/* #ifdef IP_MTU_DISCOVER */
# define BIO_CTRL_DGRAM_MTU_DISCOVER 39/* set DF bit on egress packets */
/* #endif */
# define BIO_CTRL_DGRAM_QUERY_MTU 40/* as kernel for current MTU */
# define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47
# define BIO_CTRL_DGRAM_GET_MTU 41/* get cached value for MTU */
# define BIO_CTRL_DGRAM_SET_MTU 42/* set cached value for MTU.
* want to use this if asking
* the kernel fails */
# define BIO_CTRL_DGRAM_MTU_EXCEEDED 43/* check whether the MTU was
* exceed in the previous write
* operation */
# define BIO_CTRL_DGRAM_GET_PEER 46
# define BIO_CTRL_DGRAM_SET_PEER 44/* Destination for the data */
# define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT 45/* Next DTLS handshake timeout
* to adjust socket timeouts */
# define BIO_CTRL_DGRAM_SET_DONT_FRAG 48
# define BIO_CTRL_DGRAM_GET_MTU_OVERHEAD 49
# define BIO_CTRL_DGRAM_SET_PEEK_MODE 50
# ifndef OPENSSL_NO_SCTP
/* SCTP stuff */
# define BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE 50
# define BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY 51
# define BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY 52
# define BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD 53
# define BIO_CTRL_DGRAM_SCTP_GET_SNDINFO 60
# define BIO_CTRL_DGRAM_SCTP_SET_SNDINFO 61
# define BIO_CTRL_DGRAM_SCTP_GET_RCVINFO 62
# define BIO_CTRL_DGRAM_SCTP_SET_RCVINFO 63
# define BIO_CTRL_DGRAM_SCTP_GET_PRINFO 64
# define BIO_CTRL_DGRAM_SCTP_SET_PRINFO 65
# define BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN 70
# endif
/* modifiers */
# define BIO_FP_READ 0x02
# define BIO_FP_WRITE 0x04
# define BIO_FP_APPEND 0x08
# define BIO_FP_TEXT 0x10
# define BIO_FLAGS_READ 0x01
# define BIO_FLAGS_WRITE 0x02
# define BIO_FLAGS_IO_SPECIAL 0x04
# define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
# define BIO_FLAGS_SHOULD_RETRY 0x08
# ifndef BIO_FLAGS_UPLINK
/*
* "UPLINK" flag denotes file descriptors provided by application. It
* defaults to 0, as most platforms don't require UPLINK interface.
*/
# define BIO_FLAGS_UPLINK 0
# endif
# define BIO_FLAGS_BASE64_NO_NL 0x100
/*
* This is used with memory BIOs:
* BIO_FLAGS_MEM_RDONLY means we shouldn't free up or change the data in any way;
* BIO_FLAGS_NONCLEAR_RST means we shouldn't clear data on reset.
*/
# define BIO_FLAGS_MEM_RDONLY 0x200
# define BIO_FLAGS_NONCLEAR_RST 0x400
typedef union bio_addr_st BIO_ADDR;
typedef struct bio_addrinfo_st BIO_ADDRINFO;
int BIO_get_new_index(void);
void BIO_set_flags(BIO *b, int flags);
int BIO_test_flags(const BIO *b, int flags);
void BIO_clear_flags(BIO *b, int flags);
# define BIO_get_flags(b) BIO_test_flags(b, ~(0x0))
# define BIO_set_retry_special(b) \
BIO_set_flags(b, (BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY))
# define BIO_set_retry_read(b) \
BIO_set_flags(b, (BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY))
# define BIO_set_retry_write(b) \
BIO_set_flags(b, (BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY))
/* These are normally used internally in BIOs */
# define BIO_clear_retry_flags(b) \
BIO_clear_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
# define BIO_get_retry_flags(b) \
BIO_test_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
/* These should be used by the application to tell why we should retry */
# define BIO_should_read(a) BIO_test_flags(a, BIO_FLAGS_READ)
# define BIO_should_write(a) BIO_test_flags(a, BIO_FLAGS_WRITE)
# define BIO_should_io_special(a) BIO_test_flags(a, BIO_FLAGS_IO_SPECIAL)
# define BIO_retry_type(a) BIO_test_flags(a, BIO_FLAGS_RWS)
# define BIO_should_retry(a) BIO_test_flags(a, BIO_FLAGS_SHOULD_RETRY)
/*
* The next three are used in conjunction with the BIO_should_io_special()
* condition. After this returns true, BIO *BIO_get_retry_BIO(BIO *bio, int
* *reason); will walk the BIO stack and return the 'reason' for the special
* and the offending BIO. Given a BIO, BIO_get_retry_reason(bio) will return
* the code.
*/
/*
* Returned from the SSL bio when the certificate retrieval code had an error
*/
# define BIO_RR_SSL_X509_LOOKUP 0x01
/* Returned from the connect BIO when a connect would have blocked */
# define BIO_RR_CONNECT 0x02
/* Returned from the accept BIO when an accept would have blocked */
# define BIO_RR_ACCEPT 0x03
/* These are passed by the BIO callback */
# define BIO_CB_FREE 0x01
# define BIO_CB_READ 0x02
# define BIO_CB_WRITE 0x03
# define BIO_CB_PUTS 0x04
# define BIO_CB_GETS 0x05
# define BIO_CB_CTRL 0x06
/*
* The callback is called before and after the underling operation, The
* BIO_CB_RETURN flag indicates if it is after the call
*/
# define BIO_CB_RETURN 0x80
# define BIO_CB_return(a) ((a)|BIO_CB_RETURN)
# define BIO_cb_pre(a) (!((a)&BIO_CB_RETURN))
# define BIO_cb_post(a) ((a)&BIO_CB_RETURN)
typedef long (*BIO_callback_fn)(BIO *b, int oper, const char *argp, int argi,
long argl, long ret);
BIO_callback_fn BIO_get_callback(const BIO *b);
void BIO_set_callback(BIO *b, BIO_callback_fn callback);
char *BIO_get_callback_arg(const BIO *b);
void BIO_set_callback_arg(BIO *b, char *arg);
typedef struct bio_method_st BIO_METHOD;
const char *BIO_method_name(const BIO *b);
int BIO_method_type(const BIO *b);
typedef void bio_info_cb(BIO *, int, const char *, int, long, long);
DEFINE_STACK_OF(BIO)
/* Prefix and suffix callback in ASN1 BIO */
typedef int asn1_ps_func (BIO *b, unsigned char **pbuf, int *plen,
void *parg);
# ifndef OPENSSL_NO_SCTP
/* SCTP parameter structs */
struct bio_dgram_sctp_sndinfo {
uint16_t snd_sid;
uint16_t snd_flags;
uint32_t snd_ppid;
uint32_t snd_context;
};
struct bio_dgram_sctp_rcvinfo {
uint16_t rcv_sid;
uint16_t rcv_ssn;
uint16_t rcv_flags;
uint32_t rcv_ppid;
uint32_t rcv_tsn;
uint32_t rcv_cumtsn;
uint32_t rcv_context;
};
struct bio_dgram_sctp_prinfo {
uint16_t pr_policy;
uint32_t pr_value;
};
# endif
/*
* #define BIO_CONN_get_param_hostname BIO_ctrl
*/
# define BIO_C_SET_CONNECT 100
# define BIO_C_DO_STATE_MACHINE 101
# define BIO_C_SET_NBIO 102
/* # define BIO_C_SET_PROXY_PARAM 103 */
# define BIO_C_SET_FD 104
# define BIO_C_GET_FD 105
# define BIO_C_SET_FILE_PTR 106
# define BIO_C_GET_FILE_PTR 107
# define BIO_C_SET_FILENAME 108
# define BIO_C_SET_SSL 109
# define BIO_C_GET_SSL 110
# define BIO_C_SET_MD 111
# define BIO_C_GET_MD 112
# define BIO_C_GET_CIPHER_STATUS 113
# define BIO_C_SET_BUF_MEM 114
# define BIO_C_GET_BUF_MEM_PTR 115
# define BIO_C_GET_BUFF_NUM_LINES 116
# define BIO_C_SET_BUFF_SIZE 117
# define BIO_C_SET_ACCEPT 118
# define BIO_C_SSL_MODE 119
# define BIO_C_GET_MD_CTX 120
/* # define BIO_C_GET_PROXY_PARAM 121 */
# define BIO_C_SET_BUFF_READ_DATA 122/* data to read first */
# define BIO_C_GET_CONNECT 123
# define BIO_C_GET_ACCEPT 124
# define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125
# define BIO_C_GET_SSL_NUM_RENEGOTIATES 126
# define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127
# define BIO_C_FILE_SEEK 128
# define BIO_C_GET_CIPHER_CTX 129
# define BIO_C_SET_BUF_MEM_EOF_RETURN 130/* return end of input
* value */
# define BIO_C_SET_BIND_MODE 131
# define BIO_C_GET_BIND_MODE 132
# define BIO_C_FILE_TELL 133
# define BIO_C_GET_SOCKS 134
# define BIO_C_SET_SOCKS 135
# define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */
# define BIO_C_GET_WRITE_BUF_SIZE 137
# define BIO_C_MAKE_BIO_PAIR 138
# define BIO_C_DESTROY_BIO_PAIR 139
# define BIO_C_GET_WRITE_GUARANTEE 140
# define BIO_C_GET_READ_REQUEST 141
# define BIO_C_SHUTDOWN_WR 142
# define BIO_C_NREAD0 143
# define BIO_C_NREAD 144
# define BIO_C_NWRITE0 145
# define BIO_C_NWRITE 146
# define BIO_C_RESET_READ_REQUEST 147
# define BIO_C_SET_MD_CTX 148
# define BIO_C_SET_PREFIX 149
# define BIO_C_GET_PREFIX 150
# define BIO_C_SET_SUFFIX 151
# define BIO_C_GET_SUFFIX 152
# define BIO_C_SET_EX_ARG 153
# define BIO_C_GET_EX_ARG 154
# define BIO_C_SET_CONNECT_MODE 155
# define BIO_set_app_data(s,arg) BIO_set_ex_data(s,0,arg)
# define BIO_get_app_data(s) BIO_get_ex_data(s,0)
# define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL)
# ifndef OPENSSL_NO_SOCK
/* IP families we support, for BIO_s_connect() and BIO_s_accept() */
/* Note: the underlying operating system may not support some of them */
# define BIO_FAMILY_IPV4 4
# define BIO_FAMILY_IPV6 6
# define BIO_FAMILY_IPANY 256
/* BIO_s_connect() */
# define BIO_set_conn_hostname(b,name) BIO_ctrl(b,BIO_C_SET_CONNECT,0,(char *)name)
# define BIO_set_conn_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,1,(char *)port)
# define BIO_set_conn_address(b,addr) BIO_ctrl(b,BIO_C_SET_CONNECT,2,(char *)addr)
# define BIO_set_conn_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_CONNECT,3,f)
# define BIO_get_conn_hostname(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,0))
# define BIO_get_conn_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,1))
# define BIO_get_conn_address(b) ((const BIO_ADDR *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,2))
# define BIO_get_conn_ip_family(b) BIO_ctrl(b,BIO_C_GET_CONNECT,3,NULL)
# define BIO_set_conn_mode(b,n) BIO_ctrl(b,BIO_C_SET_CONNECT_MODE,(n),NULL)
/* BIO_s_accept() */
# define BIO_set_accept_name(b,name) BIO_ctrl(b,BIO_C_SET_ACCEPT,0,(char *)name)
# define BIO_set_accept_port(b,port) BIO_ctrl(b,BIO_C_SET_ACCEPT,1,(char *)port)
# define BIO_get_accept_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,0))
# define BIO_get_accept_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,1))
# define BIO_get_peer_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,2))
# define BIO_get_peer_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,3))
/* #define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) */
# define BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,2,(n)?(void *)"a":NULL)
# define BIO_set_accept_bios(b,bio) BIO_ctrl(b,BIO_C_SET_ACCEPT,3,(char *)bio)
# define BIO_set_accept_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_ACCEPT,4,f)
# define BIO_get_accept_ip_family(b) BIO_ctrl(b,BIO_C_GET_ACCEPT,4,NULL)
/* Aliases kept for backward compatibility */
# define BIO_BIND_NORMAL 0
# define BIO_BIND_REUSEADDR BIO_SOCK_REUSEADDR
# define BIO_BIND_REUSEADDR_IF_UNUSED BIO_SOCK_REUSEADDR
# define BIO_set_bind_mode(b,mode) BIO_ctrl(b,BIO_C_SET_BIND_MODE,mode,NULL)
# define BIO_get_bind_mode(b) BIO_ctrl(b,BIO_C_GET_BIND_MODE,0,NULL)
/* BIO_s_accept() and BIO_s_connect() */
# define BIO_do_connect(b) BIO_do_handshake(b)
# define BIO_do_accept(b) BIO_do_handshake(b)
# endif /* OPENSSL_NO_SOCK */
# define BIO_do_handshake(b) BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL)
/* BIO_s_datagram(), BIO_s_fd(), BIO_s_socket(), BIO_s_accept() and BIO_s_connect() */
# define BIO_set_fd(b,fd,c) BIO_int_ctrl(b,BIO_C_SET_FD,c,fd)
# define BIO_get_fd(b,c) BIO_ctrl(b,BIO_C_GET_FD,0,(char *)c)
/* BIO_s_file() */
# define BIO_set_fp(b,fp,c) BIO_ctrl(b,BIO_C_SET_FILE_PTR,c,(char *)fp)
# define BIO_get_fp(b,fpp) BIO_ctrl(b,BIO_C_GET_FILE_PTR,0,(char *)fpp)
/* BIO_s_fd() and BIO_s_file() */
# define BIO_seek(b,ofs) (int)BIO_ctrl(b,BIO_C_FILE_SEEK,ofs,NULL)
# define BIO_tell(b) (int)BIO_ctrl(b,BIO_C_FILE_TELL,0,NULL)
/*
* name is cast to lose const, but might be better to route through a
* function so we can do it safely
*/
# ifdef CONST_STRICT
/*
* If you are wondering why this isn't defined, its because CONST_STRICT is
* purely a compile-time kludge to allow const to be checked.
*/
int BIO_read_filename(BIO *b, const char *name);
# else
# define BIO_read_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_READ,(char *)name)
# endif
# define BIO_write_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_WRITE,name)
# define BIO_append_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_APPEND,name)
# define BIO_rw_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
BIO_CLOSE|BIO_FP_READ|BIO_FP_WRITE,name)
/*
* WARNING WARNING, this ups the reference count on the read bio of the SSL
* structure. This is because the ssl read BIO is now pointed to by the
* next_bio field in the bio. So when you free the BIO, make sure you are
* doing a BIO_free_all() to catch the underlying BIO.
*/
# define BIO_set_ssl(b,ssl,c) BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)ssl)
# define BIO_get_ssl(b,sslp) BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)sslp)
# define BIO_set_ssl_mode(b,client) BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL)
# define BIO_set_ssl_renegotiate_bytes(b,num) \
BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL)
# define BIO_get_num_renegotiates(b) \
BIO_ctrl(b,BIO_C_GET_SSL_NUM_RENEGOTIATES,0,NULL)
# define BIO_set_ssl_renegotiate_timeout(b,seconds) \
BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL)
/* defined in evp.h */
/* #define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,1,(char *)md) */
# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)pp)
# define BIO_set_mem_buf(b,bm,c) BIO_ctrl(b,BIO_C_SET_BUF_MEM,c,(char *)bm)
# define BIO_get_mem_ptr(b,pp) BIO_ctrl(b,BIO_C_GET_BUF_MEM_PTR,0,(char *)pp)
# define BIO_set_mem_eof_return(b,v) \
BIO_ctrl(b,BIO_C_SET_BUF_MEM_EOF_RETURN,v,NULL)
/* For the BIO_f_buffer() type */
# define BIO_get_buffer_num_lines(b) BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL)
# define BIO_set_buffer_size(b,size) BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL)
# define BIO_set_read_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0)
# define BIO_set_write_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1)
# define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf)
/* Don't use the next one unless you know what you are doing :-) */
# define BIO_dup_state(b,ret) BIO_ctrl(b,BIO_CTRL_DUP,0,(char *)(ret))
# define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
# define BIO_eof(b) (int)BIO_ctrl(b,BIO_CTRL_EOF,0,NULL)
# define BIO_set_close(b,c) (int)BIO_ctrl(b,BIO_CTRL_SET_CLOSE,(c),NULL)
# define BIO_get_close(b) (int)BIO_ctrl(b,BIO_CTRL_GET_CLOSE,0,NULL)
# define BIO_pending(b) (int)BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL)
# define BIO_wpending(b) (int)BIO_ctrl(b,BIO_CTRL_WPENDING,0,NULL)
/* ...pending macros have inappropriate return type */
size_t BIO_ctrl_pending(BIO *b);
size_t BIO_ctrl_wpending(BIO *b);
# define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL)
# define BIO_get_info_callback(b,cbp) (int)BIO_ctrl(b,BIO_CTRL_GET_CALLBACK,0, \
cbp)
# define BIO_set_info_callback(b,cb) (int)BIO_callback_ctrl(b,BIO_CTRL_SET_CALLBACK,cb)
/* For the BIO_f_buffer() type */
# define BIO_buffer_get_num_lines(b) BIO_ctrl(b,BIO_CTRL_GET,0,NULL)
/* For BIO_s_bio() */
# define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL)
# define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL)
# define BIO_make_bio_pair(b1,b2) (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2)
# define BIO_destroy_bio_pair(b) (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL)
# define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL)
/* macros with inappropriate type -- but ...pending macros use int too: */
# define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL)
# define BIO_get_read_request(b) (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL)
size_t BIO_ctrl_get_write_guarantee(BIO *b);
size_t BIO_ctrl_get_read_request(BIO *b);
int BIO_ctrl_reset_read_request(BIO *b);
/* ctrl macros for dgram */
# define BIO_ctrl_dgram_connect(b,peer) \
(int)BIO_ctrl(b,BIO_CTRL_DGRAM_CONNECT,0, (char *)peer)
# define BIO_ctrl_set_connected(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_CONNECTED, 0, (char *)peer)
# define BIO_dgram_recv_timedout(b) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)
# define BIO_dgram_send_timedout(b) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP, 0, NULL)
# define BIO_dgram_get_peer(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_PEER, 0, (char *)peer)
# define BIO_dgram_set_peer(b,peer) \
(int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, (char *)peer)
# define BIO_dgram_get_mtu_overhead(b) \
(unsigned int)BIO_ctrl((b), BIO_CTRL_DGRAM_GET_MTU_OVERHEAD, 0, NULL)
#define BIO_get_ex_new_index(l, p, newf, dupf, freef) \
CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_BIO, l, p, newf, dupf, freef)
int BIO_set_ex_data(BIO *bio, int idx, void *data);
void *BIO_get_ex_data(BIO *bio, int idx);
uint64_t BIO_number_read(BIO *bio);
uint64_t BIO_number_written(BIO *bio);
/* For BIO_f_asn1() */
int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix,
asn1_ps_func *prefix_free);
int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix,
asn1_ps_func **pprefix_free);
int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix,
asn1_ps_func *suffix_free);
int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix,
asn1_ps_func **psuffix_free);
const BIO_METHOD *BIO_s_file(void);
BIO *BIO_new_file(const char *filename, const char *mode);
# ifndef OPENSSL_NO_STDIO
BIO *BIO_new_fp(FILE *stream, int close_flag);
# endif
BIO *BIO_new(const BIO_METHOD *type);
int BIO_free(BIO *a);
void BIO_set_data(BIO *a, void *ptr);
void *BIO_get_data(BIO *a);
void BIO_set_init(BIO *a, int init);
int BIO_get_init(BIO *a);
void BIO_set_shutdown(BIO *a, int shut);
int BIO_get_shutdown(BIO *a);
void BIO_vfree(BIO *a);
int BIO_up_ref(BIO *a);
int BIO_read(BIO *b, void *data, int len);
int BIO_gets(BIO *bp, char *buf, int size);
int BIO_write(BIO *b, const void *data, int len);
int BIO_puts(BIO *bp, const char *buf);
int BIO_indent(BIO *b, int indent, int max);
long BIO_ctrl(BIO *bp, int cmd, long larg, void *parg);
long BIO_callback_ctrl(BIO *b, int cmd,
void (*fp) (BIO *, int, const char *, int, long, long));
void *BIO_ptr_ctrl(BIO *bp, int cmd, long larg);
long BIO_int_ctrl(BIO *bp, int cmd, long larg, int iarg);
BIO *BIO_push(BIO *b, BIO *append);
BIO *BIO_pop(BIO *b);
void BIO_free_all(BIO *a);
BIO *BIO_find_type(BIO *b, int bio_type);
BIO *BIO_next(BIO *b);
void BIO_set_next(BIO *b, BIO *next);
BIO *BIO_get_retry_BIO(BIO *bio, int *reason);
int BIO_get_retry_reason(BIO *bio);
void BIO_set_retry_reason(BIO *bio, int reason);
BIO *BIO_dup_chain(BIO *in);
int BIO_nread0(BIO *bio, char **buf);
int BIO_nread(BIO *bio, char **buf, int num);
int BIO_nwrite0(BIO *bio, char **buf);
int BIO_nwrite(BIO *bio, char **buf, int num);
long BIO_debug_callback(BIO *bio, int cmd, const char *argp, int argi,
long argl, long ret);
const BIO_METHOD *BIO_s_mem(void);
const BIO_METHOD *BIO_s_secmem(void);
BIO *BIO_new_mem_buf(const void *buf, int len);
# ifndef OPENSSL_NO_SOCK
const BIO_METHOD *BIO_s_socket(void);
const BIO_METHOD *BIO_s_connect(void);
const BIO_METHOD *BIO_s_accept(void);
# endif
const BIO_METHOD *BIO_s_fd(void);
const BIO_METHOD *BIO_s_log(void);
const BIO_METHOD *BIO_s_bio(void);
const BIO_METHOD *BIO_s_null(void);
const BIO_METHOD *BIO_f_null(void);
const BIO_METHOD *BIO_f_buffer(void);
const BIO_METHOD *BIO_f_linebuffer(void);
const BIO_METHOD *BIO_f_nbio_test(void);
# ifndef OPENSSL_NO_DGRAM
const BIO_METHOD *BIO_s_datagram(void);
int BIO_dgram_non_fatal_error(int error);
BIO *BIO_new_dgram(int fd, int close_flag);
# ifndef OPENSSL_NO_SCTP
const BIO_METHOD *BIO_s_datagram_sctp(void);
BIO *BIO_new_dgram_sctp(int fd, int close_flag);
int BIO_dgram_is_sctp(BIO *bio);
int BIO_dgram_sctp_notification_cb(BIO *b,
void (*handle_notifications) (BIO *bio,
void *context,
void *buf),
void *context);
int BIO_dgram_sctp_wait_for_dry(BIO *b);
int BIO_dgram_sctp_msg_waiting(BIO *b);
# endif
# endif
# ifndef OPENSSL_NO_SOCK
int BIO_sock_should_retry(int i);
int BIO_sock_non_fatal_error(int error);
# endif
int BIO_fd_should_retry(int i);
int BIO_fd_non_fatal_error(int error);
int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u),
void *u, const char *s, int len);
int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u),
void *u, const char *s, int len, int indent);
int BIO_dump(BIO *b, const char *bytes, int len);
int BIO_dump_indent(BIO *b, const char *bytes, int len, int indent);
# ifndef OPENSSL_NO_STDIO
int BIO_dump_fp(FILE *fp, const char *s, int len);
int BIO_dump_indent_fp(FILE *fp, const char *s, int len, int indent);
# endif
int BIO_hex_string(BIO *out, int indent, int width, unsigned char *data,
int datalen);
# ifndef OPENSSL_NO_SOCK
BIO_ADDR *BIO_ADDR_new(void);
int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
const void *where, size_t wherelen, unsigned short port);
void BIO_ADDR_free(BIO_ADDR *);
void BIO_ADDR_clear(BIO_ADDR *ap);
int BIO_ADDR_family(const BIO_ADDR *ap);
int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l);
unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap);
char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric);
char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric);
char *BIO_ADDR_path_string(const BIO_ADDR *ap);
const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai);
int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai);
const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai);
void BIO_ADDRINFO_free(BIO_ADDRINFO *bai);
enum BIO_hostserv_priorities {
BIO_PARSE_PRIO_HOST, BIO_PARSE_PRIO_SERV
};
int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
enum BIO_hostserv_priorities hostserv_prio);
enum BIO_lookup_type {
BIO_LOOKUP_CLIENT, BIO_LOOKUP_SERVER
};
int BIO_lookup(const char *host, const char *service,
enum BIO_lookup_type lookup_type,
int family, int socktype, BIO_ADDRINFO **res);
int BIO_sock_error(int sock);
int BIO_socket_ioctl(int fd, long type, void *arg);
int BIO_socket_nbio(int fd, int mode);
int BIO_sock_init(void);
# if OPENSSL_API_COMPAT < 0x10100000L
# define BIO_sock_cleanup() while(0) continue
# endif
int BIO_set_tcp_ndelay(int sock, int turn_on);
DEPRECATEDIN_1_1_0(struct hostent *BIO_gethostbyname(const char *name))
DEPRECATEDIN_1_1_0(int BIO_get_port(const char *str, unsigned short *port_ptr))
DEPRECATEDIN_1_1_0(int BIO_get_host_ip(const char *str, unsigned char *ip))
DEPRECATEDIN_1_1_0(int BIO_get_accept_socket(char *host_port, int mode))
DEPRECATEDIN_1_1_0(int BIO_accept(int sock, char **ip_port))
union BIO_sock_info_u {
BIO_ADDR *addr;
};
enum BIO_sock_info_type {
BIO_SOCK_INFO_ADDRESS
};
int BIO_sock_info(int sock,
enum BIO_sock_info_type type, union BIO_sock_info_u *info);
# define BIO_SOCK_REUSEADDR 0x01
# define BIO_SOCK_V6_ONLY 0x02
# define BIO_SOCK_KEEPALIVE 0x04
# define BIO_SOCK_NONBLOCK 0x08
# define BIO_SOCK_NODELAY 0x10
int BIO_socket(int domain, int socktype, int protocol, int options);
int BIO_connect(int sock, const BIO_ADDR *addr, int options);
int BIO_listen(int sock, const BIO_ADDR *addr, int options);
int BIO_accept_ex(int accept_sock, BIO_ADDR *addr, int options);
int BIO_closesocket(int sock);
BIO *BIO_new_socket(int sock, int close_flag);
BIO *BIO_new_connect(const char *host_port);
BIO *BIO_new_accept(const char *host_port);
# endif /* OPENSSL_NO_SOCK*/
BIO *BIO_new_fd(int fd, int close_flag);
int BIO_new_bio_pair(BIO **bio1, size_t writebuf1,
BIO **bio2, size_t writebuf2);
/*
* If successful, returns 1 and in *bio1, *bio2 two BIO pair endpoints.
* Otherwise returns 0 and sets *bio1 and *bio2 to NULL. Size 0 uses default
* value.
*/
void BIO_copy_next_retry(BIO *b);
/*
* long BIO_ghbn_ctrl(int cmd,int iarg,char *parg);
*/
# ifdef __GNUC__
# define __bio_h__attr__ __attribute__
# else
# define __bio_h__attr__(x)
# endif
int BIO_printf(BIO *bio, const char *format, ...)
__bio_h__attr__((__format__(__printf__, 2, 3)));
int BIO_vprintf(BIO *bio, const char *format, va_list args)
__bio_h__attr__((__format__(__printf__, 2, 0)));
int BIO_snprintf(char *buf, size_t n, const char *format, ...)
__bio_h__attr__((__format__(__printf__, 3, 4)));
int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
__bio_h__attr__((__format__(__printf__, 3, 0)));
# undef __bio_h__attr__
BIO_METHOD *BIO_meth_new(int type, const char *name);
void BIO_meth_free(BIO_METHOD *biom);
int (*BIO_meth_get_write(BIO_METHOD *biom)) (BIO *, const char *, int);
int BIO_meth_set_write(BIO_METHOD *biom,
int (*write) (BIO *, const char *, int));
int (*BIO_meth_get_read(BIO_METHOD *biom)) (BIO *, char *, int);
int BIO_meth_set_read(BIO_METHOD *biom,
int (*read) (BIO *, char *, int));
int (*BIO_meth_get_puts(BIO_METHOD *biom)) (BIO *, const char *);
int BIO_meth_set_puts(BIO_METHOD *biom,
int (*puts) (BIO *, const char *));
int (*BIO_meth_get_gets(BIO_METHOD *biom)) (BIO *, char *, int);
int BIO_meth_set_gets(BIO_METHOD *biom,
int (*gets) (BIO *, char *, int));
long (*BIO_meth_get_ctrl(BIO_METHOD *biom)) (BIO *, int, long, void *);
int BIO_meth_set_ctrl(BIO_METHOD *biom,
long (*ctrl) (BIO *, int, long, void *));
int (*BIO_meth_get_create(BIO_METHOD *bion)) (BIO *);
int BIO_meth_set_create(BIO_METHOD *biom, int (*create) (BIO *));
int (*BIO_meth_get_destroy(BIO_METHOD *biom)) (BIO *);
int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy) (BIO *));
long (*BIO_meth_get_callback_ctrl(BIO_METHOD *biom))
(BIO *, int, bio_info_cb *);
int BIO_meth_set_callback_ctrl(BIO_METHOD *biom,
long (*callback_ctrl) (BIO *, int,
bio_info_cb *));
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
int ERR_load_BIO_strings(void);
/* Error codes for the BIO functions. */
/* Function codes. */
# define BIO_F_ACPT_STATE 100
# define BIO_F_ADDR_STRINGS 134
# define BIO_F_BIO_ACCEPT 101
# define BIO_F_BIO_ACCEPT_EX 137
# define BIO_F_BIO_ADDR_NEW 144
# define BIO_F_BIO_CALLBACK_CTRL 131
# define BIO_F_BIO_CONNECT 138
# define BIO_F_BIO_CTRL 103
# define BIO_F_BIO_GETS 104
# define BIO_F_BIO_GET_HOST_IP 106
# define BIO_F_BIO_GET_NEW_INDEX 102
# define BIO_F_BIO_GET_PORT 107
# define BIO_F_BIO_LISTEN 139
# define BIO_F_BIO_LOOKUP 135
# define BIO_F_BIO_MAKE_PAIR 121
# define BIO_F_BIO_NEW 108
# define BIO_F_BIO_NEW_FILE 109
# define BIO_F_BIO_NEW_MEM_BUF 126
# define BIO_F_BIO_NREAD 123
# define BIO_F_BIO_NREAD0 124
# define BIO_F_BIO_NWRITE 125
# define BIO_F_BIO_NWRITE0 122
# define BIO_F_BIO_PARSE_HOSTSERV 136
# define BIO_F_BIO_PUTS 110
# define BIO_F_BIO_READ 111
# define BIO_F_BIO_SOCKET 140
# define BIO_F_BIO_SOCKET_NBIO 142
# define BIO_F_BIO_SOCK_INFO 141
# define BIO_F_BIO_SOCK_INIT 112
# define BIO_F_BIO_WRITE 113
# define BIO_F_BUFFER_CTRL 114
# define BIO_F_CONN_CTRL 127
# define BIO_F_CONN_STATE 115
# define BIO_F_DGRAM_SCTP_READ 132
# define BIO_F_DGRAM_SCTP_WRITE 133
# define BIO_F_FILE_CTRL 116
# define BIO_F_FILE_READ 130
# define BIO_F_LINEBUFFER_CTRL 129
# define BIO_F_MEM_WRITE 117
# define BIO_F_SSL_NEW 118
/* Reason codes. */
# define BIO_R_ACCEPT_ERROR 100
# define BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET 141
# define BIO_R_AMBIGUOUS_HOST_OR_SERVICE 129
# define BIO_R_BAD_FOPEN_MODE 101
# define BIO_R_BROKEN_PIPE 124
# define BIO_R_CONNECT_ERROR 103
# define BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET 107
# define BIO_R_GETSOCKNAME_ERROR 132
# define BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS 133
# define BIO_R_GETTING_SOCKTYPE 134
# define BIO_R_INVALID_ARGUMENT 125
# define BIO_R_INVALID_SOCKET 135
# define BIO_R_IN_USE 123
# define BIO_R_LISTEN_V6_ONLY 136
# define BIO_R_LOOKUP_RETURNED_NOTHING 142
# define BIO_R_MALFORMED_HOST_OR_SERVICE 130
# define BIO_R_NBIO_CONNECT_ERROR 110
# define BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED 143
# define BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED 144
# define BIO_R_NO_PORT_DEFINED 113
# define BIO_R_NO_SUCH_FILE 128
# define BIO_R_NULL_PARAMETER 115
# define BIO_R_UNABLE_TO_BIND_SOCKET 117
# define BIO_R_UNABLE_TO_CREATE_SOCKET 118
# define BIO_R_UNABLE_TO_KEEPALIVE 137
# define BIO_R_UNABLE_TO_LISTEN_SOCKET 119
# define BIO_R_UNABLE_TO_NODELAY 138
# define BIO_R_UNABLE_TO_REUSEADDR 139
# define BIO_R_UNAVAILABLE_IP_FAMILY 145
# define BIO_R_UNINITIALIZED 120
# define BIO_R_UNKNOWN_INFO_TYPE 140
# define BIO_R_UNSUPPORTED_IP_FAMILY 146
# define BIO_R_UNSUPPORTED_METHOD 121
# define BIO_R_UNSUPPORTED_PROTOCOL_FAMILY 131
# define BIO_R_WRITE_TO_READ_ONLY_BIO 126
# define BIO_R_WSASTARTUP 122
# ifdef __cplusplus
}
# endif
#endif
-61
View File
@@ -1,61 +0,0 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BLOWFISH_H
# define HEADER_BLOWFISH_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_BF
# include <openssl/e_os2.h>
# ifdef __cplusplus
extern "C" {
# endif
# define BF_ENCRYPT 1
# define BF_DECRYPT 0
/*-
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* ! BF_LONG has to be at least 32 bits wide. !
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*/
# define BF_LONG unsigned int
# define BF_ROUNDS 16
# define BF_BLOCK 8
typedef struct bf_key_st {
BF_LONG P[BF_ROUNDS + 2];
BF_LONG S[4 * 256];
} BF_KEY;
void BF_set_key(BF_KEY *key, int len, const unsigned char *data);
void BF_encrypt(BF_LONG *data, const BF_KEY *key);
void BF_decrypt(BF_LONG *data, const BF_KEY *key);
void BF_ecb_encrypt(const unsigned char *in, unsigned char *out,
const BF_KEY *key, int enc);
void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length,
const BF_KEY *schedule, unsigned char *ivec, int enc);
void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, const BF_KEY *schedule,
unsigned char *ivec, int *num, int enc);
void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out,
long length, const BF_KEY *schedule,
unsigned char *ivec, int *num);
const char *BF_options(void);
# ifdef __cplusplus
}
# endif
# endif
#endif
-575
View File
@@ -1,575 +0,0 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* Portions of the attached software ("Contribution") are developed by
* SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
*
* The Contribution is licensed pursuant to the Eric Young open source
* license provided above.
*
* The binary polynomial arithmetic software is originally written by
* Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
*
*/
#ifndef HEADER_BN_H
# define HEADER_BN_H
# include <openssl/e_os2.h>
# ifndef OPENSSL_NO_STDIO
# include <stdio.h>
# endif
# include <openssl/opensslconf.h>
# include <openssl/ossl_typ.h>
# include <openssl/crypto.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* 64-bit processor with LP64 ABI
*/
# ifdef SIXTY_FOUR_BIT_LONG
# define BN_ULONG unsigned long
# define BN_BYTES 8
# endif
/*
* 64-bit processor other than LP64 ABI
*/
# ifdef SIXTY_FOUR_BIT
# define BN_ULONG unsigned long long
# define BN_BYTES 8
# endif
# ifdef THIRTY_TWO_BIT
# define BN_ULONG unsigned int
# define BN_BYTES 4
# endif
# define BN_BITS2 (BN_BYTES * 8)
# define BN_BITS (BN_BITS2 * 2)
# define BN_TBIT ((BN_ULONG)1 << (BN_BITS2 - 1))
# define BN_FLG_MALLOCED 0x01
# define BN_FLG_STATIC_DATA 0x02
/*
* avoid leaking exponent information through timing,
* BN_mod_exp_mont() will call BN_mod_exp_mont_consttime,
* BN_div() will call BN_div_no_branch,
* BN_mod_inverse() will call BN_mod_inverse_no_branch.
*/
# define BN_FLG_CONSTTIME 0x04
# define BN_FLG_SECURE 0x08
# if OPENSSL_API_COMPAT < 0x00908000L
/* deprecated name for the flag */
# define BN_FLG_EXP_CONSTTIME BN_FLG_CONSTTIME
# define BN_FLG_FREE 0x8000 /* used for debugging */
# endif
void BN_set_flags(BIGNUM *b, int n);
int BN_get_flags(const BIGNUM *b, int n);
/* Values for |top| in BN_rand() */
#define BN_RAND_TOP_ANY -1
#define BN_RAND_TOP_ONE 0
#define BN_RAND_TOP_TWO 1
/* Values for |bottom| in BN_rand() */
#define BN_RAND_BOTTOM_ANY 0
#define BN_RAND_BOTTOM_ODD 1
/*
* get a clone of a BIGNUM with changed flags, for *temporary* use only (the
* two BIGNUMs cannot be used in parallel!). Also only for *read only* use. The
* value |dest| should be a newly allocated BIGNUM obtained via BN_new() that
* has not been otherwise initialised or used.
*/
void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags);
/* Wrapper function to make using BN_GENCB easier */
int BN_GENCB_call(BN_GENCB *cb, int a, int b);
BN_GENCB *BN_GENCB_new(void);
void BN_GENCB_free(BN_GENCB *cb);
/* Populate a BN_GENCB structure with an "old"-style callback */
void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback) (int, int, void *),
void *cb_arg);
/* Populate a BN_GENCB structure with a "new"-style callback */
void BN_GENCB_set(BN_GENCB *gencb, int (*callback) (int, int, BN_GENCB *),
void *cb_arg);
void *BN_GENCB_get_arg(BN_GENCB *cb);
# define BN_prime_checks 0 /* default: select number of iterations based
* on the size of the number */
/*
* number of Miller-Rabin iterations for an error rate of less than 2^-80 for
* random 'b'-bit input, b >= 100 (taken from table 4.4 in the Handbook of
* Applied Cryptography [Menezes, van Oorschot, Vanstone; CRC Press 1996];
* original paper: Damgaard, Landrock, Pomerance: Average case error
* estimates for the strong probable prime test. -- Math. Comp. 61 (1993)
* 177-194)
*/
# define BN_prime_checks_for_size(b) ((b) >= 1300 ? 2 : \
(b) >= 850 ? 3 : \
(b) >= 650 ? 4 : \
(b) >= 550 ? 5 : \
(b) >= 450 ? 6 : \
(b) >= 400 ? 7 : \
(b) >= 350 ? 8 : \
(b) >= 300 ? 9 : \
(b) >= 250 ? 12 : \
(b) >= 200 ? 15 : \
(b) >= 150 ? 18 : \
/* b >= 100 */ 27)
# define BN_num_bytes(a) ((BN_num_bits(a)+7)/8)
int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w);
int BN_is_zero(const BIGNUM *a);
int BN_is_one(const BIGNUM *a);
int BN_is_word(const BIGNUM *a, const BN_ULONG w);
int BN_is_odd(const BIGNUM *a);
# define BN_one(a) (BN_set_word((a),1))
void BN_zero_ex(BIGNUM *a);
# if OPENSSL_API_COMPAT >= 0x00908000L
# define BN_zero(a) BN_zero_ex(a)
# else
# define BN_zero(a) (BN_set_word((a),0))
# endif
const BIGNUM *BN_value_one(void);
char *BN_options(void);
BN_CTX *BN_CTX_new(void);
BN_CTX *BN_CTX_secure_new(void);
void BN_CTX_free(BN_CTX *c);
void BN_CTX_start(BN_CTX *ctx);
BIGNUM *BN_CTX_get(BN_CTX *ctx);
void BN_CTX_end(BN_CTX *ctx);
int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
int BN_rand_range(BIGNUM *rnd, const BIGNUM *range);
int BN_pseudo_rand_range(BIGNUM *rnd, const BIGNUM *range);
int BN_num_bits(const BIGNUM *a);
int BN_num_bits_word(BN_ULONG l);
int BN_security_bits(int L, int N);
BIGNUM *BN_new(void);
BIGNUM *BN_secure_new(void);
void BN_clear_free(BIGNUM *a);
BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b);
void BN_swap(BIGNUM *a, BIGNUM *b);
BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2bin(const BIGNUM *a, unsigned char *to);
int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen);
BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen);
BIGNUM *BN_mpi2bn(const unsigned char *s, int len, BIGNUM *ret);
int BN_bn2mpi(const BIGNUM *a, unsigned char *to);
int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
/** BN_set_negative sets sign of a BIGNUM
* \param b pointer to the BIGNUM object
* \param n 0 if the BIGNUM b should be positive and a value != 0 otherwise
*/
void BN_set_negative(BIGNUM *b, int n);
/** BN_is_negative returns 1 if the BIGNUM is negative
* \param a pointer to the BIGNUM object
* \return 1 if a < 0 and 0 otherwise
*/
int BN_is_negative(const BIGNUM *b);
int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
BN_CTX *ctx);
# define BN_mod(rem,m,d,ctx) BN_div(NULL,(rem),(m),(d),(ctx))
int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx);
int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *m);
int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *m);
int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m);
int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
BN_CTX *ctx);
int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m);
BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w);
BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w);
int BN_mul_word(BIGNUM *a, BN_ULONG w);
int BN_add_word(BIGNUM *a, BN_ULONG w);
int BN_sub_word(BIGNUM *a, BN_ULONG w);
int BN_set_word(BIGNUM *a, BN_ULONG w);
BN_ULONG BN_get_word(const BIGNUM *a);
int BN_cmp(const BIGNUM *a, const BIGNUM *b);
void BN_free(BIGNUM *a);
int BN_is_bit_set(const BIGNUM *a, int n);
int BN_lshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_lshift1(BIGNUM *r, const BIGNUM *a);
int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
int BN_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx,
BN_MONT_CTX *in_mont);
int BN_mod_exp_mont_word(BIGNUM *r, BN_ULONG a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int BN_mod_exp2_mont(BIGNUM *r, const BIGNUM *a1, const BIGNUM *p1,
const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
BN_CTX *ctx, BN_MONT_CTX *m_ctx);
int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
int BN_mask_bits(BIGNUM *a, int n);
# ifndef OPENSSL_NO_STDIO
int BN_print_fp(FILE *fp, const BIGNUM *a);
# endif
int BN_print(BIO *bio, const BIGNUM *a);
int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx);
int BN_rshift(BIGNUM *r, const BIGNUM *a, int n);
int BN_rshift1(BIGNUM *r, const BIGNUM *a);
void BN_clear(BIGNUM *a);
BIGNUM *BN_dup(const BIGNUM *a);
int BN_ucmp(const BIGNUM *a, const BIGNUM *b);
int BN_set_bit(BIGNUM *a, int n);
int BN_clear_bit(BIGNUM *a, int n);
char *BN_bn2hex(const BIGNUM *a);
char *BN_bn2dec(const BIGNUM *a);
int BN_hex2bn(BIGNUM **a, const char *str);
int BN_dec2bn(BIGNUM **a, const char *str);
int BN_asc2bn(BIGNUM **a, const char *str);
int BN_gcd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); /* returns
* -2 for
* error */
BIGNUM *BN_mod_inverse(BIGNUM *ret,
const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
BIGNUM *BN_mod_sqrt(BIGNUM *ret,
const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
void BN_consttime_swap(BN_ULONG swap, BIGNUM *a, BIGNUM *b, int nwords);
/* Deprecated versions */
DEPRECATEDIN_0_9_8(BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe,
const BIGNUM *add,
const BIGNUM *rem,
void (*callback) (int, int,
void *),
void *cb_arg))
DEPRECATEDIN_0_9_8(int
BN_is_prime(const BIGNUM *p, int nchecks,
void (*callback) (int, int, void *),
BN_CTX *ctx, void *cb_arg))
DEPRECATEDIN_0_9_8(int
BN_is_prime_fasttest(const BIGNUM *p, int nchecks,
void (*callback) (int, int, void *),
BN_CTX *ctx, void *cb_arg,
int do_trial_division))
/* Newer versions */
int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add,
const BIGNUM *rem, BN_GENCB *cb);
int BN_is_prime_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx, BN_GENCB *cb);
int BN_is_prime_fasttest_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx,
int do_trial_division, BN_GENCB *cb);
int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx);
int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2,
const BIGNUM *Xp, const BIGNUM *Xp1,
const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx,
BN_GENCB *cb);
int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1,
BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e,
BN_CTX *ctx, BN_GENCB *cb);
BN_MONT_CTX *BN_MONT_CTX_new(void);
int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
BN_MONT_CTX *mont, BN_CTX *ctx);
int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
BN_CTX *ctx);
void BN_MONT_CTX_free(BN_MONT_CTX *mont);
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx);
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from);
BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock,
const BIGNUM *mod, BN_CTX *ctx);
/* BN_BLINDING flags */
# define BN_BLINDING_NO_UPDATE 0x00000001
# define BN_BLINDING_NO_RECREATE 0x00000002
BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod);
void BN_BLINDING_free(BN_BLINDING *b);
int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *);
int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b,
BN_CTX *);
int BN_BLINDING_is_current_thread(BN_BLINDING *b);
void BN_BLINDING_set_current_thread(BN_BLINDING *b);
int BN_BLINDING_lock(BN_BLINDING *b);
int BN_BLINDING_unlock(BN_BLINDING *b);
unsigned long BN_BLINDING_get_flags(const BN_BLINDING *);
void BN_BLINDING_set_flags(BN_BLINDING *, unsigned long);
BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b,
const BIGNUM *e, BIGNUM *m, BN_CTX *ctx,
int (*bn_mod_exp) (BIGNUM *r,
const BIGNUM *a,
const BIGNUM *p,
const BIGNUM *m,
BN_CTX *ctx,
BN_MONT_CTX *m_ctx),
BN_MONT_CTX *m_ctx);
DEPRECATEDIN_0_9_8(void BN_set_params(int mul, int high, int low, int mont))
DEPRECATEDIN_0_9_8(int BN_get_params(int which)) /* 0, mul, 1 high, 2 low, 3
* mont */
BN_RECP_CTX *BN_RECP_CTX_new(void);
void BN_RECP_CTX_free(BN_RECP_CTX *recp);
int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *rdiv, BN_CTX *ctx);
int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y,
BN_RECP_CTX *recp, BN_CTX *ctx);
int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
const BIGNUM *m, BN_CTX *ctx);
int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
BN_RECP_CTX *recp, BN_CTX *ctx);
# ifndef OPENSSL_NO_EC2M
/*
* Functions for arithmetic over binary polynomials represented by BIGNUMs.
* The BIGNUM::neg property of BIGNUMs representing binary polynomials is
* ignored. Note that input arguments are not const so that their bit arrays
* can be expanded to the appropriate size if needed.
*/
/*
* r = a + b
*/
int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
# define BN_GF2m_sub(r, a, b) BN_GF2m_add(r, a, b)
/*
* r=a mod p
*/
int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p);
/* r = (a * b) mod p */
int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *p, BN_CTX *ctx);
/* r = (a * a) mod p */
int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
/* r = (1 / b) mod p */
int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx);
/* r = (a / b) mod p */
int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *p, BN_CTX *ctx);
/* r = (a ^ b) mod p */
int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const BIGNUM *p, BN_CTX *ctx);
/* r = sqrt(a) mod p */
int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
BN_CTX *ctx);
/* r^2 + r = a mod p */
int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
BN_CTX *ctx);
# define BN_GF2m_cmp(a, b) BN_ucmp((a), (b))
/*-
* Some functions allow for representation of the irreducible polynomials
* as an unsigned int[], say p. The irreducible f(t) is then of the form:
* t^p[0] + t^p[1] + ... + t^p[k]
* where m = p[0] > p[1] > ... > p[k] = 0.
*/
/* r = a mod p */
int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[]);
/* r = (a * b) mod p */
int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const int p[], BN_CTX *ctx);
/* r = (a * a) mod p */
int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[],
BN_CTX *ctx);
/* r = (1 / b) mod p */
int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *b, const int p[],
BN_CTX *ctx);
/* r = (a / b) mod p */
int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const int p[], BN_CTX *ctx);
/* r = (a ^ b) mod p */
int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
const int p[], BN_CTX *ctx);
/* r = sqrt(a) mod p */
int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a,
const int p[], BN_CTX *ctx);
/* r^2 + r = a mod p */
int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a,
const int p[], BN_CTX *ctx);
int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max);
int BN_GF2m_arr2poly(const int p[], BIGNUM *a);
# endif
/*
* faster mod functions for the 'NIST primes' 0 <= a < p^2
*/
int BN_nist_mod_192(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_224(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_256(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_384(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
int BN_nist_mod_521(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
const BIGNUM *BN_get0_nist_prime_192(void);
const BIGNUM *BN_get0_nist_prime_224(void);
const BIGNUM *BN_get0_nist_prime_256(void);
const BIGNUM *BN_get0_nist_prime_384(void);
const BIGNUM *BN_get0_nist_prime_521(void);
int (*BN_nist_mod_func(const BIGNUM *p)) (BIGNUM *r, const BIGNUM *a,
const BIGNUM *field, BN_CTX *ctx);
int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
const BIGNUM *priv, const unsigned char *message,
size_t message_len, BN_CTX *ctx);
/* Primes from RFC 2409 */
BIGNUM *BN_get_rfc2409_prime_768(BIGNUM *bn);
BIGNUM *BN_get_rfc2409_prime_1024(BIGNUM *bn);
/* Primes from RFC 3526 */
BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *bn);
BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *bn);
# if OPENSSL_API_COMPAT < 0x10100000L
# define get_rfc2409_prime_768 BN_get_rfc2409_prime_768
# define get_rfc2409_prime_1024 BN_get_rfc2409_prime_1024
# define get_rfc3526_prime_1536 BN_get_rfc3526_prime_1536
# define get_rfc3526_prime_2048 BN_get_rfc3526_prime_2048
# define get_rfc3526_prime_3072 BN_get_rfc3526_prime_3072
# define get_rfc3526_prime_4096 BN_get_rfc3526_prime_4096
# define get_rfc3526_prime_6144 BN_get_rfc3526_prime_6144
# define get_rfc3526_prime_8192 BN_get_rfc3526_prime_8192
# endif
int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom);
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
int ERR_load_BN_strings(void);
/* Error codes for the BN functions. */
/* Function codes. */
# define BN_F_BNRAND 127
# define BN_F_BN_BLINDING_CONVERT_EX 100
# define BN_F_BN_BLINDING_CREATE_PARAM 128
# define BN_F_BN_BLINDING_INVERT_EX 101
# define BN_F_BN_BLINDING_NEW 102
# define BN_F_BN_BLINDING_UPDATE 103
# define BN_F_BN_BN2DEC 104
# define BN_F_BN_BN2HEX 105
# define BN_F_BN_COMPUTE_WNAF 142
# define BN_F_BN_CTX_GET 116
# define BN_F_BN_CTX_NEW 106
# define BN_F_BN_CTX_START 129
# define BN_F_BN_DIV 107
# define BN_F_BN_DIV_RECP 130
# define BN_F_BN_EXP 123
# define BN_F_BN_EXPAND_INTERNAL 120
# define BN_F_BN_GENCB_NEW 143
# define BN_F_BN_GENERATE_DSA_NONCE 140
# define BN_F_BN_GENERATE_PRIME_EX 141
# define BN_F_BN_GF2M_MOD 131
# define BN_F_BN_GF2M_MOD_EXP 132
# define BN_F_BN_GF2M_MOD_MUL 133
# define BN_F_BN_GF2M_MOD_SOLVE_QUAD 134
# define BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR 135
# define BN_F_BN_GF2M_MOD_SQR 136
# define BN_F_BN_GF2M_MOD_SQRT 137
# define BN_F_BN_LSHIFT 145
# define BN_F_BN_MOD_EXP2_MONT 118
# define BN_F_BN_MOD_EXP_MONT 109
# define BN_F_BN_MOD_EXP_MONT_CONSTTIME 124
# define BN_F_BN_MOD_EXP_MONT_WORD 117
# define BN_F_BN_MOD_EXP_RECP 125
# define BN_F_BN_MOD_EXP_SIMPLE 126
# define BN_F_BN_MOD_INVERSE 110
# define BN_F_BN_MOD_INVERSE_NO_BRANCH 139
# define BN_F_BN_MOD_LSHIFT_QUICK 119
# define BN_F_BN_MOD_SQRT 121
# define BN_F_BN_MPI2BN 112
# define BN_F_BN_NEW 113
# define BN_F_BN_RAND 114
# define BN_F_BN_RAND_RANGE 122
# define BN_F_BN_RSHIFT 146
# define BN_F_BN_SET_WORDS 144
# define BN_F_BN_USUB 115
/* Reason codes. */
# define BN_R_ARG2_LT_ARG3 100
# define BN_R_BAD_RECIPROCAL 101
# define BN_R_BIGNUM_TOO_LONG 114
# define BN_R_BITS_TOO_SMALL 118
# define BN_R_CALLED_WITH_EVEN_MODULUS 102
# define BN_R_DIV_BY_ZERO 103
# define BN_R_ENCODING_ERROR 104
# define BN_R_EXPAND_ON_STATIC_BIGNUM_DATA 105
# define BN_R_INPUT_NOT_REDUCED 110
# define BN_R_INVALID_LENGTH 106
# define BN_R_INVALID_RANGE 115
# define BN_R_INVALID_SHIFT 119
# define BN_R_NOT_A_SQUARE 111
# define BN_R_NOT_INITIALIZED 107
# define BN_R_NO_INVERSE 108
# define BN_R_NO_SOLUTION 116
# define BN_R_PRIVATE_KEY_TOO_LARGE 117
# define BN_R_P_IS_NOT_PRIME 112
# define BN_R_TOO_MANY_ITERATIONS 113
# define BN_R_TOO_MANY_TEMPORARY_VARIABLES 109
# ifdef __cplusplus
}
# endif
#endif
-76
View File
@@ -1,76 +0,0 @@
/*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_BUFFER_H
# define HEADER_BUFFER_H
# include <openssl/ossl_typ.h>
# ifndef HEADER_CRYPTO_H
# include <openssl/crypto.h>
# endif
#ifdef __cplusplus
extern "C" {
#endif
# include <stddef.h>
# if !defined(NO_SYS_TYPES_H)
# include <sys/types.h>
# endif
/*
* These names are outdated as of OpenSSL 1.1; a future release
* will move them to be deprecated.
*/
# define BUF_strdup(s) OPENSSL_strdup(s)
# define BUF_strndup(s, size) OPENSSL_strndup(s, size)
# define BUF_memdup(data, size) OPENSSL_memdup(data, size)
# define BUF_strlcpy(dst, src, size) OPENSSL_strlcpy(dst, src, size)
# define BUF_strlcat(dst, src, size) OPENSSL_strlcat(dst, src, size)
# define BUF_strnlen(str, maxlen) OPENSSL_strnlen(str, maxlen)
struct buf_mem_st {
size_t length; /* current number of bytes */
char *data;
size_t max; /* size of buffer */
unsigned long flags;
};
# define BUF_MEM_FLAG_SECURE 0x01
BUF_MEM *BUF_MEM_new(void);
BUF_MEM *BUF_MEM_new_ex(unsigned long flags);
void BUF_MEM_free(BUF_MEM *a);
size_t BUF_MEM_grow(BUF_MEM *str, size_t len);
size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len);
void BUF_reverse(unsigned char *out, const unsigned char *in, size_t siz);
/* BEGIN ERROR CODES */
/*
* The following lines are auto generated by the script mkerr.pl. Any changes
* made after this point may be overwritten when the script is next run.
*/
int ERR_load_BUF_strings(void);
/* Error codes for the BUF functions. */
/* Function codes. */
# define BUF_F_BUF_MEM_GROW 100
# define BUF_F_BUF_MEM_GROW_CLEAN 105
# define BUF_F_BUF_MEM_NEW 101
/* Reason codes. */
# ifdef __cplusplus
}
# endif
#endif
-83
View File
@@ -1,83 +0,0 @@
/*
* Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_CAMELLIA_H
# define HEADER_CAMELLIA_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_CAMELLIA
# include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
# define CAMELLIA_ENCRYPT 1
# define CAMELLIA_DECRYPT 0
/*
* Because array size can't be a const in C, the following two are macros.
* Both sizes are in bytes.
*/
/* This should be a hidden type, but EVP requires that the size be known */
# define CAMELLIA_BLOCK_SIZE 16
# define CAMELLIA_TABLE_BYTE_LEN 272
# define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / 4)
typedef unsigned int KEY_TABLE_TYPE[CAMELLIA_TABLE_WORD_LEN]; /* to match
* with WORD */
struct camellia_key_st {
union {
double d; /* ensures 64-bit align */
KEY_TABLE_TYPE rd_key;
} u;
int grand_rounds;
};
typedef struct camellia_key_st CAMELLIA_KEY;
int Camellia_set_key(const unsigned char *userKey, const int bits,
CAMELLIA_KEY *key);
void Camellia_encrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key);
void Camellia_decrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key);
void Camellia_ecb_encrypt(const unsigned char *in, unsigned char *out,
const CAMELLIA_KEY *key, const int enc);
void Camellia_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, const int enc);
void Camellia_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num, const int enc);
void Camellia_cfb1_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num, const int enc);
void Camellia_cfb8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num, const int enc);
void Camellia_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char *ivec, int *num);
void Camellia_ctr128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const CAMELLIA_KEY *key,
unsigned char ivec[CAMELLIA_BLOCK_SIZE],
unsigned char ecount_buf[CAMELLIA_BLOCK_SIZE],
unsigned int *num);
# ifdef __cplusplus
}
# endif
# endif
#endif

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