Compare commits

...

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

65 changed files with 5399 additions and 3119 deletions

68
.github/workflows/build.yml vendored Normal file
View File

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

7
.gitignore vendored
View File

@ -1,3 +1,4 @@
.idea
.vscode
cmake-build-*
.vs/
.vscode/
bin/
obj/

View File

@ -1,94 +0,0 @@
cmake_minimum_required(VERSION 3.18)
project(navicat-keygen)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(fmt REQUIRED)
find_package(RapidJSON REQUIRED)
find_package(OpenSSL REQUIRED)
include(FetchContent)
set(KEYSTONE_BUILD_STATIC_RUNTIME ON CACHE BOOL "" FORCE)
set(BUILD_LIBS_ONLY ON CACHE BOOL "" FORCE)
set(UNICORN_ARCH "x86" CACHE STRING "" FORCE)
set(UNICORN_INSTALL OFF CACHE BOOL "" FORCE)
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
set(UNICORN_BUILD_TESTS OFF CACHE BOOL "" FORCE)
FetchContent_Declare(
keystone
GIT_REPOSITORY "https://github.com/keystone-engine/keystone.git"
GIT_TAG "1475885daa7e566c064ae9754706e1a0ba24be3b"
)
FetchContent_Declare(
unicorn
URL "https://github.com/unicorn-engine/unicorn/archive/refs/tags/2.0.0.tar.gz"
URL_HASH "SHA256=67b445c760e2bbac663e8c8bc410e43311c7fc92df4dfa8d90e06a021d07f634"
)
FetchContent_MakeAvailable(keystone unicorn)
set(
NKG_COMMON_SOURCE
./common/exception.hpp
./common/exceptions/index_exception.hpp
./common/exceptions/key_exception.hpp
./common/exceptions/operation_canceled_exception.hpp
./common/exceptions/unix_exception.hpp
./common/resource_wrapper.hpp
./common/resource_traits/cxx_object_traits.hpp
./common/resource_traits/cxx_dynamic_array_traits.hpp
./common/resource_traits/keystone/keystone_alloc.hpp
./common/resource_traits/keystone/keystone_handle.hpp
./common/resource_traits/openssl/bignum.hpp
./common/resource_traits/openssl/bio.hpp
./common/resource_traits/openssl/bio_chain.hpp
./common/resource_traits/openssl/rsa.hpp
./common/resource_traits/openssl/evp_pkey.hpp
./common/resource_traits/openssl/evp_pkey_ctx.hpp
./common/resource_traits/openssl/evp_cipher_ctx.hpp
./common/resource_traits/openssl/encoder_ctx.hpp
./common/resource_traits/openssl/decoder_ctx.hpp
./common/resource_traits/unicorn/unicorn_handle.hpp
./common/resource_traits/unicorn/unicorn_alloc.hpp
./common/resource_traits/unix_os/file_descriptor.hpp
./common/resource_traits/unix_os/map_view.hpp
./common/rsa_cipher.hpp
./common/rsa_cipher.cpp
)
set(
NKG_KEYGEN_SOURCE
./navicat-keygen/base32_rfc4648.hpp
./navicat-keygen/base32_rfc4648.cpp
./navicat-keygen/base64_rfc4648.hpp
./navicat-keygen/base64_rfc4648.cpp
./navicat-keygen/navicat_serial_generator.hpp
./navicat-keygen/navicat_serial_generator.cpp
./navicat-keygen/CollectInformation.cpp
./navicat-keygen/GenerateLicense.cpp
./navicat-keygen/main.cpp
)
set(
NKG_PATCHER_SOURCE
./navicat-patcher/amd64_emulator.hpp
./navicat-patcher/amd64_emulator.cpp
./navicat-patcher/keystone_assembler.hpp
./navicat-patcher/keystone_assembler.cpp
./navicat-patcher/elf64_interpreter.hpp
./navicat-patcher/elf64_interpreter.cpp
./navicat-patcher/patch_solution.hpp
./navicat-patcher/patch_solution_since.hpp
./navicat-patcher/patch_solution_since_16.0.7.0.hpp
./navicat-patcher/patch_solution_since_16.0.7.0.cpp
./navicat-patcher/memory_utility.hpp
./navicat-patcher/main.cpp
)
add_executable(navicat-keygen ${NKG_COMMON_SOURCE} ${NKG_KEYGEN_SOURCE})
target_include_directories(navicat-keygen PRIVATE ./common ${RAPIDJSON_INCLUDE_DIRS})
target_link_libraries(navicat-keygen fmt::fmt OpenSSL::Crypto)
add_executable(navicat-patcher ${NKG_COMMON_SOURCE} ${NKG_PATCHER_SOURCE})
target_include_directories(navicat-patcher PRIVATE ./common ${keystone_SOURCE_DIR}/include)
target_link_libraries(navicat-patcher fmt::fmt OpenSSL::Crypto keystone unicorn pthread stdc++fs)

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) 2017 {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
navicat-keygen Copyright (C) 2017 Double Helix
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,20 +1,22 @@
# navicat-keygen for linux
# navicat-keygen
[中文版README](README.zh-CN.md)
This repository will tell you how Navicat offline activation works.
Previous code is archived in [`linux-archived`](https://notabug.org/doublesine/navicat-keygen/src/linux-archived) branch for the reason that Navicat has come to version 16.x.x which I think should be a milestone and I decide to obsolete previous code and rewrite new one.
Previous previous code is archived in [`windows-archived`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived) branch for the reason that previous previous code contains 3rd binary libraries and it gets quite big :-(
Previous code is archived in [`windows-archived2`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived2) branch for the reason that Navicat has come to version 16.x.x which I think should be a milestone and I decide to obsolete previous code and rewrite new one.
When you git-clone this repo, please add `--single-branch` flag so that archived branches won't be cloned to your computer, which saves your time and disk.
```console
$ git clone -b linux --single-branch https://notabug.org/doublesine/navicat-keygen.git
$ git clone -b windows --single-branch https://notabug.org/doublesine/navicat-keygen.git
```
## 1. How does it work?
see [here](doc/how-does-it-work.md). (WAIT TO BE DONE)
see [here](doc/how-does-it-work.md). (WATING TO BE UPDATED)
## 2. How to build?
@ -30,4 +32,4 @@ see [here](doc/how-to-use.md).
* dragonflylee
* zenuo
* zenuo

View File

@ -1,18 +1,20 @@
# navicat-keygen for linux
# navicat-keygen for windows
这份repo将会告诉你Navicat是怎么完成离线激活的。
归档的代码位于 [`linux-archived`](https://notabug.org/doublesine/navicat-keygen/src/linux-archived) 分支。归档原因Navicat进入16.x.x版本本项目打算进行重构。
第一次归档的代码位于 [`windows-archived`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived) 分支。归档原因:包含第三方二进制库,项目过大。
第二次归档的代码位于 [`windows-archived2`](https://notabug.org/doublesine/navicat-keygen/src/windows-archived2) 分支。归档原因Navicat进入16.x.x版本本项目打算进行重构。
当你clone该仓库的时候请使用 `--single-branch` 选项以此避免clone到已被归档的分支、以及节省你的时间和磁盘空间。
```console
$ git clone -b linux --single-branch https://notabug.org/doublesine/navicat-keygen.git
$ git clone -b windows --single-branch https://notabug.org/doublesine/navicat-keygen.git
```
## 1. 注册机是怎么工作的?
见[这里](doc/how-does-it-work.zh-CN.md)。(待完成)
见[这里](doc/how-does-it-work.zh-CN.md)。
## 2. 如何编译?
@ -29,3 +31,4 @@ $ git clone -b linux --single-branch https://notabug.org/doublesine/navicat-keyg
* dragonflylee
* zenuo

49
common/common.vcxitems Normal file
View File

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

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ShowAllFiles>true</ShowAllFiles>
</PropertyGroup>
</Project>

79
common/cp_converter.hpp Normal file
View File

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

View File

@ -2,8 +2,6 @@
#include <exception>
#include <string>
#include <vector>
#include <utility>
#include <cstdint>
namespace nkg {
@ -29,13 +27,10 @@ namespace nkg {
}
exception(std::string_view file, int line, std::string_view message) noexcept :
std::exception(), m_source_line(line), m_source_file(file), m_custom_message(message) {}
exception(const exception&) noexcept = default;
exception(exception&&) noexcept = default;
exception& operator=(const exception&) noexcept = default;
exception& operator=(exception&&) noexcept = default;
std::exception(), // don't pass `char*` to `std::exception`, because it is not documented in c++ standard.
m_source_line(line),
m_source_file(file),
m_custom_message(message) {}
[[nodiscard]]
int source_line() const noexcept {
@ -52,14 +47,14 @@ namespace nkg {
return m_custom_message;
}
exception&& push_hint(std::string_view hint) noexcept {
exception& push_hint(std::string_view hint) noexcept {
m_hints.emplace_back(hint);
return std::move(*this);
return *this;
}
exception&& pop_hint() noexcept {
exception& pop_hint() noexcept {
m_hints.pop_back();
return std::move(*this);
return *this;
}
const std::vector<std::string>& hints() const noexcept {
@ -85,7 +80,7 @@ namespace nkg {
trap_then_terminate();
}
virtual ~exception() override = default;
virtual ~exception() = default;
};
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,4 +18,18 @@ namespace nkg::resource_traits::keystone {
}
};
struct keystone_alloc {
using handle_t = unsigned char*;
static constexpr handle_t invalid_value = nullptr;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
static void release(const handle_t& handle) noexcept {
ks_free(handle);
}
};
}

View File

@ -1,19 +0,0 @@
#pragma once
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
namespace nkg::resource_traits::unix_os {
struct map_view {
using handle_t = void*;
static inline const handle_t invalid_value = MAP_FAILED;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
return handle != invalid_value;
}
};
}

View File

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

View File

@ -1,12 +1,12 @@
#pragma once
#include <unistd.h>
#include <windows.h>
namespace nkg::resource_traits::unix_os {
namespace nkg::resource_traits::win32 {
struct file_descriptor {
using handle_t = int;
struct generic_handle {
using handle_t = HANDLE;
static constexpr handle_t invalid_value = -1;
static constexpr handle_t invalid_value = NULL;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
@ -14,7 +14,7 @@ namespace nkg::resource_traits::unix_os {
}
static void release(const handle_t& handle) {
close(handle);
CloseHandle(handle);
}
};

View File

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

View File

@ -1,12 +1,12 @@
#pragma once
#include <unicorn/unicorn.h>
#include <windows.h>
namespace nkg::resource_traits::unicorn {
namespace nkg::resource_traits::win32 {
struct unicorn_alloc {
using handle_t = void*;
struct map_view_ptr {
using handle_t = PVOID;
static constexpr handle_t invalid_value = nullptr;
static constexpr handle_t invalid_value = NULL;
[[nodiscard]]
static bool is_valid(const handle_t& handle) noexcept {
@ -14,7 +14,7 @@ namespace nkg::resource_traits::unicorn {
}
static void release(const handle_t& handle) {
uc_free(handle);
UnmapViewOfFile(handle);
}
};

View File

@ -7,7 +7,7 @@ namespace nkg {
template<typename resource_traits_t, typename releaser_t = void>
class resource_wrapper {
public:
using handle_t = typename resource_traits_t::handle_t;
using handle_t = typename resource_traits_t::handle_t;
static_assert(std::is_trivial_v<handle_t> && std::is_standard_layout_v<handle_t>, "`resource_wrapper` requires a handle with POD type.");
private:
@ -35,9 +35,9 @@ namespace nkg {
m_handle(handle),
m_releaser(std::forward<releaser_t>(releaser)) {}
//
//
// `resource_wrapper` does not allow copy-construct
//
//
resource_wrapper(const resource_wrapper& other) = delete;
//
@ -45,7 +45,7 @@ namespace nkg {
//
resource_wrapper(resource_wrapper&& other) noexcept :
m_handle(other.m_handle),
m_releaser(std::move(other.m_releaser))
m_releaser(std::move(other.m_releaser))
{
other.m_handle = resource_traits_t::invalid_value;
}
@ -150,7 +150,7 @@ namespace nkg {
resource_wrapper(const resource_wrapper& other) = delete;
resource_wrapper(resource_wrapper&& other) noexcept :
m_handle(other.m_handle)
m_handle(other.m_handle)
{
other.m_handle = resource_traits_t::invalid_value;
}
@ -225,14 +225,21 @@ namespace nkg {
template<typename resource_traits_t>
resource_wrapper(resource_traits_t) ->
resource_wrapper<resource_traits_t, void>;
resource_wrapper<resource_traits_t, void>;
template<typename resource_traits_t, typename arg_t>
resource_wrapper(resource_traits_t, arg_t&&) ->
resource_wrapper<resource_traits_t, std::conditional_t<!std::is_same_v<std::remove_cv_t<std::remove_reference_t<arg_t>>, typename resource_traits_t::handle_t>, std::remove_reference_t<arg_t>, void>>;
resource_wrapper<
resource_traits_t,
std::conditional_t<
std::is_same_v<std::remove_cv_t<std::remove_reference_t<arg_t>>, typename resource_traits_t::handle_t> == false,
std::remove_reference_t<arg_t>,
void
>
>;
template<typename resource_traits_t, typename releaser_t, typename handle_t = typename resource_traits_t::handle_t>
resource_wrapper(resource_traits_t, const handle_t&, releaser_t&&) ->
resource_wrapper<resource_traits_t, std::remove_reference_t<releaser_t>>;
resource_wrapper<resource_traits_t, std::remove_reference_t<releaser_t>>;
}

View File

@ -1,4 +1,6 @@
#include "rsa_cipher.hpp"
#include <mutex>
#include <openssl/pem.h>
#include <openssl/bio.h>
@ -12,13 +14,20 @@
#include "resource_traits/openssl/decoder_ctx.hpp"
#endif
#include "cp_converter.hpp"
#include "exceptions/overflow_exception.hpp"
#pragma comment(lib, "libcrypto")
#pragma comment(lib, "crypt32") // required by libcrypto.lib
#pragma comment(lib, "ws2_32") // required by libcrypto.lib
#define NKG_CURRENT_SOURCE_FILE() u8".\\common\\rsa_cipher.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
[[nodiscard]]
RSA* rsa_cipher::_read_private_key_from_bio(BIO* p_bio) {
resource_wrapper new_rsa
{ resource_traits::openssl::rsa{}, PEM_read_bio_RSAPrivateKey(p_bio, nullptr, nullptr, nullptr) };
@ -31,7 +40,6 @@ namespace nkg {
}
}
[[nodiscard]]
RSA* rsa_cipher::_read_public_key_pem_from_bio(BIO* p_bio) {
resource_wrapper new_rsa
{ resource_traits::openssl::rsa{}, PEM_read_bio_RSA_PUBKEY(p_bio, nullptr, nullptr, nullptr) };
@ -44,7 +52,6 @@ namespace nkg {
}
}
[[nodiscard]]
RSA* rsa_cipher::_read_public_key_pkcs1_from_bio(BIO* p_bio) {
resource_wrapper new_rsa
{ resource_traits::openssl::rsa{}, PEM_read_bio_RSAPublicKey(p_bio, nullptr, nullptr, nullptr) };
@ -77,14 +84,6 @@ namespace nkg {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"PEM_write_bio_RSAPublicKey failed.");
}
}
rsa_cipher::rsa_cipher() :
m_rsa(RSA_new())
{
if (!m_rsa.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_new failed.");
}
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
[[nodiscard]]
EVP_PKEY* rsa_cipher::_read_private_key_from_bio(BIO* p_bio) {
@ -102,7 +101,7 @@ namespace nkg {
}
return new_rsa.transfer();
}
}
[[nodiscard]]
EVP_PKEY* rsa_cipher::_read_public_key_pem_from_bio(BIO* p_bio) {
@ -178,37 +177,33 @@ namespace nkg {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"OSSL_ENCODER_to_bio failed.");
}
}
rsa_cipher::rsa_cipher() = default;
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#endif
rsa_cipher::rsa_cipher() = default;
[[nodiscard]]
size_t rsa_cipher::bits() const {
if (m_rsa.get()) {
#if (OPENSSL_VERSION_NUMBER & 0xfff00000) == 0x10000000 // openssl 1.0.x
if (m_rsa->n) {
return BN_num_bits(m_rsa->n);
} else {
throw no_key_assigned_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"RSA key has not been set yet.");
}
#elif (OPENSSL_VERSION_NUMBER & 0xfff00000) == 0x10100000 // openssl 1.1.x
return RSA_bits(m_rsa.get());
return RSA_bits(m_rsa.get());
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // openssl 3.x.x
if (m_rsa.is_valid()) {
return EVP_PKEY_get_bits(m_rsa.get());
} else {
throw no_key_assigned_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"RSA key has not been set yet.");
}
#else
#error "rsa_cipher.cpp: Unexpected OpenSSL version."
#error "rsa_cipher.cpp: uexpected OpenSSL version"
#endif
} else {
throw no_key_assigned_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"RSA key has not been assigned yet.");
}
}
void rsa_cipher::generate_key(int bits, unsigned int e) {
resource_wrapper bn_e{ resource_traits::openssl::bignum{}, BN_new() };
if (!bn_e.is_valid()) {
if (bn_e.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"BN_new failed.");
}
@ -217,9 +212,16 @@ namespace nkg {
}
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (RSA_generate_key_ex(m_rsa.get(), bits, bn_e.get(), nullptr) == 0) {
resource_wrapper new_rsa{ resource_traits::openssl::rsa{}, RSA_new() };
if (!new_rsa.is_valid()) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_new failed.");
}
if (RSA_generate_key_ex(new_rsa.get(), bits, bn_e.get(), nullptr) == 0) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_generate_key_ex failed.");
}
m_rsa = std::move(new_rsa);
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr) };
if (!evp_pkey_context.is_valid()) {
@ -250,9 +252,9 @@ namespace nkg {
#endif
}
void rsa_cipher::export_private_key_file(std::string_view file_path) const {
void rsa_cipher::export_private_key_file(std::wstring_view file_path) const {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(file_path.data(), "w")};
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "w")};
if (bio_file.is_valid()) {
_write_private_key_to_bio(m_rsa.get(), bio_file.get());
@ -261,9 +263,13 @@ namespace nkg {
}
}
void rsa_cipher::export_public_key_file_pem(std::string_view file_path) const {
void rsa_cipher::export_private_key_file(const std::filesystem::path& file_path) const {
export_private_key_file(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::export_public_key_file_pem(std::wstring_view file_path) const {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(file_path.data(), "w")};
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "w")};
if (bio_file.is_valid()) {
_write_public_key_pem_to_bio(m_rsa.get(), bio_file.get());
@ -272,9 +278,13 @@ namespace nkg {
}
}
void rsa_cipher::export_public_key_file_pkcs1(std::string_view file_path) const {
void rsa_cipher::export_public_key_file_pem(const std::filesystem::path& file_path) const {
export_public_key_file_pem(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::export_public_key_file_pkcs1(std::wstring_view file_path) const {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(file_path.data(), "w")};
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "w")};
if (bio_file.is_valid()) {
_write_public_key_pkcs1_to_bio(m_rsa.get(), bio_file.get());
@ -283,9 +293,13 @@ namespace nkg {
}
}
void rsa_cipher::import_private_key_file(std::string_view file_path) {
void rsa_cipher::export_public_key_file_pkcs1(const std::filesystem::path& file_path) const {
export_public_key_file_pkcs1(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::import_private_key_file(std::wstring_view file_path) {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(file_path.data(), "r") };
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "r") };
if (bio_file.is_valid()) {
m_rsa.set(_read_private_key_from_bio(bio_file.get()));
@ -294,9 +308,13 @@ namespace nkg {
}
}
void rsa_cipher::import_public_key_file_pem(std::string_view file_path) {
void rsa_cipher::import_private_key_file(const std::filesystem::path& file_path) {
import_private_key_file(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::import_public_key_file_pem(std::wstring_view file_path) {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(file_path.data(), "r") };
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "r") };
if (bio_file.is_valid()) {
m_rsa.set(_read_public_key_pem_from_bio(bio_file.get()));
@ -305,9 +323,13 @@ namespace nkg {
}
}
void rsa_cipher::import_public_key_file_pkcs1(std::string_view file_path) {
void rsa_cipher::import_public_key_file_pem(const std::filesystem::path& file_path) {
import_public_key_file_pem(static_cast<std::wstring_view>(file_path.native()));
}
void rsa_cipher::import_public_key_file_pkcs1(std::wstring_view file_path) {
resource_wrapper bio_file
{ resource_traits::openssl::bio{}, BIO_new_file(file_path.data(), "r") };
{ resource_traits::openssl::bio{}, BIO_new_file(cp_converter<-1, CP_UTF8>::convert(file_path).c_str(), "r") };
if (bio_file.is_valid()) {
m_rsa.set(_read_public_key_pkcs1_from_bio(bio_file.get()));
@ -316,6 +338,10 @@ namespace nkg {
}
}
void rsa_cipher::import_public_key_file_pkcs1(const std::filesystem::path& file_path) {
import_public_key_file_pkcs1(static_cast<std::wstring_view>(file_path.native()));
}
[[nodiscard]]
std::string rsa_cipher::export_private_key_string() const {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
@ -367,7 +393,7 @@ namespace nkg {
void rsa_cipher::import_private_key_string(std::string_view key_string) {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (!bio_memory.is_valid()) {
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
@ -381,7 +407,7 @@ namespace nkg {
void rsa_cipher::import_public_key_string_pem(std::string_view key_string) {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (!bio_memory.is_valid()) {
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
@ -395,7 +421,7 @@ namespace nkg {
void rsa_cipher::import_public_key_string_pkcs1(std::string_view key_string) {
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (!bio_memory.is_valid()) {
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
@ -409,16 +435,16 @@ namespace nkg {
size_t rsa_cipher::public_encrypt(const void* plaintext, size_t plaintext_size, void* ciphertext, int padding) const {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (plaintext_size <= INT_MAX) {
int bytes_written =
int bytes_written =
RSA_public_encrypt(static_cast<int>(plaintext_size), reinterpret_cast<const unsigned char*>(plaintext), reinterpret_cast<unsigned char*>(ciphertext), m_rsa.get(), padding);
if (bytes_written != -1) {
return bytes_written;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_public_encrypt failed.");
}
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"plaintext_size > INT_MAX");
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"plaintext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
@ -452,16 +478,16 @@ namespace nkg {
size_t rsa_cipher::private_encrypt(const void* plaintext, size_t plaintext_size, void* ciphertext, int padding) const {
#if (OPENSSL_VERSION_NUMBER & 0xf0000000) < 0x30000000 // for openssl < 3.0.0
if (plaintext_size <= INT_MAX) {
int bytes_written =
int bytes_written =
RSA_private_encrypt(static_cast<int>(plaintext_size), reinterpret_cast<const unsigned char*>(plaintext), reinterpret_cast<unsigned char*>(ciphertext), m_rsa.get(), padding);
if (bytes_written != -1) {
return bytes_written;
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), ERR_get_error(), u8"RSA_public_encrypt failed.");
}
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"plaintext_size > INT_MAX");
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"plaintext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
@ -505,7 +531,7 @@ namespace nkg {
.push_hint(u8"Are your sure you DO provide a correct public key?");
}
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"ciphertext_size > INT_MAX");
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"ciphertext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
@ -523,7 +549,8 @@ namespace nkg {
size_t plaintext_size = 0;
if (EVP_PKEY_verify_recover(evp_pkey_context.get(), nullptr, &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_verify_recover failed.");
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_verify_recover failed.")
.push_hint(u8"Are your sure you DO provide a correct public key?");
}
if (EVP_PKEY_verify_recover(evp_pkey_context.get(), reinterpret_cast<unsigned char*>(plaintext), &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
@ -549,7 +576,7 @@ namespace nkg {
.push_hint(u8"Are your sure you DO provide a correct private key?");
}
} else {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"ciphertext_size > INT_MAX");
throw exceptions::overflow_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"ciphertext_size > INT_MAX");
}
#elif (OPENSSL_VERSION_NUMBER & 0xf0000000) == 0x30000000 // for openssl 3.x.x
resource_wrapper evp_pkey_context{ resource_traits::openssl::evp_pkey_ctx{}, EVP_PKEY_CTX_new(m_rsa.get(), nullptr) };
@ -567,7 +594,8 @@ namespace nkg {
size_t plaintext_size = 0;
if (EVP_PKEY_decrypt(evp_pkey_context.get(), nullptr, &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_decrypt failed.");
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_PKEY_decrypt failed.")
.push_hint(u8"Are your sure you DO provide a correct private key?");
}
if (EVP_PKEY_decrypt(evp_pkey_context.get(), reinterpret_cast<unsigned char*>(plaintext), &plaintext_size, reinterpret_cast<const unsigned char*>(ciphertext), ciphertext_size) <= 0) { // return 1 for success, 0 or a negative value for failure
@ -580,6 +608,17 @@ namespace nkg {
#endif
}
rsa_cipher::backend_error::backend_error(std::string_view file, int line, std::string_view message) noexcept:
::nkg::exception::exception(file, line, message), m_error_code(0) {}
rsa_cipher::backend_error::backend_error(std::string_view file, int line, error_code_t openssl_errno, std::string_view message) noexcept:
::nkg::exception::exception(file, line, message), m_error_code(openssl_errno)
{
static std::once_flag onceflag_load_crypto_strings;
std::call_once(onceflag_load_crypto_strings, []() { ERR_load_crypto_strings(); });
m_error_string = ERR_reason_error_string(m_error_code);
}
}
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,6 +1,6 @@
#pragma once
#include <string>
#include <optional>
#include <filesystem>
#include <openssl/err.h>
#include <openssl/rsa.h>
@ -74,17 +74,29 @@ namespace nkg {
void generate_key(int bits, unsigned int e = RSA_F4);
void export_private_key_file(std::string_view file_path) const;
void export_private_key_file(std::wstring_view file_path) const;
void export_public_key_file_pem(std::string_view file_path) const;
void export_private_key_file(const std::filesystem::path& file_path) const;
void export_public_key_file_pkcs1(std::string_view file_path) const;
void export_public_key_file_pem(std::wstring_view file_path) const;
void import_private_key_file(std::string_view file_path);
void export_public_key_file_pem(const std::filesystem::path& file_path) const;
void import_public_key_file_pem(std::string_view file_path);
void export_public_key_file_pkcs1(std::wstring_view file_path) const;
void import_public_key_file_pkcs1(std::string_view file_path);
void export_public_key_file_pkcs1(const std::filesystem::path& file_path) const;
void import_private_key_file(std::wstring_view file_path);
void import_private_key_file(const std::filesystem::path& file_path);
void import_public_key_file_pem(std::wstring_view file_path);
void import_public_key_file_pem(const std::filesystem::path& file_path);
void import_public_key_file_pkcs1(std::wstring_view file_path);
void import_public_key_file_pkcs1(const std::filesystem::path& file_path);
[[nodiscard]]
std::string export_private_key_string() const;
@ -115,24 +127,22 @@ namespace nkg {
using error_code_t = decltype(ERR_get_error());
private:
std::optional<error_code_t> m_error_code;
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, std::string_view message) noexcept :
::nkg::exception(file, line, message) {}
backend_error(std::string_view file, int line, std::string_view message) noexcept;
backend_error(std::string_view file, int line, error_code_t openssl_errno, std::string_view message) noexcept :
::nkg::exception(file, line, message), m_error_code(openssl_errno) {}
backend_error(std::string_view file, int line, error_code_t openssl_errno, std::string_view message) noexcept;
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return m_error_code.has_value();
return m_error_code != 0;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
if (error_code_exists()) { return m_error_code.value(); } else { trap_then_terminate(); }
if (error_code_exists()) { return m_error_code; } else { trap_then_terminate(); }
}
[[nodiscard]]

284
doc/how-does-it-work.md Normal file
View File

@ -0,0 +1,284 @@
# Navicat Keygen - How does it work?
[中文版](how-does-it-work.zh-CN.md)
## 1. Keyword Explanation.
* __Navicat Activation Public Key__
It is a __RSA-2048__ public key that Navicat used to encrypt or decrypt offline activation information.
It is stored in __navicat.exe__ as a kind of resource called __RCData__. The resource name is `"ACTIVATIONPUBKEY"`. You can see it by a software called [___Resource Hacker___](http://www.angusj.com/resourcehacker/). The public key is
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
If you have the corresponding private key, you can tell me. I would be very appreciated for your generous.
__NOTICE:__
Start from __Navicat Premium 12.0.25__, Navicat do not load this public key from resource in `navicat.exe`. Instead, the public key is stored in `libcc.dll` and has been encrypted. To avoid being replaced easily, the public key is split into 5 parts:
The following content is discovered from `libcc.dll` of __Navicat Premium x64 12.0.25 Simplified Chinese version__. The SHA256 value of `libcc.dll` is `607e0a84c75966b00f3d12fa833e91d159e4f51ac51b6ba66f98d0c3cbefdce0`.
I __DO NOT__ guarantee that offset values are absolutely correct in other versions. But __char strings__ and __immediate values__ are highly possible to be found.
1. At file offset `+0x01A12090` in `libcc.dll`, stored as __char string__:
```
"D75125B70767B94145B47C1CB3C0755E
7CCB8825C5DCE0C58ACF944E08280140
9A02472FAFFD1CD77864BB821AE36766
FEEDE6A24F12662954168BFA314BD950
32B9D82445355ED7BC0B880887D650F5"
```
2. At file offset `+0x0059D799` in `libcc.dll`, stored as __immediate value__ in a instruction:
```
0xFE 0xEA 0xBC 0x01
```
In decimal: `29158142`
3. At file offset `+0x01A11DA0` in `libcc.dll`, stored as __char string__:
```
"E1CED09B9C2186BF71A70C0FE2F1E0AE
F3BD6B75277AAB20DFAF3D110F75912B
FB63AC50EC4C48689D1502715243A79F
39FF2DE2BF15CE438FF885745ED54573
850E8A9F40EE2FF505EB7476F95ADB78
3B28CA374FAC4632892AB82FB3BF4715
FCFE6E82D03731FC3762B6AAC3DF1C3B
C646FE9CD3C62663A97EE72DB932A301
312B4A7633100C8CC357262C39A2B3A6
4B224F5276D5EDBDF0804DC3AC4B8351
62BB1969EAEBADC43D2511D6E0239287
81B167A48273B953378D3D2080CC0677
7E8A2364F0234B81064C5C739A8DA28D
C5889072BF37685CBC94C2D31D0179AD
86D8E3AA8090D4F0B281BE37E0143746
E6049CCC06899401264FA471C016A96C
79815B55BBC26B43052609D9D175FBCD
E455392F10E51EC162F51CF732E6BB39
1F56BBFD8D957DF3D4C55B71CEFD54B1
9C16D458757373E698D7E693A8FC3981
5A8BF03BA05EA8C8778D38F9873D62B4
460F41ACF997C30E7C3AF025FA171B5F
5AD4D6B15E95C27F6B35AD61875E5505
449B4E"
```
4. At file offset `+0x0059D77F` in `libcc.dll`, stored as __immediate value__ in a instruction:
```
0x59 0x08 0x01 0x00
```
In decimal: `67673`
5. At file offset `+ 0x1A11D8C` in `libcc.dll`, stored as __char string__:
```
"92933"
```
Then output encrypted public key with format `"%s%d%s%d%s"`. The order is the same as it lists:
```
D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933
```
This encrypted public key can be decrypted by my another repo: [how-does-navicat-encrypt-password](https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password), while the key used is `b'23970790'`.
Example:
```cmd
E:\GitHub>git clone https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password.git
...
E:\GitHub>cd how-does-navicat-encrypt-password\python3
E:\GitHub\how-does-navicat-encrypt-password\python3>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from NavicatCrypto import *
>>> cipher = Navicat11Crypto(b'23970790')
>>> print(cipher.DecryptString('D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933'))
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
__NOTICE:__
Start from __Navicat Premium 12.1.11__, Navicat do not load the public key through the method I talked before. Of course, the public key is still stored in `libcc.dll`. When Navicat starts, it encrypts the public key by an 8-bytes-long XOR key and stores the ciphertext in static area. When verifing __Activation Code__, Navicat will regenerate the 8-bytes-long XOR key and decrypts the ciphertext in static area to get the public key.
In `libcc.dll`, x64 version, you can find some instructions that looks like:
```asm
xor eax, 'M'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'B'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'j'
mov byte_xxxxxx, al
...
...
```
* __Request Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the cipher text of __Offline Activation Request Information__ encrypted by __Navicat Activation Public Key__.
* __Offline Activation Request Information__
It is just a JSON-style ASCII string which contains 3 items. They are `"K"`, `"DI"` and `"P"` respectively, which represent __snKey__, __DeviceIdentifier__ (related with your machine), __Platform__ (OS Type).
Like
```
{"K": "xxxxxxxxxxxxxxxx", "DI": "yyyyyyyyyyyyy", "P": "WIN8"}
```
* __Activation Code__
It is a Base64 string that represents 256-bytes-long data, while the 256-bytes-long data is the cipher text of the __Offline Activation Response Information__ encrypted by __Navicat Activation Private Key__. So far, we don't know the official activation private key and we have to replace it in `navicat.exe` and `libcc.dll`.
* __Offline Activation Response Information__
Just like __Offline Activation Request Information__, it is also a JSON-style ASCII string. But it contains 5 items. They are `"K"`, `"N"`, `"O"`, `"T"` and `"DI"` respectively.
`"K"` and `"DI"` has the same meaning that is mentioned in __Offline Activation Request Information__ and must be the same with the corresponding items in __Offline Activation Request Information__.
`"N"`, `"O"`, `"T"` represent __Name__, __Organization__, __Timestamp__ respectively. __Name__ and __Organization__ are UTF-8 strings and the type of __Timestamp__ can be string or integer. (Thanks for discoveries from @Wizr, issue #10)
`"T"` can be omitted.
* __snKey__
It is a 4-block-long string, while every block is 4-chars-long.
__snKey__ is generated by 10-bytes-long data. In order to explain it easily, I use __uint8_t data[10]__ to represent the 10-bytes-long data.
1. __data[0]__ and __data[1]__ must be `0x68` and `0x2A` respectively.
These two bytes are Naivcat signature number.
2. __data[2]__, __data[3]__ and __data[4]__ can be any byte. Just set them whatever you want.
3. __data[5]__ and __data[6]__ are product language signatures.
| Language | data[5] | data[6] | Discoverer |
|------------|:---------:|:---------:|-----------------|
| English | 0xAC | 0x88 | |
| 简体中文 | 0xCE | 0x32 | |
| 繁體中文 | 0xAA | 0x99 | |
| 日本語 | 0xAD | 0x82 | @dragonflylee |
| Polski | 0xBB | 0x55 | @dragonflylee |
| Español | 0xAE | 0x10 | @dragonflylee |
| Français | 0xFA | 0x20 | @Deltafox79 |
| Deutsch | 0xB1 | 0x60 | @dragonflylee |
| 한국어 | 0xB5 | 0x60 | @dragonflylee |
| Русский | 0xEE | 0x16 | @dragonflylee |
| Português | 0xCD | 0x49 | @dragonflylee |
4. __data[7]__ is Navicat product ID. (Thanks @dragonflylee and @Deltafox79)
|Product Name |Enterprise|Standard|Educational|Essentials|
|----------------------|:--------:|:------:|:---------:|:--------:|
|Navicat Report Viewer |0x0B | | | |
|Navicat Data Modeler 3| |0x84 |0x85 | |
|Navicat Premium |0x65 | |0x66 |0x67 |
|Navicat MySQL |0x68 |0x69 |0x6A |0x6B |
|Navicat PostgreSQL |0x6C |0x6D |0x6E |0x6F |
|Navicat Oracle |0x70 |0x71 |0x72 |0x73 |
|Navicat SQL Server |0x74 |0x75 |0x76 |0x77 |
|Navicat SQLite |0x78 |0x79 |0x7A |0x7B |
|Navicat MariaDB |0x7C |0x7D |0x7E |0x7F |
|Navicat MongoDB |0x80 |0x81 |0x82 | |
5. High 4 bits of __data[8]__ represents __major version number__.
Low 4 bits is unknown, but we can use it to delay activation deadline. Possible values are `0000` or `0001`.
__Example:__
For __Navicat 12 x64__: High 4 bits must be `1100`, which is the binary of number `12`.
For __Navicat 11 x64__: High 4 bits must be `1011`, which is the binary of number `11`.
6. __data[9]__ is unknown, but you can set it by `0xFD`, `0xFC` or `0xFB` if you want to use __not-for-resale license__.
According to symbol information in __Navicat 12 for Mac x64__ version:
* `0xFB` is __Not-For-Resale-30-days__ license.
* `0xFC` is __Not-For-Resale-90-days__ license.
* `0xFD` is __Not-For-Resale-365-days__ license.
* `0xFE` is __Not-For-Resale__ license.
* `0xFF` is __Site__ license.
After `uint8_t data[10]` is ready, Navicat uses __DES__ with __ECB mode__ to encrypt the last 8 bytes of `uint8_t data[10]` which are from __data[2]__ to __data[9]__.
The DES key is:
```cpp
unsigned char DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
```
Then use Base32 to encode `uint8_t data[10]` whose encode table is
```cpp
char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
```
After encoding, you will get a 16-char-long string starting with `"NAV"`.
Finally, divide the 16-char-long string to four 4-chars-long blocks and join them with `"-"` then you will get __snKey__.
## 2. Activation Process
1. Check whether __snKey__ that user inputs is valid.
2. After user clicks `Activate`, Navicat will start online activation first. If fails, user can choose offline activation.
3. Navicat will use the __snKey__ that user inputs and some information collected from user's machine to generate __Offline Activation Request Information__. Then Navicat will encrypt it by __Navicat Activation Public Key__ and return a Base64-encoded string as __Request Code__.
4. In legal way, the __Request Code__ should be sent to Navicat official activation server by a Internet-accessible computer. And Navicat official activation server will return a legal __Activation Code__.
But now, we use keygen to play the official activation server's role.
1. According to the __Request Code__, get `"DI"` value and `"K"` value.
2. Fill __Offline Activation Response Information__ with `"K"` value, name, organization name, `"DI"` value and, if need, `"T"` value.
3. Encrypt __Offline Activation Response Information__ by __Navicat Activation Private Key__ and you will get 256-byte-long data.
4. Encode the 256-byte-long data by Base64. The result is __Activation Code__.
5. After user input __Activation Code__, offline activation is done successfully.

View File

@ -0,0 +1,282 @@
# Navicat Keygen - 注册机是怎么工作的?
## 1. 关键词解释.
* __Navicat激活公钥__
这是一个2048位的RSA公钥Navicat使用这个公钥来完成相关激活信息的加密和解密。
这个公钥被作为 __RCData__ 类型的资源储存在 __navicat.exe__ 当中。资源名为`"ACTIVATIONPUBKEY"`。你可以使用一个叫[Resource Hacker](http://www.angusj.com/resourcehacker/)的软件来查看它。这个公钥的具体内容为:
```
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
如果您有相应的私钥并乐意公开的话欢迎联系我,我将非常感谢您的慷慨。
__注意__
__Navicat Premium 12.0.25__ 开始Navicat不再从`navicat.exe`的资源中加载私钥。事实上,公钥转为从`libcc.dll`中加载并且已经被加密。与此同时为了防止被轻松地替换加密的公钥被分到5个地方储存
以下内容是从 __Navicat Premium x64 12.0.25 简体中文版__ 的`libcc.dll`中发现的,`libcc.dll`的SHA256值为`607e0a84c75966b00f3d12fa833e91d159e4f51ac51b6ba66f98d0c3cbefdce0`。我不保证在Navicat的其他版本中相关偏移量和下述的相同但相关的 __字符串__ 以及 __立即数__ 是很可能找得到的。
1. 在`libcc.dll`中,文件偏移量`+0x01A12090`的地方,储存了加密公钥的第一部分,以 __字符串__ 的形式储存:
```
"D75125B70767B94145B47C1CB3C0755E
7CCB8825C5DCE0C58ACF944E08280140
9A02472FAFFD1CD77864BB821AE36766
FEEDE6A24F12662954168BFA314BD950
32B9D82445355ED7BC0B880887D650F5"
```
2. 在`libcc.dll`中,文件偏移量`+0x0059D799`的地方,储存了加密公钥的第二部分,以 __立即数__ 的形式储存在一条指令中:
```
0xFE 0xEA 0xBC 0x01
```
相应的十进制值为: `29158142`
3. 在`libcc.dll`中,文件偏移量`+0x01A11DA0`的地方,储存了加密公钥的第三部分,以 __字符串__ 的形式储存:
```
"E1CED09B9C2186BF71A70C0FE2F1E0AE
F3BD6B75277AAB20DFAF3D110F75912B
FB63AC50EC4C48689D1502715243A79F
39FF2DE2BF15CE438FF885745ED54573
850E8A9F40EE2FF505EB7476F95ADB78
3B28CA374FAC4632892AB82FB3BF4715
FCFE6E82D03731FC3762B6AAC3DF1C3B
C646FE9CD3C62663A97EE72DB932A301
312B4A7633100C8CC357262C39A2B3A6
4B224F5276D5EDBDF0804DC3AC4B8351
62BB1969EAEBADC43D2511D6E0239287
81B167A48273B953378D3D2080CC0677
7E8A2364F0234B81064C5C739A8DA28D
C5889072BF37685CBC94C2D31D0179AD
86D8E3AA8090D4F0B281BE37E0143746
E6049CCC06899401264FA471C016A96C
79815B55BBC26B43052609D9D175FBCD
E455392F10E51EC162F51CF732E6BB39
1F56BBFD8D957DF3D4C55B71CEFD54B1
9C16D458757373E698D7E693A8FC3981
5A8BF03BA05EA8C8778D38F9873D62B4
460F41ACF997C30E7C3AF025FA171B5F
5AD4D6B15E95C27F6B35AD61875E5505
449B4E"
```
4. 在`libcc.dll`中,文件偏移量`+0x0059D77F`的地方,储存了加密公钥的第四部分,以 __立即数__ 的形式储存在一条指令中:
```
0x59 0x08 0x01 0x00
```
相应的十进制值为: `67673`
5. 在`libcc.dll`中,文件偏移量`+0x01A11D8C`的地方,储存了加密公钥的第五部分,以 __字符串__ 的形式储存:
```
"92933"
```
这五部分按照`"%s%d%s%d%s"`的形式输出则为加密的公钥,顺序和上述的顺序相同,具体的输出为:
```
D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933
```
这个加密的公钥可以用我的另外一个repo[how-does-navicat-encrypt-password](https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password))解密,其中密钥为`b'23970790'`。
例如:
```cmd
E:\GitHub>git clone https://github.com/DoubleLabyrinth/how-does-navicat-encrypt-password.git
...
E:\GitHub>cd how-does-navicat-encrypt-password\python3
E:\GitHub\how-does-navicat-encrypt-password\python3>python
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from NavicatCrypto import *
>>> cipher = Navicat11Crypto(b'23970790')
>>> print(cipher.DecryptString('D75125B70767B94145B47C1CB3C0755E7CCB8825C5DCE0C58ACF944E082801409A02472FAFFD1CD77864BB821AE36766FEEDE6A24F12662954168BFA314BD95032B9D82445355ED7BC0B880887D650F529158142E1CED09B9C2186BF71A70C0FE2F1E0AEF3BD6B75277AAB20DFAF3D110F75912BFB63AC50EC4C48689D1502715243A79F39FF2DE2BF15CE438FF885745ED54573850E8A9F40EE2FF505EB7476F95ADB783B28CA374FAC4632892AB82FB3BF4715FCFE6E82D03731FC3762B6AAC3DF1C3BC646FE9CD3C62663A97EE72DB932A301312B4A7633100C8CC357262C39A2B3A64B224F5276D5EDBDF0804DC3AC4B835162BB1969EAEBADC43D2511D6E023928781B167A48273B953378D3D2080CC06777E8A2364F0234B81064C5C739A8DA28DC5889072BF37685CBC94C2D31D0179AD86D8E3AA8090D4F0B281BE37E0143746E6049CCC06899401264FA471C016A96C79815B55BBC26B43052609D9D175FBCDE455392F10E51EC162F51CF732E6BB391F56BBFD8D957DF3D4C55B71CEFD54B19C16D458757373E698D7E693A8FC39815A8BF03BA05EA8C8778D38F9873D62B4460F41ACF997C30E7C3AF025FA171B5F5AD4D6B15E95C27F6B35AD61875E5505449B4E6767392933'))
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889I
qdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginv
a5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOF
R0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2
WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmt
YyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQ
awIDAQAB
-----END PUBLIC KEY-----
```
__注意__
__Navicat Premium 12.1.11__ 开始Navicat不再用上面说的方法加载密钥。当然密钥还是储存在`libcc.dll`文件中。当Navicat启动时它会用8字节长的XOR密钥来加密公钥并储存到一个静态数据区中。当验证 __激活码__Navicat会重新生成一样的8字节XOR密钥并解密在静态储存区中的密文从而获取公钥。
在`libcc.dll`x64版本中你会看到如下的几条指令
```asm
xor eax, 'M'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'B'
mov byte_xxxxxx, al
...
xor eax, 'I'
mov byte_xxxxxx, al
...
xor eax, 'j'
mov byte_xxxxxx, al
...
...
```
* __请求码__
这是一个Base64编码的字符串代表的是长度为256字节的数据。这256字节的数据是 __离线激活信息____Navicat激活公钥__ 加密的密文。
* __离线激活请求信息__
这是一个JSON风格的字符串。它包含了3个Key`"K"`、`"DI"`和`"P"`,分别代表 __序列号__、__设备识别码__与你的电脑硬件信息相关__平台__ (其实就是操作系统类型)。
例如:
```
{"K": "xxxxxxxxxxxxxxxx", "DI": "yyyyyyyyyyyyy", "P": "WIN8"}
```
* __激活码__
这是一个Base64编码的字符串代表的是长度为256字节的数据。这256字节的数据是 __离线激活回复信息____Navicat激活私钥__ 加密的密文。目前我们不知道官方的 __Navicat激活私钥__,所以我们得替换掉软件里的公钥。
* __离线激活回复信息__
__离线激活请求信息__ 一样它也是一个JSON风格的字符串。但是它包含5个Key分别为`"K"`、`"N"`、`"O"`、`"T"` 和 `"DI"`.
`"K"``"DI"` 的意义与 __离线激活请求信息__ 中的相同且Value必须与 __离线激活请求信息__ 中的相同。
`"N"`、`"O"`、`"T"` 分别代表 __注册名__、__组织__、__授权时间__。
__注册名____组织__ 的值类型为UTF-8编码的字符串。__授权时间__ 的值类型可以为字符串或整数(感谢@Wizr在issue #10中的报告)。
`"T"` 可以被省略。
* __序列号__
这是一个被分为了4个部分的字符串其中每个部分都是4个字符长。
__序列号__ 是通过10个字节的数据来生成的。为了表达方便我用 __uint8_t data[10]__ 来表示这10个字节。
1. __data[0]____data[1]__ 必须分别为 `0x68``0x2A`
这两个字节为Navicat的标志数。
2. __data[2]__、__data[3]__ 和 __data[4]__ 可以是任意字节,你想设成什么都行。
3. __data[5]____data[6]__ 是Navicat的语言标志值如下
| 语言类型 | data[5] | data[6] | 发现者 |
|------------|:---------:|:---------:|-----------------|
| English | 0xAC | 0x88 | |
| 简体中文 | 0xCE | 0x32 | |
| 繁體中文 | 0xAA | 0x99 | |
| 日本語 | 0xAD | 0x82 | @dragonflylee |
| Polski | 0xBB | 0x55 | @dragonflylee |
| Español | 0xAE | 0x10 | @dragonflylee |
| Français | 0xFA | 0x20 | @Deltafox79 |
| Deutsch | 0xB1 | 0x60 | @dragonflylee |
| 한국어 | 0xB5 | 0x60 | @dragonflylee |
| Русский | 0xEE | 0x16 | @dragonflylee |
| Português | 0xCD | 0x49 | @dragonflylee |
4. __data[7]__ 是Navicat产品ID。感谢 @dragonflylee@Deltafox79提供的数据
|产品名 |Enterprise|Standard|Educational|Essentials|
|----------------------|:--------:|:------:|:---------:|:--------:|
|Navicat Report Viewer |0x0B | | | |
|Navicat Data Modeler 3| |0x84 |0x85 | |
|Navicat Premium |0x65 | |0x66 |0x67 |
|Navicat MySQL |0x68 |0x69 |0x6A |0x6B |
|Navicat PostgreSQL |0x6C |0x6D |0x6E |0x6F |
|Navicat Oracle |0x70 |0x71 |0x72 |0x73 |
|Navicat SQL Server |0x74 |0x75 |0x76 |0x77 |
|Navicat SQLite |0x78 |0x79 |0x7A |0x7B |
|Navicat MariaDB |0x7C |0x7D |0x7E |0x7F |
|Navicat MongoDB |0x80 |0x81 |0x82 | |
5. __data[8]__ 的高4位代表 __版本号__。低4位未知但可以用来延长激活期限可取的值有`0000`和`0001`。
例如:
对于 __Navicat 12__: 高4位必须是`1100`,为`12`的二进制形式。
对于 __Navicat 11__: 高4位必须是`1011`,为`11`的二进制形式。
6. __data[9]__ 目前暂未知,但如果你想要 __not-for-resale license__ 的话可以设成`0xFD`、`0xFC`或`0xFB`。
根据 __Navicat 12 for Mac x64__ 版本残留的符号信息可知:
* `0xFB`__Not-For-Resale-30-days__ license.
* `0xFC`__Not-For-Resale-90-days__ license.
* `0xFD`__Not-For-Resale-365-days__ license.
* `0xFE`__Not-For-Resale__ license.
* `0xFF`__Site__ license.
之后Navicat使用 __ECB__ 模式的 __DES__ 算法来加密 __data[10]__ 的后8字节也就是 __data[2]____data[9]__ 的部分。
相应的DES密钥为
```cpp
unsigned char DESKey = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
```
之后使用Base32编码 __data[10]__,其中编码表改为:
```cpp
char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
```
编码之后你应该会得到一个16字节长的字符串并且以"NAV"打头。
将16字节的字符串分成4个4字节的小块然后用`"-"`连接就可以得到 __序列号__
## 2. 激活过程
1. 检查用户输入的 __序列号__ 是否合法。
2. 在用户点击了`激活`按钮之后Navicat会先尝试在线激活。如果失败用户可以选择离线激活。
3. Navicat会使用用户输入的 __序列号__ 以及从用户电脑收集来的信息生成 __离线激活请求信息__,然后用 __Navicat激活公钥__ 加密并将密文用Base64编码最后得到 __请求码__
4. 正常流程下__请求码__ 应该通过可联网的电脑发送给Navicat的官方激活服务器。之后Navicat的官方激活服务器会返回一个合法的 __激活码__
但现在我们使用注册机来扮演官方激活服务器的角色只是Navicat软件里的激活公钥得换成自己的公钥
1. 根据 __请求码__, 获得`"DI"`值和`"K"`值。
2. 用`"K"`值、用户名、组织名和`"DI"`值填写 __离线激活回复信息__
3. 用自己的2048位RSA私钥加密 __离线激活回复信息__你将会得到256字节的密文。
4. 用Base64编码这256字节的密文就可以得到 __激活码__
5. 在Navicat软件中填入 __激活码__ 即可完成离线激活。

View File

@ -1,37 +1,60 @@
# navicat-keygen for linux - How to build?
# navicat-keygen for windows - How to build?
[中文版](how-to-build.zh-CN.md)
## 1. Prerequisites
1. Install latest `CMake`:
1. Please make sure that you have __Visual Studio 2022__ or the higher. Because this is a VS2022 project.
```bash
$ sudo apt-get install cmake
2. Please make sure you have installed `vcpkg` and the following libraries:
* `fmt:x64-windows-static`
* `fmt:x86-windows-static`
* `openssl:x64-windows-static`
* `openssl:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `unicorn:x64-windows-static`
* `unicorn:x86-windows-static`
is installed.
You can install them by:
```console
$ vcpkg install fmt:x64-windows-static
$ vcpkg install fmt:x86-windows-static
$ vcpkg install openssl:x64-windows-static
$ vcpkg install openssl:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install unicorn:x64-windows-static
$ vcpkg install unicorn:x86-windows-static
```
2. Install `fmt`, `OpenSSL` and `rapidjson`:
3. Your `vcpkg` has been integrated into your __Visual Studio__, which means you have run
```bash
$ sudo apt-get install libfmt-dev libssl-dev rapidjson-dev
```console
$ vcpkg integrate install
```
successfully.
## 2. Build
1. Clone:
1. Open this project in __Visual Studio__.
```bash
$ git clone -b linux --single-branch https://notabug.org/doublesine/navicat-keygen.git
$ cd navicat-keygen
```
2. Select `Release` configuration.
2. Build:
3. Select `Win32` to build keygen/patcher for 32-bits Navicat.
```bash
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release ..
$ cmake --build . -- -j4
```
Or select `x64` to build keygen/patcher for 64-bits Navicat.
4. Select __Build > Build Solution__.
You will see executable files in `bin/` directory.
Then you will see two executable files, `navicat-keygen` and `navicat-patcher`, in `build` directory.

View File

@ -1,35 +1,54 @@
# navicat-keygen for linux - 如何编译?
# navicat-keygen for windows - 如何编译?
## 1. 前提条件
1. 安装最新的 `CMake`:
1. 请确保你有 __Visual Studio 2022__ 或者更高版本。因为这是一个VS2022项目。
```bash
$ sudo apt-get install cmake
2. 请确保你安装了 `vcpkg` 以及下面几个库:
* `fmt:x64-windows-static`
* `fmt:x86-windows-static`
* `openssl:x64-windows-static`
* `openssl:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `unicorn:x64-windows-static`
* `unicorn:x86-windows-static`
你可以通过下面的命令来安装它们:
```console
$ vcpkg install fmt:x64-windows-static
$ vcpkg install fmt:x86-windows-static
$ vcpkg install openssl:x64-windows-static
$ vcpkg install openssl:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install unicorn:x64-windows-static
$ vcpkg install unicorn:x86-windows-static
```
2. 安装 `fmt`、`OpenSSL` 和 `rapidjson`:
3. 你的 `vcpkg` 已经和你的 __Visual Studio__ 集成了,即你曾成功运行了:
```bash
$ sudo apt-get install libfmt-dev libssl-dev rapidjson-dev
```console
$ vcpkg integrate install
```
## 2. 编译
1. clone仓库:
1. __Visual Studio__ 打开这个项目。
```bash
$ git clone -b linux --single-branch https://notabug.org/doublesine/navicat-keygen.git
$ cd navicat-keygen
```
2. 选择 `Release` 配置。
2. 编译:
3. 选择 `Win32` 来生成供32位Navicat使用的keygen/patcher。
```bash
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release ..
$ cmake --build . -- -j4
```
或者选择 `x64` 来生成供64位Navicat使用的keygen/patcher。
4. 选择 __生成 > 生成解决方案__
生成完成后,你会在 `bin/` 文件夹下看到编译后的keygen/patcher。
编译完后你会在build文件夹里看到两个可执行文件 `navicat-keygen``navicat-patcher`

View File

@ -1,85 +1,80 @@
# navicat-keygen for linux - How to use?
# navicat-keygen for windows - How to use?
[中文版](how-to-use.zh-CN.md)
[中文版](how-to-use.windows.zh-CN.md)
1. Download navicat from official website and you will get an AppImage file. For example, a file named `navicat16-premium-en.AppImage`. I assume that the AppImage file is located in `~/` folder.
2. Extract all files inside `navicat16-premium-en.AppImage` to a directory, e.g. `~/navicat16-premium-en-patched`:
```bash
$ mkdir ~/navicat16-premium-en
$ sudo mount -o loop ~/navicat16-premium-en.AppImage ~/navicat16-premium-en
$ cp -r ~/navicat16-premium-en ~/navicat16-premium-en-patched
$ sudo umount ~/navicat16-premium-en
$ rm -rf ~/navicat16-premium-en
```
3. [Build keygen and patcher.](how-to-build.md)
4. Use `navicat-patcher` to replace the official public key.
```
Usage:
navicat-patcher [OPTION...] <navicat root path> [RSA-2048 private key file]
1. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `libcc.dll`.
--dry-run Run patcher without applying any patches
-h, --help Print help
```
navicat-patcher.exe [-dry-run] <Navicat Install Path> [RSA-2048 PEM File Path]
```
__Example:__
* `[-dry-run]` Run patcher without applying any patches.
__This parameter is optional.__
* `<Navicat Install Path>`: The full path to Navicat installation folder.
__This parameter must be specified.__
* `[RSA-2048 PEM File Path]`: The full path or relative path to a RSA-2048 private key file.
__This parameter is optional.__ If not specified, `navicat-patcher.exe` will generate a new RSA-2048 private key file `RegPrivateKey.pem` at current directory.
__Example: (in cmd.exe)__
```bash
$ ./navicat-patcher ~/navicat16-premium-en-patched
```
It has been tested on __Navicat Premium 16.0.7 English For Linux__ version. The following is an example of output:
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 16"
```
It has been tested on __Navicat Premium 16.0.7 English version__. The following is an example of output.
```
***************************************************
* navicat-patcher by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[+] Try to open libcc.dll ... OK!
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_LINUX_vtable = 0x0000000002fbf038
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey = 0x0000000001420530
[*] patch_solution_since<16, 0, 7, 0>: m_va_pltgot_std_string_append = 0x000000000306a608
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x00000001837759f0
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x0000000181fa52d0
[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x0000000183439bd0
[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAnqeNFqE0n6k+Ys58R+IzIULlZ9oxasJns46vaVcnd9e9mTj4
hf/ArQohP5bex0UD+NGCLfQWKohnQxy9IFjQxZ6wUJnKOaA1UfdRr0ck7LZz5YV2
5CkF4VZ7UWGEp/LEQiJnIBAtp7Zq5PNviqI03PZv2MfZt1/6YstCvi8s0rmpAyTw
V5pteDipsI3lTapysLLsL+kQuJ0Z64GGk5D7rM8UPBt/Wjpe/qb/OwJKJ3Vi65/Z
RRLVt46euwdiW8ORmNt552zOdvQPgYLEP38dMCpoeqIwv7IFWWJHxt0JgOTmxZ5c
hjMq9ns3wyyEFjvSGSpM6sGL5eR1TMDQt8PSIwIDAQABAoIBAAp+jL+VdDSnbj/8
5o2escEeeqwu65vjNhbTdljicfLka18qPI4oh6cqh158bUoDD6syuIivn5O6qBHx
YbU1CsI3p/P86Dp9lWlRka6lZxTdULc6581ZxVDNdqTAbZTqYv745ZdiWpLAZzuz
uooSBqsjBezx8z3E9Hv6c/S+jBl4IcKx7vEgKbC47CAAnFZFGonRPBj88fXn7VmP
KEa7EVIE8yNG/xO4H+hlpio8XsTfbXB4Tx/Mw4f0ZCifFFE9aC503usbTQ9HCRn/
13VgBeFzC+uxluEvpm7r3efcI1vFLDHiKlAzO85vDhTOef3jZv29PTUwbkNCP8AM
CHP9abECgYEAzKWmGRcMVhwKL2RIc0VW1mSW82VTnjuTe9wnonYOGHmxCxQBZpB2
j8mjfPBNzg3pjhRryrmfA2V/1Rxk7/hnw9I+OnRJA2p+USOKVlXi5YA3CMtPcevS
DJaawPIkvjnnApSQ0CNYYKCgB43l33GJQ+btvYQiB/pmPwCiPhdsdYkCgYEAxndh
GVSRd9yHez9LggsTfS4uo1OlZReHrtyX933eEG4YtiwM90Mb/9ZCA6CY5/o8YpOp
AhPu7he3f67cQ7dotjilFHWqi4f+53d8NhfweQhM0azA9zzXjKhsao9jPjtTo+DW
BptWVNZOqv1v0Np4/BZ3rTKtP42vSR4/Ql7Mi0sCgYATzoiH7yIjh2047wTQG0rv
TycJAaqZKvz4RPOVFsYAem63OsVz7tF60zI+mmd9ZP1Q4gsYwORyCLXZo3jlfO5W
FpgtQin66ai2I7F077UZL1KkSEE1LnTTARSTThxeSO5h4o0th+460/EJKiOwf6Wg
a85gxFQi34pb2KzbQ5scuQKBgGLHA9LBnm0Tm3Kh/AjLTnXdSGUNuqHn5iYHsLMD
OEThJvd0UTe3dPYOQ2jew3uhtfAyIcng9egWccPg2cvyOvGGm9LlBW7QzvORKocZ
vxveH62z1461/2oIYX1fxDsy99v2iU9cfMlYqGq+HKrMMa7117aiJEwfToCLx1xX
JmKlAoGAI8aOpSjyQ/xVUS1niXmwbKPkOJP7jI3yQ6YpUEnho/wpFw2/OjuVdXw2
tcYFSg1GjBvTigDeh385TsjDa862SYAslgqZBPN4jXP20xw1kRr9kAQq6bvadC+b
WpwZ8C5vNxwX5ccbxz3WwJhHtZvIQt0J8hOf3+BgcedHxa+bcTQ=
MIIEpQIBAAKCAQEAvxaFFjTE6hi80nhjgfFMM3yPer122OIWIbbumFIuAOcCF6D3
PnRHBdP9IqB99K6Nv6vKK3Jf0Y+dc5ETrg0l0AHYq+dTFTiWusHuRMx6xFjWzO96
7mFmJq6P28dUucKnr6yG1TQeZaq+mHh2DNEnNEYgV7cLVT1unUmMOL/PBh/eCcaJ
8hQNTQafQQknzCnAKC89v33y+rKInJNy9B+zSB0BGCz+eS8MKf6zc78JMSOnF2uj
NK+QEwaYw8lAbJve1F+rCQS0mbm0QvHhZYZrblVHI5l/8LkX5qBtKw7duUhXHxmO
fQieF23bBk9HDp5uQUGsdbKX6ZWitn/h926xyQIDAQABAoIBAQCHXxDRdni5zuSV
xivYdnUhVHDg5zA23ZQINmw5BJ8KjJzy2FnPqNhXzKJb0Y7ptG8/BhinRtOSxkcp
A/IJL89F2MkCn1JAimJd091UZ/fg+X7SmCVikyWm6auIa2IeZ0QcNAEhMVcHdzqn
EU+wLMu1QKjQ+x/QN0ERtHTeDyQ+lUNB+bvAjx3LHN9Zh8weVBHHtwDoyyZDdJPw
NWgpgcW+uYzlT66uh7LPPaRsEZgAkPIkhzZnwmugXdhlWxtYHKTEfe5gCqubQICc
I/x1yBP1EZFm6qBQD4/49775ZbXwxgaWvBXG+Aah9x8JYtVUS4MgrAiC4a8NQqFp
nwKVjUIBAoGBAOWsj9GGb2KYbfLzJNRrSxhs4TUBfpHteKSm2pL92NAbIOjssNhL
hLY3gBFX2RnYmoGD6YT84JNykuAictgAd5GwvLIbaVF9l7MQn8APRbe2CzQ+/494
9hpn33MZOBNd3I+a5+2qoFbXI04loyYDJkkeOqbwZzJjs7k9HmZMNwY5AoGBANT9
tRFWFDvA0pPgGoHhzlsAUAmrbSfCPkhrRXpE9fgl3VnV+NRtjCf9NhJt0uaIokZ5
oSf+jClcwU8N4EvGxMBaCHTqBzgc4dLPWpMAhPoMjjv1Oyug2iBcuTasHVP+Jdgq
CaNzpXOuq4upaaNrq+QMsI6O9wA/zWhWPmnYQYgRAoGAUk56471noU+65zvXUQB6
UvCB7Hrynt0ZRPg+kDrEPh/atV5NKdY2Yw6UqKJwvOBwzkU1pGDzIiQHGqd9vIa+
Usmhdbp5DakSeitU9IEEnQdyEHEbKJFSsLfUzeyVuesDJbt/rh5dg4Fpt5GpW+/5
Am8A2d6BPP+Z4qJSiJp7hZECgYEAy64TCZEXqEytE1yr/KjDfaK+54BX0j2e8gIj
XtmznqoXE2Hboslfzp4Gp3j+xhbDmEGYK3bw8l0RP1g1tkFOxeNTUvq6DJ8SFVbV
dt54S+bV3eCVxRL9hRUmyXGuWjQgXKdWsEhXYFkZE2Xe77h3mI3KCYoOCt74v146
MV3szQECgYEAozTO7Wuum+VMKIY35hmHMjUiYmLl3EXWwMBT2VSsk8Siu0XoH0yd
KoxsLDUBMS8sWKCZhFwU+Fx8UZjfo+xE3H4UTyVsw5EDpB9gSud928gNADwxTKor
3s4jnUzb4XRQ0qN2jXzdNuqXNV1ozeqajbM2oSZqbSnWSs5g6DpIs1Q=
-----END RSA PRIVATE KEY-----
[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.
[*] New RSA-2048 private key has been saved to
/home/doublesine/RegPrivateKey.pem
C:\Users\DoubleSine\source\repos\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
@ -87,47 +82,35 @@
*******************************************************
```
5. Repack files into a new AppImage:
__Example:__
```bash
$ wget 'https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage'
$ chmod +x appimagetool-x86_64.AppImage
$ ./appimagetool-x86_64.AppImage ~/navicat16-premium-en-patched ~/navicat16-premium-en-patched.AppImage
```
6. Run the newly-generated AppImage:
```bash
$ chmod +x ~/navicat16-premium-en-patched.AppImage
$ ~/navicat16-premium-en-patched.AppImage
```
7. Use `navicat-keygen` to generate __snKey__ and __Activation Code__.
2. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```
Usage:
navicat-keygen <--bin|-text> [--adv] <RSA-2048 private key file>
<--bin|--text> Specify "--bin" to generate "license_file" used by Navicat 11.
Specify "--text" to generate base64-encoded activation code.
This parameter is mandatory.
[--adv] Enable advance mode.
This parameter is optional.
<RSA-2048 private key file> A path to an RSA-2048 private key file.
This parameter is mandatory.
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>
```
__Example:__
* `<-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.
```bash
$ ./navicat-keygen --text ./RegPrivateKey.pem
If `-text` is specified, `navicat-keygen.exe` will finally generate a Base64-style string which is __Activation Code__. It is used for Navicat new activation method.
__This parameter must be specified.__
* `[-adv]`: Enable advanced mode.
__This parameter is optional.__ If specified, `navicat-keygen.exe` will ask you input Navicat product ID number, language signature numbers. It is for future use generally.
* `<RSA-2048 Private Key File>`: The full path or relative path to an RSA-2048 private key file. The private key must be in PEM format.
__This parameter must be specified.__
__Example: (in cmd.exe)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
You will be asked to select Navicat language and give major version number. After that an randomly generated __snKey__ will be given.
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
***************************************************
@ -136,88 +119,78 @@
***************************************************
[*] Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
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
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 0
[*] Input major version number:
(range: 11 ~ 16, default: 16)> 16
[*] Serial number:
NAVB-EZF4-7T7X-9MPG
NAVL-GFKA-T5SR-ZFTK
[*] Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code in Base64: (Double press ENTER to end)
[*] Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
3. __Disconnect your network__ and open Navicat. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
4. Generally online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
5. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
CpgnfbIJGmAcxCuo/pAb8EeoS0audZn2NNemg6c3NPK/dWgb343IZQrFwoBZY6lpxE4Fq1BoNmCM75P03XpiXQ+hErcvFWk6iQPDCk/d4msf/AoprIqAMpXFoFLkeP0G93UIIEeBsUej8SrxdDgQDM585iPok5fUW+fTDCD1VICr7DBdL3c/69IxeIgiOQSuImdIQiM3/EOfDiFbAJL9vHW5LxFT8jj+8RPXehwPTBphpInmGdzxVZUZJwAGlXt7orrRbzafdeBjz6MnTajTcJP3SS2dBCiR33UScnyxYGEXdzv7+QLScTmCvI7gqg3Z8DMhroKMoHmy1AvC16FKVw==
[*] Request Info:
{"K":"NAVLGFKAT5SRZFTK", "DI":"7D48FCBD093C778879A1", "P":"WIN"}
[*] Response Info:
{"K":"NAVLGFKAT5SRZFTK","DI":"7D48FCBD093C778879A1","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644387294}
[*] Activation Code:
vwLGmQIWg/DtzHMcaKCDHAjTcBNbTo2VmNllphUSUMgGjgvL6v82ue+GqXB6M/qn48Rj4D4Joqqisr6UwMSclNmQxOQz4RftEpLtG6KBjDo4LM71qn9R/jWoZV5EoHPQkX5gzhO/D7GammrRGn2MV+zI6dJ4c4SBFNnNyjAeEqNzinrQwjB7lUVTlpHEe/SMrdCsGliPZQ/X+5ASbEsq3D8PZsjysJv98MIJrZvdTdznrRe8JzYP+8sbIPQMIX1UDmdyDpbpSl45N92OhO4htz1kFjUEfnrwY0GMOhdYHv/PfMI7RiQzkRyY7pLvX7muJ4dkA+CmMmwew3gy3MWjig==
```
After that, you will be asked to input request code. Now __DO NOT CLOSE KEYGEN__.
6. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully.
8. __Disconnect your network__. Find and click `Registration`.
Fill license key by __Serial number__ that the keygen gave and click `Activate`.
9. Generally online activation will fail and Navicat will ask you do `Manual Activation`, just choose it.
10. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
[*] Input request code in Base64: (Double press ENTER to end)
ds7CnjEnNL+8Rme9Q5iD+3t9Tfuq9W6FzVN/3UZwC5zzecmM9EwyHJuZSovKJNSBTzL6AiGyxliTuKPWmLqAdwiKGLuD+mSaZ0syk0jTakVbXmbAk9maFkTz8SK5jMwnQVM/WBZcI0z2Jg1GnOCZVClu/Lo3/WF+XncS+alc2gshG9dUaI44Cqfvp/u1/EYso5fX/bjeBXaFW1/zj+uuRjVv5l0gt7JsTh9byGVxSDTO4zI64Iz9+58QYCbI9zKM+3G9Gou0UlNKjDYw4gN5+4dpiWAjitVTcL3oQzvflgAXjGlT/P6MA+8Xb5PEPJrEdxsErJObxBhO4cTH52wKoQ==
[*] Request Info:
{"K":"NAVBEZF47T7X9MPG", "DI":"AFCFB038A240942D8776", "P":"linux"}
[*] Response Info:
{"K":"NAVBEZF47T7X9MPG","DI":"AFCFB038A240942D8776","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644837835}
[*] Activation Code:
OY8Ib0brsepeS99it4s4WTDPQuKgu93WembLJ0bzr6M30Wh24reH1/ocaZ2Ek1bRBi5lqu2xBv/MpAcFUlstJANtavArkFnXYv0ZZiF3VF70De5GMe/VjkreNhjCGtTZcQKr8fabBTPjJuN0P+Hi1xWwMs9zJMuH+MJTmCQpbM4gu86YrFK/EDcdHtA4ZFgUI0SgYW8lwFausLFHp7C4uIQNbjtv4KP3XolDUrAx4lqg6bklgZ9C8ZjUpg28VVR9Ym37b1Fup7Y7C8OjmmMiAp8N5z8m6cA/EjcSLfLOMGf8jsAK0GHz5/AGUqAXWifv9h9cxPA35UgytqI9F2IH/Q==
```
11. Finally, you will get __Activation Code__ which looks like a Base64 string.
Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`.
If nothing wrong, activation should be done successfully.
12. Clean up:
```bash
$ rm ~/navicat16-premium-en.AppImage
$ rm -rf ~/navicat16-premium-en-patched
$ mv ~/navicat16-premium-en-patched.AppImage ~/navicat16-premium-en.AppImage
```

View File

@ -1,85 +1,78 @@
# navicat-keygen for linux - 如何使用?
# navicat-keygen for windows - 如何使用这个注册机?
1. 从官网下载Navicat你应该会得到一个AppImage文件例如 `navicat16-premium-en.AppImage`
我假定这个AppImage文件在 `~/` 文件夹下。
2. 提取 `navicat16-premium-en.AppImage` 里的所有文件到一个文件夹,例如 `~/navicat16-premium-en-patched`:
```bash
$ mkdir ~/navicat16-premium-en
$ sudo mount -o loop ~/navicat16-premium-en.AppImage ~/navicat16-premium-en
$ cp -r ~/navicat16-premium-en ~/navicat16-premium-en-patched
$ sudo umount ~/navicat16-premium-en
$ rm -rf ~/navicat16-premium-en
```
3. [编译patcher和keygen](how-to-build.zh-CN.md)。
4. 使用 `navicat-patcher` 替换官方公钥。
1. 使用`navicat-patcher.exe`替换掉`navicat.exe`和`libcc.dll`里的Navicat激活公钥。
```
Usage:
navicat-patcher [OPTION...] <navicat root path> [RSA-2048 private key file]
navicat-patcher.exe [-dry-run] <Navicat Install Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]`: 运行patcher但不对Navicat程序做任何修改。
__这个参数是可选的。__
* `<Navicat Install Path>`: Navicat的完整安装路径。
__这个参数必须指定。__
* `[RSA-2048 PEM File Path]`: RSA-2048私钥文件的完整路径或相对路径。
__这个参数是可选的。__ 如果未指定,`navicat-patcher.exe`将会在当前目录生成一个新的RSA-2048私钥文件。
__例如(在cmd.exe中)__
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 16"
```
--dry-run Run patcher without applying any patches
-h, --help Print help
```
__例如__
```bash
$ ./navicat-patcher ~/navicat16-premium-en-patched
```
__Navicat Premium 16.0.7 英文版 for Linux__ 已经通过测试,下面是一份样例输出:
__Navicat Premium 16.0.7 英文版__ 已通过测试。下面将是一份样例输出:
```
***************************************************
* navicat-patcher by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[+] Try to open libcc.dll ... OK!
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_LINUX_vtable = 0x0000000002fbf038
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey = 0x0000000001420530
[*] patch_solution_since<16, 0, 7, 0>: m_va_pltgot_std_string_append = 0x000000000306a608
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x00000001837759f0
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x0000000181fa52d0
[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x0000000183439bd0
[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAnqeNFqE0n6k+Ys58R+IzIULlZ9oxasJns46vaVcnd9e9mTj4
hf/ArQohP5bex0UD+NGCLfQWKohnQxy9IFjQxZ6wUJnKOaA1UfdRr0ck7LZz5YV2
5CkF4VZ7UWGEp/LEQiJnIBAtp7Zq5PNviqI03PZv2MfZt1/6YstCvi8s0rmpAyTw
V5pteDipsI3lTapysLLsL+kQuJ0Z64GGk5D7rM8UPBt/Wjpe/qb/OwJKJ3Vi65/Z
RRLVt46euwdiW8ORmNt552zOdvQPgYLEP38dMCpoeqIwv7IFWWJHxt0JgOTmxZ5c
hjMq9ns3wyyEFjvSGSpM6sGL5eR1TMDQt8PSIwIDAQABAoIBAAp+jL+VdDSnbj/8
5o2escEeeqwu65vjNhbTdljicfLka18qPI4oh6cqh158bUoDD6syuIivn5O6qBHx
YbU1CsI3p/P86Dp9lWlRka6lZxTdULc6581ZxVDNdqTAbZTqYv745ZdiWpLAZzuz
uooSBqsjBezx8z3E9Hv6c/S+jBl4IcKx7vEgKbC47CAAnFZFGonRPBj88fXn7VmP
KEa7EVIE8yNG/xO4H+hlpio8XsTfbXB4Tx/Mw4f0ZCifFFE9aC503usbTQ9HCRn/
13VgBeFzC+uxluEvpm7r3efcI1vFLDHiKlAzO85vDhTOef3jZv29PTUwbkNCP8AM
CHP9abECgYEAzKWmGRcMVhwKL2RIc0VW1mSW82VTnjuTe9wnonYOGHmxCxQBZpB2
j8mjfPBNzg3pjhRryrmfA2V/1Rxk7/hnw9I+OnRJA2p+USOKVlXi5YA3CMtPcevS
DJaawPIkvjnnApSQ0CNYYKCgB43l33GJQ+btvYQiB/pmPwCiPhdsdYkCgYEAxndh
GVSRd9yHez9LggsTfS4uo1OlZReHrtyX933eEG4YtiwM90Mb/9ZCA6CY5/o8YpOp
AhPu7he3f67cQ7dotjilFHWqi4f+53d8NhfweQhM0azA9zzXjKhsao9jPjtTo+DW
BptWVNZOqv1v0Np4/BZ3rTKtP42vSR4/Ql7Mi0sCgYATzoiH7yIjh2047wTQG0rv
TycJAaqZKvz4RPOVFsYAem63OsVz7tF60zI+mmd9ZP1Q4gsYwORyCLXZo3jlfO5W
FpgtQin66ai2I7F077UZL1KkSEE1LnTTARSTThxeSO5h4o0th+460/EJKiOwf6Wg
a85gxFQi34pb2KzbQ5scuQKBgGLHA9LBnm0Tm3Kh/AjLTnXdSGUNuqHn5iYHsLMD
OEThJvd0UTe3dPYOQ2jew3uhtfAyIcng9egWccPg2cvyOvGGm9LlBW7QzvORKocZ
vxveH62z1461/2oIYX1fxDsy99v2iU9cfMlYqGq+HKrMMa7117aiJEwfToCLx1xX
JmKlAoGAI8aOpSjyQ/xVUS1niXmwbKPkOJP7jI3yQ6YpUEnho/wpFw2/OjuVdXw2
tcYFSg1GjBvTigDeh385TsjDa862SYAslgqZBPN4jXP20xw1kRr9kAQq6bvadC+b
WpwZ8C5vNxwX5ccbxz3WwJhHtZvIQt0J8hOf3+BgcedHxa+bcTQ=
MIIEpQIBAAKCAQEAvxaFFjTE6hi80nhjgfFMM3yPer122OIWIbbumFIuAOcCF6D3
PnRHBdP9IqB99K6Nv6vKK3Jf0Y+dc5ETrg0l0AHYq+dTFTiWusHuRMx6xFjWzO96
7mFmJq6P28dUucKnr6yG1TQeZaq+mHh2DNEnNEYgV7cLVT1unUmMOL/PBh/eCcaJ
8hQNTQafQQknzCnAKC89v33y+rKInJNy9B+zSB0BGCz+eS8MKf6zc78JMSOnF2uj
NK+QEwaYw8lAbJve1F+rCQS0mbm0QvHhZYZrblVHI5l/8LkX5qBtKw7duUhXHxmO
fQieF23bBk9HDp5uQUGsdbKX6ZWitn/h926xyQIDAQABAoIBAQCHXxDRdni5zuSV
xivYdnUhVHDg5zA23ZQINmw5BJ8KjJzy2FnPqNhXzKJb0Y7ptG8/BhinRtOSxkcp
A/IJL89F2MkCn1JAimJd091UZ/fg+X7SmCVikyWm6auIa2IeZ0QcNAEhMVcHdzqn
EU+wLMu1QKjQ+x/QN0ERtHTeDyQ+lUNB+bvAjx3LHN9Zh8weVBHHtwDoyyZDdJPw
NWgpgcW+uYzlT66uh7LPPaRsEZgAkPIkhzZnwmugXdhlWxtYHKTEfe5gCqubQICc
I/x1yBP1EZFm6qBQD4/49775ZbXwxgaWvBXG+Aah9x8JYtVUS4MgrAiC4a8NQqFp
nwKVjUIBAoGBAOWsj9GGb2KYbfLzJNRrSxhs4TUBfpHteKSm2pL92NAbIOjssNhL
hLY3gBFX2RnYmoGD6YT84JNykuAictgAd5GwvLIbaVF9l7MQn8APRbe2CzQ+/494
9hpn33MZOBNd3I+a5+2qoFbXI04loyYDJkkeOqbwZzJjs7k9HmZMNwY5AoGBANT9
tRFWFDvA0pPgGoHhzlsAUAmrbSfCPkhrRXpE9fgl3VnV+NRtjCf9NhJt0uaIokZ5
oSf+jClcwU8N4EvGxMBaCHTqBzgc4dLPWpMAhPoMjjv1Oyug2iBcuTasHVP+Jdgq
CaNzpXOuq4upaaNrq+QMsI6O9wA/zWhWPmnYQYgRAoGAUk56471noU+65zvXUQB6
UvCB7Hrynt0ZRPg+kDrEPh/atV5NKdY2Yw6UqKJwvOBwzkU1pGDzIiQHGqd9vIa+
Usmhdbp5DakSeitU9IEEnQdyEHEbKJFSsLfUzeyVuesDJbt/rh5dg4Fpt5GpW+/5
Am8A2d6BPP+Z4qJSiJp7hZECgYEAy64TCZEXqEytE1yr/KjDfaK+54BX0j2e8gIj
XtmznqoXE2Hboslfzp4Gp3j+xhbDmEGYK3bw8l0RP1g1tkFOxeNTUvq6DJ8SFVbV
dt54S+bV3eCVxRL9hRUmyXGuWjQgXKdWsEhXYFkZE2Xe77h3mI3KCYoOCt74v146
MV3szQECgYEAozTO7Wuum+VMKIY35hmHMjUiYmLl3EXWwMBT2VSsk8Siu0XoH0yd
KoxsLDUBMS8sWKCZhFwU+Fx8UZjfo+xE3H4UTyVsw5EDpB9gSud928gNADwxTKor
3s4jnUzb4XRQ0qN2jXzdNuqXNV1ozeqajbM2oSZqbSnWSs5g6DpIs1Q=
-----END RSA PRIVATE KEY-----
[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.
[*] New RSA-2048 private key has been saved to
/home/doublesine/RegPrivateKey.pem
C:\Users\DoubleSine\source\repos\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
@ -87,47 +80,35 @@
*******************************************************
```
5. 将文件重新打包成AppImage
__例如__
```bash
$ wget 'https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage'
$ chmod +x appimagetool-x86_64.AppImage
$ ./appimagetool-x86_64.AppImage ~/navicat16-premium-en-patched ~/navicat16-premium-en-patched.AppImage
```
6. 运行刚生成的AppImage
```bash
$ chmod +x ~/navicat16-premium-en-patched.AppImage
$ ~/navicat16-premium-en-patched.AppImage
```
7. 使用 `navicat-keygen` 来生成 __序列号____激活码__
2. 接下来使用`navicat-keygen.exe`来生成序列号和激活码
```
Usage:
navicat-keygen <--bin|-text> [--adv] <RSA-2048 private key file>
<--bin|--text> Specify "--bin" to generate "license_file" used by Navicat 11.
Specify "--text" to generate base64-encoded activation code.
This parameter is mandatory.
[--adv] Enable advance mode.
This parameter is optional.
<RSA-2048 private key file> A path to an RSA-2048 private key file.
This parameter is mandatory.
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>
```
__例如__
* `<-bin|-text>`: 必须是`-bin`或`-text`。
```bash
$ ./navicat-keygen --text ./RegPrivateKey.pem
如果指定了`-bin``navicat-keygen.exe`最终将生成`license_file`文件。这个选项是给Navicat旧激活方式使用的。
如果指定了`-text``navicat-keygen.exe`最终将生成Base64样式的激活码。这个选项是给Navicat新激活方式使用的。
__这个参数必须指定。__
* `[-adv]`: 开启高级模式。
__这个参数是可选的。__ 如果指定了这个参数,`navicat-keygen.exe`将会要求你手工填写产品ID号、语言标识号。这个选项一般是给以后用的。
* `<RSA-2048 Private Key File>`: RSA-2048私钥文件的完整路径或相对路径。私钥必须是PEM格式的。
__这个参数必须指定。__
__例如(在cmd.exe中)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
你会被要求选择Navicat产品类别、Navicat语言版本和填写主版本号。之后一个随机生成的 __序列号__ 将会给出。
你会被要求选择Navicat产品类别、语言以及输入主版本号。之后会随机生成一个序列号
```
***************************************************
@ -136,86 +117,78 @@
***************************************************
[*] Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
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
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 0
[*] Input major version number:
(range: 11 ~ 16, default: 16)> 16
[*] Serial number:
NAVB-EZF4-7T7X-9MPG
NAVL-GFKA-T5SR-ZFTK
[*] Your name:
```
你可以使用这个 __序列号__ 来暂时激活Navicat。
你可以使用这个序列号暂时激活Navicat。
之后你会被要求填写 __用户名____组织名__。你可以随意填写,但别太长。
接下来你会被要求输入`用户名`和`组织名`;请随便填写,但不要太长。
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code in Base64: (Double press ENTER to end)
[*] Input request code (in Base64), input empty line to end:
```
之后你会被要求填入请求码。注意 __不要关闭命令行__.
3. __断开网络__ 并打开Navicat。找到`注册`窗口并填入keygen给你的序列号。然后点击`激活`按钮。
4. 一般来说在线激活肯定会失败这时候Navicat会询问你是否`手动激活`,直接选吧。
5. 在`手动激活`窗口你会得到一个请求码复制它并把它粘贴到keygen里。最后别忘了连按至少两下回车结束输入。
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
CpgnfbIJGmAcxCuo/pAb8EeoS0audZn2NNemg6c3NPK/dWgb343IZQrFwoBZY6lpxE4Fq1BoNmCM75P03XpiXQ+hErcvFWk6iQPDCk/d4msf/AoprIqAMpXFoFLkeP0G93UIIEeBsUej8SrxdDgQDM585iPok5fUW+fTDCD1VICr7DBdL3c/69IxeIgiOQSuImdIQiM3/EOfDiFbAJL9vHW5LxFT8jj+8RPXehwPTBphpInmGdzxVZUZJwAGlXt7orrRbzafdeBjz6MnTajTcJP3SS2dBCiR33UScnyxYGEXdzv7+QLScTmCvI7gqg3Z8DMhroKMoHmy1AvC16FKVw==
[*] Request Info:
{"K":"NAVLGFKAT5SRZFTK", "DI":"7D48FCBD093C778879A1", "P":"WIN"}
[*] Response Info:
{"K":"NAVLGFKAT5SRZFTK","DI":"7D48FCBD093C778879A1","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644387294}
[*] Activation Code:
vwLGmQIWg/DtzHMcaKCDHAjTcBNbTo2VmNllphUSUMgGjgvL6v82ue+GqXB6M/qn48Rj4D4Joqqisr6UwMSclNmQxOQz4RftEpLtG6KBjDo4LM71qn9R/jWoZV5EoHPQkX5gzhO/D7GammrRGn2MV+zI6dJ4c4SBFNnNyjAeEqNzinrQwjB7lUVTlpHEe/SMrdCsGliPZQ/X+5ASbEsq3D8PZsjysJv98MIJrZvdTdznrRe8JzYP+8sbIPQMIX1UDmdyDpbpSl45N92OhO4htz1kFjUEfnrwY0GMOhdYHv/PfMI7RiQzkRyY7pLvX7muJ4dkA+CmMmwew3gy3MWjig==
```
之后你会被要求填写请求码。__注意不要关闭keygen。__
6. 如果不出意外你会得到一个看似用Base64编码的激活码。直接复制它并把它粘贴到Navicat的`手动激活`窗口,最后点`激活`按钮。如果没什么意外的话应该能成功激活。
8. __断开网络__. 找到注册窗口填写keygen给你的 __序列号__,然后点击 `激活`
9. 通常在线激活会失败,所以在弹出的提示中选择 `手动激活`
10. 复制 __请求码__ 到keygen连按两次回车结束。
```
[*] Input request code in Base64: (Double press ENTER to end)
ds7CnjEnNL+8Rme9Q5iD+3t9Tfuq9W6FzVN/3UZwC5zzecmM9EwyHJuZSovKJNSBTzL6AiGyxliTuKPWmLqAdwiKGLuD+mSaZ0syk0jTakVbXmbAk9maFkTz8SK5jMwnQVM/WBZcI0z2Jg1GnOCZVClu/Lo3/WF+XncS+alc2gshG9dUaI44Cqfvp/u1/EYso5fX/bjeBXaFW1/zj+uuRjVv5l0gt7JsTh9byGVxSDTO4zI64Iz9+58QYCbI9zKM+3G9Gou0UlNKjDYw4gN5+4dpiWAjitVTcL3oQzvflgAXjGlT/P6MA+8Xb5PEPJrEdxsErJObxBhO4cTH52wKoQ==
[*] Request Info:
{"K":"NAVBEZF47T7X9MPG", "DI":"AFCFB038A240942D8776", "P":"linux"}
[*] Response Info:
{"K":"NAVBEZF47T7X9MPG","DI":"AFCFB038A240942D8776","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644837835}
[*] Activation Code:
OY8Ib0brsepeS99it4s4WTDPQuKgu93WembLJ0bzr6M30Wh24reH1/ocaZ2Ek1bRBi5lqu2xBv/MpAcFUlstJANtavArkFnXYv0ZZiF3VF70De5GMe/VjkreNhjCGtTZcQKr8fabBTPjJuN0P+Hi1xWwMs9zJMuH+MJTmCQpbM4gu86YrFK/EDcdHtA4ZFgUI0SgYW8lwFausLFHp7C4uIQNbjtv4KP3XolDUrAx4lqg6bklgZ9C8ZjUpg28VVR9Ym37b1Fup7Y7C8OjmmMiAp8N5z8m6cA/EjcSLfLOMGf8jsAK0GHz5/AGUqAXWifv9h9cxPA35UgytqI9F2IH/Q==
```
11. 最终你会得到一个base64编码的 __激活码__
将之复制到 `手动激活` 的窗口,然后点击 `激活`
如果没有什么意外,应该可以成功激活。
12. 最后清理:
```bash
$ rm ~/navicat16-premium-en.AppImage
$ rm -rf ~/navicat16-premium-en-patched
$ mv ~/navicat16-premium-en-patched.AppImage ~/navicat16-premium-en.AppImage
```

48
navicat-keygen.sln Normal file
View File

@ -0,0 +1,48 @@

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

View File

@ -1,5 +1,5 @@
#include <iostream>
#include "navicat_serial_generator.hpp"
#include <iostream>
#include "exceptions/operation_canceled_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\CollectInformation.cpp"
@ -8,12 +8,12 @@
namespace nkg {
[[nodiscard]]
static int read_int(int min_val, int max_val, std::string_view prompt, std::string_view error_msg) {
static int read_int(int min_val, int max_val, std::wstring_view prompt, std::wstring_view error_msg) {
int val;
for (std::string s;;) {
std::cout << prompt;
if (!std::getline(std::cin, s)) {
for (std::wstring s;;) {
std::wcout << prompt;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
}
@ -25,21 +25,21 @@ namespace nkg {
if (min_val <= val && val <= max_val) {
return val;
} else {
throw std::invalid_argument("Out of range.");
throw std::invalid_argument(u8"");
}
} catch (std::invalid_argument&) {
std::cout << error_msg << std::endl;
std::wcout << error_msg << std::endl;
}
}
}
[[nodiscard]]
static int read_int(int min_val, int max_val, int default_val, std::string_view prompt, std::string_view error_msg) {
static int read_int(int min_val, int max_val, int default_val, std::wstring_view prompt, std::wstring_view error_msg) {
int val;
for (std::string s;;) {
std::cout << prompt;
if (!std::getline(std::cin, s)) {
for (std::wstring s;;) {
std::wcout << prompt;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
}
@ -52,10 +52,10 @@ namespace nkg {
if (min_val <= val && val <= max_val) {
return val;
} else {
throw std::invalid_argument("Out of range.");
throw std::invalid_argument(u8"");
}
} catch (std::invalid_argument&) {
std::cout << error_msg << std::endl;
std::wcout << error_msg << std::endl;
}
}
}
@ -64,43 +64,43 @@ namespace nkg {
navicat_serial_generator CollectInformationNormal() {
navicat_serial_generator sn_generator;
std::cout << "[*] Select Navicat product:" << std::endl;
std::cout << " 0. DataModeler" << std::endl;
std::cout << " 1. Premium" << std::endl;
std::cout << " 2. MySQL" << std::endl;
std::cout << " 3. PostgreSQL" << std::endl;
std::cout << " 4. Oracle" << std::endl;
std::cout << " 5. SQLServer" << std::endl;
std::cout << " 6. SQLite" << std::endl;
std::cout << " 7. MariaDB" << std::endl;
std::cout << " 8. MongoDB" << std::endl;
std::cout << " 9. ReportViewer" << std::endl;
std::cout << " 10. ChartsCreator" << std::endl;
std::cout << " 11. ChartsViewer" << std::endl;
std::cout << std::endl;
sn_generator.set_software_type(static_cast<navicat_software_type>(read_int(0, 11, "(Input index)> ", "Invalid index.")));
std::wcout << L"[*] Select Navicat product:" << std::endl;
std::wcout << L" 0. DataModeler" << std::endl;
std::wcout << L" 1. Premium" << std::endl;
std::wcout << L" 2. MySQL" << std::endl;
std::wcout << L" 3. PostgreSQL" << std::endl;
std::wcout << L" 4. Oracle" << std::endl;
std::wcout << L" 5. SQLServer" << std::endl;
std::wcout << L" 6. SQLite" << std::endl;
std::wcout << L" 7. MariaDB" << std::endl;
std::wcout << L" 8. MongoDB" << std::endl;
std::wcout << L" 9. ReportViewer" << std::endl;
std::wcout << L" 10. ChartsCreator" << std::endl;
std::wcout << L" 11. ChartsViewer" << std::endl;
std::wcout << std::endl;
sn_generator.set_software_type(static_cast<navicat_software_type>(read_int(0, 11, L"(Input index)> ", L"Invalid index.")));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Select product language:" << std::endl;
std::cout << " 0. English" << std::endl;
std::cout << " 1. Simplified Chinese" << std::endl;
std::cout << " 2. Traditional Chinese" << std::endl;
std::cout << " 3. Japanese" << std::endl;
std::cout << " 4. Polish" << std::endl;
std::cout << " 5. Spanish" << std::endl;
std::cout << " 6. French" << std::endl;
std::cout << " 7. German" << std::endl;
std::cout << " 8. Korean" << std::endl;
std::cout << " 9. Russian" << std::endl;
std::cout << " 10. Portuguese" << std::endl;
std::cout << std::endl;
sn_generator.set_software_language(static_cast<navicat_software_language>(read_int(0, 10, "(Input index)> ", "Invalid index.")));
std::wcout << L"[*] Select product language:" << std::endl;
std::wcout << L" 0. English" << std::endl;
std::wcout << L" 1. Simplified Chinese" << std::endl;
std::wcout << L" 2. Traditional Chinese" << std::endl;
std::wcout << L" 3. Japanese" << std::endl;
std::wcout << L" 4. Polish" << std::endl;
std::wcout << L" 5. Spanish" << std::endl;
std::wcout << L" 6. French" << std::endl;
std::wcout << L" 7. German" << std::endl;
std::wcout << L" 8. Korean" << std::endl;
std::wcout << L" 9. Russian" << std::endl;
std::wcout << L" 10. Portuguese" << std::endl;
std::wcout << std::endl;
sn_generator.set_software_language(static_cast<navicat_software_language>(read_int(0, 10, L"(Input index)> ", L"Invalid index.")));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(1, 16, 16, "(range: 1 ~ 16, default: 16)> ", "Invalid number."));
std::wcout << L"[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(1, 16, 16, L"(range: 1 ~ 16, default: 16)> ", L"Invalid number."));
std::wcout << std::endl;
std::cout << std::endl;
return sn_generator;
}
@ -108,24 +108,23 @@ namespace nkg {
navicat_serial_generator CollectInformationAdvanced() {
navicat_serial_generator sn_generator;
std::cout << "[*] Navicat Product Signature:" << std::endl;
sn_generator.set_software_type(static_cast<uint8_t>(read_int(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number.")));
std::wcout << L"[*] Navicat Product Signature:" << std::endl;
sn_generator.set_software_type(static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number.")));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Navicat Language Signature 0:" << std::endl;
auto s1 = static_cast<uint8_t>(read_int(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number."));
std::wcout << L"[*] Navicat Language Signature 0:" << std::endl;
auto s1 = static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number."));
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Navicat Language Signature 1:" << std::endl;
auto s2 = static_cast<uint8_t>(read_int(0x00, 0xff, "(range: 0x00 ~ 0xFF)> ", "Invalid number."));
std::wcout << L"[*] Navicat Language Signature 1:" << std::endl;
auto s2 = static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number."));
sn_generator.set_software_language(s1, s2);
std::wcout << std::endl;
std::cout << std::endl;
std::cout << "[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(1, 16, 16, "(range: 1 ~ 16, default: 16)> ", "Invalid number."));
std::wcout << L"[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(1, 16, 16, L"(range: 1 ~ 16, default: 16)> ", L"Invalid number."));
std::wcout << std::endl;
std::cout << std::endl;
return sn_generator;
}
}

View File

@ -1,17 +1,17 @@
#include <iostream>
#include <ctime>
#include <fmt/format.h>
#include <fcntl.h>
#include "exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#include "exceptions/unix_exception.hpp"
#include "exceptions/win32_exception.hpp"
#include "resource_wrapper.hpp"
#include "resource_traits/unix_os/file_descriptor.hpp"
#include "resource_traits/win32/file_handle.hpp"
#include "rsa_cipher.hpp"
#include "navicat_serial_generator.hpp"
#include "cp_converter.hpp"
#include "base64_rfc4648.hpp"
#include "navicat_serial_generator.hpp"
#include "rsa_cipher.hpp"
#include <iostream>
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
@ -23,53 +23,62 @@
namespace nkg {
void GenerateLicenseText(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
std::string b64_request_code;
std::vector<uint8_t> request_code;
std::wstring b64_request_code;
std::vector<std::uint8_t> request_code;
std::string u8_request_info;
std::string u8_response_info;
std::vector<uint8_t> response_code;
std::string b64_response_code;
std::vector<std::uint8_t> response_code;
std::wstring b64_response_code;
std::cout << "[*] Your name: ";
if (!std::getline(std::cin, u8_username)) {
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
}
std::cout << "[*] Your organization: ";
if (!std::getline(std::cin, u8_organization)) {
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
}
std::cout << std::endl;
std::cout << "[*] Input request code in Base64: (Double press ENTER to end)" << std::endl;
std::wcout << std::endl;
std::wcout << L"[*] Input request code in Base64: (Input empty line to end)" << std::endl;
while (true) {
std::string temp;
if (!std::getline(std::cin, temp)) {
std::wstring s;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
}
if (temp.empty()) {
if (s.empty()) {
break;
}
b64_request_code.append(temp);
b64_request_code.append(s);
}
request_code = base64_rfc4648::decode(b64_request_code);
if (request_code.size() != 256) {
throw ::nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Broken request code. %zu", request_code.size()));
if (b64_request_code.empty()) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Nothing inputs, abort!");
}
request_code = base64_rfc4648::decode(cp_converter<-1, CP_UTF8>::convert(b64_request_code));
u8_request_info.resize((cipher.bits() + 7) / 8);
u8_request_info.resize(cipher.private_decrypt(request_code.data(), request_code.size(), u8_request_info.data(), RSA_PKCS1_PADDING));
while (u8_request_info.back() == '\x00') {
u8_request_info.pop_back();
}
std::cout << "[*] Request Info:" << std::endl;
std::cout << u8_request_info << std::endl;
std::cout << std::endl;
std::wcout << L"[*] Request Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_request_info) << std::endl;
std::wcout << std::endl;
rapidjson::Document json;
rapidjson::Value N_Key;
@ -82,77 +91,89 @@ namespace nkg {
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//
// Begin to parse
// begin to parse
//
json.Parse(u8_request_info.c_str());
//
// Remove "Platform" info
// remove "Platform" info
//
json.RemoveMember("P");
json.RemoveMember(u8"P");
//
// Set "Name" info
// set "Name" info
//
N_Key.SetString("N", 1);
N_Key.SetString(u8"N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
//
// Set "Organization" info
// set "Organization" info
//
O_Key.SetString("O", 1);
O_Key.SetString(u8"O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
//
// Set "Time" info
// set "Time" info
//
T_Key.SetString("T", 1);
T_Key.SetString(u8"T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
//
// Add "Name", "Organization" and "Time"
// add "Name", "Organization" and "Time"
//
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw ::nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::cout << "[*] Response Info:" << std::endl;
std::cout << u8_response_info << std::endl;
std::cout << std::endl;
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
b64_response_code = cp_converter<CP_UTF8, -1>::convert(base64_rfc4648::encode(response_code));
b64_response_code = base64_rfc4648::encode(response_code);
std::cout << "[*] Activation Code:" << std::endl;
std::cout << b64_response_code << std::endl;
std::cout << std::endl;
std::wcout << L"[*] Activation Code:" << std::endl;
std::wcout << b64_response_code << std::endl;
std::wcout << std::endl;
}
void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::string u8_serial_number = sn_generator.serial_number();
std::string utf8SerialNumber = sn_generator.serial_number();
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
std::string u8_response_info;
std::vector<uint8_t> response_code;
std::vector<std::uint8_t> response_code;
std::cout << "[*] Your name: ";
if (!std::getline(std::cin, u8_username)) {
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
}
std::cout << "[*] Your organization: ";
if (!std::getline(std::cin, u8_organization)) {
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
}
std::cout << std::endl;
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
@ -167,7 +188,7 @@ namespace nkg {
json.Parse("{}");
K_Key.SetString("K", 1);
K_Value.SetString(u8_serial_number.c_str(), static_cast<rapidjson::SizeType>(u8_serial_number.length()));
K_Value.SetString(utf8SerialNumber.c_str(), static_cast<rapidjson::SizeType>(utf8SerialNumber.length()));
N_Key.SetString("N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
O_Key.SetString("O", 1);
@ -180,31 +201,36 @@ namespace nkg {
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw ::nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::cout << "[*] Response Info:" << std::endl;
std::cout << u8_response_info << std::endl;
std::cout << std::endl;
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
resource_wrapper license_file{ resource_traits::unix_os::file_descriptor{}, open("license_file", O_WRONLY | O_CREAT | O_TRUNC, 0666) };
if (!license_file.is_valid()) {
throw exceptions::unix_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), errno, u8"open failed.");
resource_wrapper license_file{ resource_traits::win32::file_handle{}, CreateFileW(L"license_file", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL) };
if (license_file.is_valid() == false) {
throw exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"CreateFileW failed.");
}
if (write(license_file.get(), response_code.data(), response_code.size()) < 0) {
throw exceptions::unix_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), errno, u8"write failed.");
if (DWORD _; WriteFile(license_file.get(), response_code.data(), static_cast<DWORD>(response_code.size()), &_, NULL) == FALSE) {
throw exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"WriteFile failed.");
}
std::cout << "[+] license_file has been generated." << std::endl;
std::wcout << L"[+] license_file has been generated." << std::endl;
}
}
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,6 +1,4 @@
#include "base32_rfc4648.hpp"
#include <limits>
#include <algorithm>
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\base32_rfc4648.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
@ -17,7 +15,7 @@ namespace nkg {
} else if ('2' <= c && c <= '7') {
return c - '2' + 26;
} else {
throw decoding_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Non-base32 digit is found.");
throw decoding_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Non-base32 digit is found");
}
}
@ -66,10 +64,10 @@ namespace nkg {
retval.append(1, padding_character);
break;
default:
__builtin_unreachable();
__assume(false);
}
}
return retval;
}

View File

@ -1,8 +1,13 @@
#pragma once
#include <limits>
#include <string>
#include <vector>
#include <algorithm>
#include "exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\base32_rfc4648.hpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
struct base32_rfc4648 {
@ -11,7 +16,11 @@ namespace nkg {
static constexpr const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static constexpr const char padding_character = '=';
class decoding_error;
class decoding_error : public ::nkg::exception {
public:
decoding_error(std::string_view file, int line, std::string_view message) noexcept :
::nkg::exception(file, line, message) {}
};
static char symbol(alphabet_index_t idx);
@ -24,8 +33,7 @@ namespace nkg {
static std::vector<uint8_t> decode(std::string_view b32_string);
};
class base32_rfc4648::decoding_error : public ::nkg::exception {
using ::nkg::exception::exception;
};
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -7,6 +7,10 @@
#include "resource_traits/openssl/bio.hpp"
#include "resource_traits/openssl/bio_chain.hpp"
#pragma comment(lib, "libcrypto")
#pragma comment(lib, "crypt32") // required by libcrypto.lib
#pragma comment(lib, "ws2_32") // required by libcrypto.lib
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\base64_rfc4648.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
@ -14,14 +18,14 @@ namespace nkg {
std::string base64_rfc4648::encode(const std::vector<std::uint8_t>& data) {
resource_wrapper bio_b64{ resource_traits::openssl::bio_chain{}, BIO_new(BIO_f_base64()) };
if (!bio_b64.is_valid()) {
if (bio_b64.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
BIO_set_flags(bio_b64.get(), BIO_FLAGS_BASE64_NO_NL);
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (!bio_memory.is_valid()) {
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
@ -51,14 +55,14 @@ namespace nkg {
std::vector<uint8_t> base64_rfc4648::decode(std::string_view b64_string) {
resource_wrapper bio_b64{ resource_traits::openssl::bio_chain{}, BIO_new(BIO_f_base64()) };
if (!bio_b64.is_valid()) {
if (bio_b64.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}
BIO_set_flags(bio_b64.get(), BIO_FLAGS_BASE64_NO_NL);
resource_wrapper bio_memory{ resource_traits::openssl::bio{}, BIO_new(BIO_s_mem()) };
if (!bio_memory.is_valid()) {
if (bio_memory.is_valid() == false) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"BIO_new failed.");
}

View File

@ -6,15 +6,15 @@
namespace nkg {
struct base64_rfc4648 {
class backend_error;
class backend_error : public ::nkg::exception {
public:
backend_error(std::string_view file, int line, std::string_view message) noexcept :
::nkg::exception(file, line, message) {}
};
static std::string encode(const std::vector<std::uint8_t>& data);
static std::vector<uint8_t> decode(std::string_view str_b64);
};
class base64_rfc4648::backend_error : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

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

View File

@ -0,0 +1,187 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{6d262af4-5dac-4f0c-b3d6-23c9cbea9756}</ProjectGuid>
<RootNamespace>navicatkeygen</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
<Import Project="..\common\common.vcxitems" Label="Shared" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" />
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="base32_rfc4648.cpp" />
<ClCompile Include="base64_rfc4648.cpp" />
<ClCompile Include="CollectInformation.cpp" />
<ClCompile Include="GenerateLicense.cpp" />
<ClCompile Include="navicat_serial_generator.cpp" />
<ClCompile Include="wmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="base32_rfc4648.hpp" />
<ClInclude Include="base64_rfc4648.hpp" />
<ClInclude Include="navicat_serial_generator.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="wmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="base64_rfc4648.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="navicat_serial_generator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CollectInformation.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="GenerateLicense.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="base32_rfc4648.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="base64_rfc4648.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="navicat_serial_generator.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="base32_rfc4648.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>

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>

View File

@ -18,7 +18,7 @@
namespace nkg {
char navicat_serial_generator::_replace_confusing_chars(char c) {
char navicat_serial_generator::_replace_confusing_chars(char c) noexcept {
if (c == 'I') {
return '8';
} else if (c == 'O') {
@ -78,7 +78,7 @@ namespace nkg {
m_data[6] = 0x49; // Must be 0x49 for Portuguese version. Discoverer: @dragonflylee
break;
default:
__builtin_unreachable();
break;
}
}
@ -126,7 +126,7 @@ namespace nkg {
m_data[7] = 0x88;
break;
default:
__builtin_unreachable();
break;
}
}
@ -166,7 +166,7 @@ namespace nkg {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_CIPHER_CTX_new failed.");
}
if (EVP_EncryptInit_ex(evp_cipher_context.get(), EVP_des_ecb(), nullptr, m_des_key, nullptr) <= 0) { // return 1 for success and 0 for failure
if (EVP_EncryptInit(evp_cipher_context.get(), EVP_des_ecb(), m_des_key, nullptr) <= 0) { // return 1 for success and 0 for failure
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"EVP_EncryptInit failed.");
}

View File

@ -40,15 +40,15 @@ namespace nkg {
class backend_error;
private:
static inline const uint8_t s_des_key0[8] = { 0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27 };
static inline const uint8_t s_des_key1[8] = { 0xE9, 0x7F, 0xB0, 0x60, 0x77, 0x45, 0x90, 0xAE };
static inline const uint8_t s_des_key0[8] = {0x64, 0xAD, 0xF3, 0x2F, 0xAE, 0xF2, 0x1A, 0x27};
static inline const uint8_t s_des_key1[8] = {0xE9, 0x7F, 0xB0, 0x60, 0x77, 0x45, 0x90, 0xAE};
uint8_t m_data[10];
uint8_t m_des_key[8];
std::string m_serial_number;
std::string m_serial_number_formatted;
static char _replace_confusing_chars(char c);
static char _replace_confusing_chars(char c) noexcept;
public:
navicat_serial_generator() noexcept;
@ -79,3 +79,4 @@ namespace nkg {
};
}

121
navicat-keygen/wmain.cpp Normal file
View File

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

View File

@ -1,7 +1,6 @@
#define _CRT_SECURE_NO_WARNINGS
#include "amd64_emulator.hpp"
#include "exceptions/key_exception.hpp"
#include "resource_traits/unicorn/unicorn_alloc.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\amd64_emulator.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
@ -10,20 +9,17 @@ namespace nkg {
void amd64_emulator::_unicorn_hookcode_cb_stub(uc_engine* uc, uint64_t address, uint32_t size, void* user_data) {
auto hook_stub_ctx = reinterpret_cast<hook_stub_context_t*>(user_data);
auto& hook_callback = std::any_cast<std::function<hookcode_cb_t>&>(hook_stub_ctx->self->m_unicorn_hook_callbacks[hook_stub_ctx->unicorn_hook_handle]);
hook_callback(address, size);
hook_stub_ctx->self->m_unicorn_hook_cbs_hookcode[hook_stub_ctx->unicorn_hook_handle](address, size);
}
void amd64_emulator::_unicorn_hookmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data) {
auto hook_stub_ctx = reinterpret_cast<hook_stub_context_t*>(user_data);
auto& hook_callback = std::any_cast<std::function<hookmem_cb_t>&>(hook_stub_ctx->self->m_unicorn_hook_callbacks[hook_stub_ctx->unicorn_hook_handle]);
hook_callback(type, address, static_cast<unsigned int>(size), value);
hook_stub_ctx->self->m_unicorn_hook_cbs_hookmem[hook_stub_ctx->unicorn_hook_handle](type, address, static_cast<unsigned int>(size), value);
}
bool amd64_emulator::_unicorn_eventmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data) {
auto hook_stub_ctx = reinterpret_cast<hook_stub_context_t*>(user_data);
auto& hook_callback = std::any_cast<std::function<eventmem_cb_t>&>(hook_stub_ctx->self->m_unicorn_hook_callbacks[hook_stub_ctx->unicorn_hook_handle]);
return hook_callback(type, address, static_cast<unsigned int>(size), value);
return hook_stub_ctx->self->m_unicorn_hook_cbs_eventmem[hook_stub_ctx->unicorn_hook_handle](type, address, static_cast<unsigned int>(size), value);
}
amd64_emulator::amd64_emulator() {
@ -72,21 +68,21 @@ namespace nkg {
void amd64_emulator::mem_map(uint64_t address, size_t size, uint32_t perms) {
auto err = uc_mem_map(m_unicorn_engine.get(), address, size, perms);
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_map failed.");
}
}
void amd64_emulator::mem_unmap(uint64_t address, size_t size) {
auto err = uc_mem_unmap(m_unicorn_engine.get(), address, size);
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_unmap failed.");
}
}
void amd64_emulator::mem_read(uint64_t address, void* buf, size_t size) {
auto err = uc_mem_read(m_unicorn_engine.get(), address, buf, size);
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_read failed.");
}
}
@ -95,7 +91,7 @@ namespace nkg {
std::vector<uint8_t> ret_buf(size);
auto err = uc_mem_read(m_unicorn_engine.get(), address, ret_buf.data(), ret_buf.size());
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_read failed.");
}
@ -104,7 +100,7 @@ namespace nkg {
void amd64_emulator::mem_write(uint64_t address, const void* buf, size_t size) {
auto err = uc_mem_write(m_unicorn_engine.get(), address, buf, size);
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_write failed.");
}
}
@ -113,56 +109,61 @@ namespace nkg {
mem_write(address, buf.data(), buf.size());
}
bool amd64_emulator::is_address_mapped(uint64_t address) {
resource_wrapper mapped_regions{ resource_traits::unicorn::unicorn_alloc{} };
uint32_t mapped_regions_num;
auto err = uc_mem_regions(m_unicorn_engine.get(), mapped_regions.unsafe_addressof<uc_mem_region*>(), &mapped_regions_num);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_mem_regions failed.");
}
for (size_t i = 0; i < mapped_regions_num; ++i) {
auto& region = mapped_regions.as<uc_mem_region*>()[i];
if (region.begin <= address && address <= region.end) {
return true;
}
}
return false;
}
void amd64_emulator::hook_del(uc_hook hook_handle) {
auto iter_of_hook_stub_ctxs = m_unicorn_hook_stub_ctxs.find(hook_handle);
if (iter_of_hook_stub_ctxs == m_unicorn_hook_stub_ctxs.end()) {
throw exceptions::key_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Target hook is not found.");
}
auto iter_of_hook_callbacks = m_unicorn_hook_callbacks.find(hook_handle);
if (iter_of_hook_callbacks != m_unicorn_hook_callbacks.end()) {
auto iter_of_hook_cbs_hookcode = m_unicorn_hook_cbs_hookcode.find(hook_handle);
if (iter_of_hook_cbs_hookcode != m_unicorn_hook_cbs_hookcode.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_callbacks.erase(iter_of_hook_callbacks);
m_unicorn_hook_cbs_hookcode.erase(iter_of_hook_cbs_hookcode);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
__builtin_unreachable();
auto iter_of_hook_cbs_hookmem = m_unicorn_hook_cbs_hookmem.find(hook_handle);
if (iter_of_hook_cbs_hookmem != m_unicorn_hook_cbs_hookmem.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_cbs_hookmem.erase(iter_of_hook_cbs_hookmem);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
auto iter_of_hook_cbs_eventmem = m_unicorn_hook_cbs_eventmem.find(hook_handle);
if (iter_of_hook_cbs_eventmem != m_unicorn_hook_cbs_eventmem.end()) {
auto err = uc_hook_del(m_unicorn_engine.get(), hook_handle);
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"hook_del failed.");
}
m_unicorn_hook_cbs_eventmem.erase(iter_of_hook_cbs_eventmem);
m_unicorn_hook_stub_ctxs.erase(iter_of_hook_stub_ctxs);
return;
}
__assume(false);
}
void amd64_emulator::emu_start(uint64_t begin_address, uint64_t end_address, uint64_t timeout, size_t count) {
auto err = uc_emu_start(m_unicorn_engine.get(), begin_address, end_address, timeout, count);
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"emu_start failed.");
}
}
void amd64_emulator::emu_stop() {
auto err = uc_emu_stop(m_unicorn_engine.get());
if (err != UC_ERR_OK) {
if (err) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_emu_stop failed.");
}
}

View File

@ -1,12 +1,17 @@
#pragma once
#include <winsock2.h>
#include <windows.h>
#include <unicorn/unicorn.h>
#include <any>
#include <memory>
#include <string>
#include <unordered_map>
#include <functional>
#include <unicorn/unicorn.h>
#include "resource_wrapper.hpp"
#include "resource_traits/unicorn/unicorn_handle.hpp"
#include "exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\amd64_emulator.hpp"
@ -54,10 +59,14 @@ namespace nkg {
uc_hook unicorn_hook_handle;
};
resource_wrapper<resource_traits::unicorn::unicorn_handle> m_unicorn_engine;
std::unordered_map<std::string, std::any> m_unicorn_user_ctx;
std::unordered_map<uc_hook, std::unique_ptr<hook_stub_context_t>> m_unicorn_hook_stub_ctxs;
std::unordered_map<uc_hook, std::any> m_unicorn_hook_callbacks;
resource_wrapper<resource_traits::unicorn::unicorn_handle> m_unicorn_engine;
std::unordered_map<std::string, std::any> m_unicorn_user_ctx;
std::unordered_map<uc_hook, std::unique_ptr<hook_stub_context_t>> m_unicorn_hook_stub_ctxs;
std::unordered_map<uc_hook, std::function<hookcode_cb_t>> m_unicorn_hook_cbs_hookcode;
std::unordered_map<uc_hook, std::function<hookmem_cb_t>> m_unicorn_hook_cbs_hookmem;
std::unordered_map<uc_hook, std::function<eventmem_cb_t>> m_unicorn_hook_cbs_eventmem;
static void _unicorn_hookcode_cb_stub(uc_engine* uc, uint64_t address, uint32_t size, void* user_data);
static void _unicorn_hookmem_cb_stub(uc_engine* uc, uc_mem_type type, uint64_t address, int size, int64_t value, void* user_data);
@ -86,8 +95,6 @@ namespace nkg {
void mem_write(uint64_t address, const std::vector<uint8_t>& buf);
bool is_address_mapped(uint64_t address);
template<int hook_type, typename callable_t>
uc_hook hook_add(callable_t&& hook_callback, uint64_t begin_address = 1, uint64_t end_address = 0) {
uc_err err;
@ -97,31 +104,31 @@ namespace nkg {
hook_stub_ctx->unicorn_hook_handle = 0;
if constexpr (hook_type == UC_HOOK_CODE) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, reinterpret_cast<void*>(_unicorn_hookcode_cb_stub), hook_stub_ctx.get(), begin_address, end_address);
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_hookcode_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_callbacks.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::function<hookcode_cb_t>{ std::forward<callable_t>(hook_callback) }));
m_unicorn_hook_cbs_hookcode.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::forward<callable_t>(hook_callback)));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_VALID) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, reinterpret_cast<void*>(_unicorn_hookmem_cb_stub), hook_stub_ctx.get(), begin_address, end_address);
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_hookmem_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_callbacks.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::function<hookmem_cb_t>{ std::forward<callable_t>(hook_callback) }));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0 || (hook_type & ~UC_HOOK_MEM_PROT) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, reinterpret_cast<void*>(_unicorn_eventmem_cb_stub), hook_stub_ctx.get(), begin_address, end_address);
m_unicorn_hook_cbs_hookmem.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::forward<callable_t>(hook_callback)));
} else if constexpr ((hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0) {
err = uc_hook_add(m_unicorn_engine.get(), &hook_stub_ctx->unicorn_hook_handle, hook_type, _unicorn_eventmem_cb_stub, hook_stub_ctx.get(), begin_address, end_address);
if (err != UC_ERR_OK) {
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"uc_hook_add failed.");
}
m_unicorn_hook_callbacks.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::function<eventmem_cb_t>{ std::forward<callable_t>(hook_callback) }));
m_unicorn_hook_cbs_eventmem.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::forward<callable_t>(hook_callback)));
} else {
static_assert(
hook_type == UC_HOOK_CODE ||
(hook_type & ~UC_HOOK_MEM_VALID) == 0 ||
(hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0 || (hook_type & ~UC_HOOK_MEM_PROT) == 0, "Unsupported hook type.");
(hook_type & ~UC_HOOK_MEM_UNMAPPED) == 0, "Unsupported hook type.");
}
return m_unicorn_hook_stub_ctxs.emplace(std::make_pair(hook_stub_ctx->unicorn_hook_handle, std::move(hook_stub_ctx))).first->first;

View File

@ -1,635 +0,0 @@
#include "elf64_interpreter.hpp"
#include "exceptions/index_exception.hpp"
#include "exceptions/key_exception.hpp"
#include <memory.h>
#include <algorithm>
#include <fmt/format.h>
#define NKG_CURRENT_SOURCE_FILE() ".\\navicat-patcher\\elf64_interpreter.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
elf64_interpreter::elf64_interpreter() :
m_elf_size(0),
m_elf_header(nullptr),
m_elf_program_headers(nullptr),
m_elf_section_headers(nullptr),
m_dynamic_rela(nullptr),
m_dynamic_relasz(nullptr),
m_dynamic_rel(nullptr),
m_dynamic_relsz(nullptr),
m_dynamic_pltgot(nullptr),
m_dynamic_jmprel(nullptr),
m_dynamic_pltrel(nullptr),
m_dynamic_pltrelsz(nullptr),
m_dynamic_symtab(nullptr),
m_dynamic_strtab(nullptr) {}
[[nodiscard]]
elf64_interpreter elf64_interpreter::parse(void* image_ptr, size_t image_size) {
elf64_interpreter new_image;
// check ELF header
new_image.m_elf_size = image_size;
new_image.m_elf_header = reinterpret_cast<Elf64_Ehdr*>(image_ptr);
if (is_address_in_range(new_image.m_elf_header, sizeof(Elf64_Ehdr), image_ptr, image_size) == false) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: image is corrupted.");
}
if (memcmp(new_image.m_elf_header->e_ident, ELFMAG, SELFMAG) != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: header magic check failed.");
}
if (new_image.m_elf_header->e_ident[EI_CLASS] != ELFCLASS64) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Unsupported ELF file: not ELF64 image.");
}
if (new_image.m_elf_header->e_ident[EI_DATA] == ELFDATA2LSB && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) {
; // pass
} else if (new_image.m_elf_header->e_ident[EI_DATA] == ELFDATA2MSB && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) {
; // pass
} else {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Unsupported ELF file: unsupported endian.");
}
if (new_image.m_elf_header->e_ident[EI_VERSION] != EV_CURRENT) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_ident[EI_VERSION] check failed.");
}
// new_image.m_elf_header->e_ident[EI_OSABI]
// new_image.m_elf_header->e_ident[EI_ABIVERSION]
for (int i = EI_PAD; i < sizeof(new_image.m_elf_header->e_ident); ++i) {
if (new_image.m_elf_header->e_ident[i] != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_ident padding contains non-zero byte(s).");
}
}
if (new_image.m_elf_header->e_version != EV_CURRENT) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_version check failed.");
}
if (new_image.m_elf_header->e_ehsize != sizeof(Elf64_Ehdr)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_ehsize check failed.");
}
if (new_image.m_elf_header->e_phoff && new_image.m_elf_header->e_phentsize && new_image.m_elf_header->e_phnum) {
if (new_image.m_elf_header->e_phentsize != sizeof(Elf64_Phdr)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_phentsize check failed.");
}
new_image.m_elf_program_headers = address_offset_cast<Elf64_Phdr*>(image_ptr, new_image.m_elf_header->e_phoff);
if (is_address_in_range(new_image.m_elf_program_headers, new_image.m_elf_header->e_phnum * sizeof(Elf64_Phdr), image_ptr, image_size) == false) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: image is corrupted.");
}
} else if (new_image.m_elf_header->e_phoff == 0 && new_image.m_elf_header->e_phentsize == 0 && new_image.m_elf_header->e_phnum == 0) {
new_image.m_elf_program_headers = nullptr;
} else {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_ph* check failed.");
}
if (new_image.m_elf_header->e_shoff && new_image.m_elf_header->e_shentsize && new_image.m_elf_header->e_shnum) {
if (new_image.m_elf_header->e_shentsize != sizeof(Elf64_Shdr)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_shentsize check failed.");
}
new_image.m_elf_section_headers = address_offset_cast<Elf64_Shdr*>(image_ptr, new_image.m_elf_header->e_shoff);
if (is_address_in_range(new_image.m_elf_section_headers, new_image.m_elf_header->e_shnum * sizeof(Elf64_Shdr), image_ptr, image_size) == false) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: image is corrupted.");
}
} else if (new_image.m_elf_header->e_shoff == 0 && new_image.m_elf_header->e_shentsize == 0 && new_image.m_elf_header->e_shnum == 0) {
new_image.m_elf_section_headers = nullptr;
} else {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_sh* check failed.");
}
if (new_image.m_elf_header->e_shstrndx != SHN_UNDEF) {
if (new_image.m_elf_header->e_shstrndx >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: Elf64_Ehdr::e_shstrndx is out of range.");
}
}
// check program header table and section header table are not overlapped
if (new_image.m_elf_program_headers && new_image.m_elf_section_headers) {
auto a1 = new_image.m_elf_program_headers;
auto a2 = new_image.m_elf_program_headers + new_image.m_elf_header->e_phnum;
auto b1 = new_image.m_elf_section_headers;
auto b2 = new_image.m_elf_section_headers + new_image.m_elf_header->e_shnum;
bool not_overlapped = address_delta(a1, b1) < 0 && address_delta(a2, b1) <= 0 || address_delta(b1, a1) < 0 && address_delta(b2, a1) <= 0;
if (!not_overlapped) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: program header table and section header table overlapped.");
}
}
// parse program header
for (size_t i = 0; i < new_image.m_elf_header->e_phnum; ++i) {
auto& prog_hdr = new_image.m_elf_program_headers[i];
if (!is_address_in_range(address_offset(image_ptr, static_cast<ptrdiff_t>(prog_hdr.p_offset)), prog_hdr.p_filesz, image_ptr, image_size)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: image is corrupted.");
}
auto prog_hdr_align = prog_hdr.p_align;
if (prog_hdr_align) {
// align must be a power of 2
if ((prog_hdr_align & (prog_hdr_align - 1)) != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Phdr[{}]: p_align is not a power of 2.", i));
}
if (prog_hdr.p_offset % prog_hdr_align != prog_hdr.p_vaddr % prog_hdr_align) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Phdr[{}]: p_offset !== p_vaddr (mod prog_hdr_align).", i));
}
}
if (prog_hdr.p_type == PT_LOAD) {
new_image.m_segment_va_lookup_table.emplace(std::make_pair(prog_hdr.p_vaddr, &prog_hdr));
new_image.m_segment_fo_lookup_table.emplace(std::make_pair(prog_hdr.p_offset, &prog_hdr));
}
}
// parse section header
if (new_image.m_elf_header->e_shstrndx != SHN_UNDEF) {
auto sect_hdr_strtab = &new_image.m_elf_section_headers[new_image.m_elf_header->e_shstrndx];
auto sect_view_strtab = address_offset_cast<const char*>(image_ptr, sect_hdr_strtab->sh_offset);
if (sect_hdr_strtab->sh_type != SHT_STRTAB) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: sect_hdr_strtab->sh_type != SHT_STRTAB.");
}
if (!is_address_in_range(sect_view_strtab, sect_hdr_strtab->sh_size, image_ptr, image_size)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: image is corrupted.");
}
for (size_t i = 0; i < new_image.m_elf_header->e_shnum; ++i) {
new_image.m_section_name_lookup_table
.emplace(std::make_pair(std::string_view(address_offset(sect_view_strtab, new_image.m_elf_section_headers[i].sh_name)), &new_image.m_elf_section_headers[i]));
}
}
for (int i = 0; i < new_image.m_elf_header->e_shnum; ++i) {
auto& sect_hdr = new_image.m_elf_section_headers[i];
switch (sect_hdr.sh_type) {
case SHT_SYMTAB:
if (sect_hdr.sh_entsize != sizeof(Elf64_Sym)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_entsize != sizeof(Elf64_Sym).", i));
}
// check sh_link
if (sect_hdr.sh_link == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link == SHN_UNDEF.", i));
}
if (sect_hdr.sh_link >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link is out of range.", i));
}
if (new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_STRTAB) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: bad value of sh_link.", i));
}
// todo: check sh_info
break;
case SHT_RELA:
if (sect_hdr.sh_entsize != sizeof(Elf64_Rela)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_entsize != sizeof(Elf64_Rela).", i));
}
// check sh_link
if (sect_hdr.sh_link == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link == SHN_UNDEF.", i));
}
if (sect_hdr.sh_link >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link is out of range.", i));
}
if (new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_SYMTAB && new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_DYNSYM) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[%u]: bad value of sh_link.", i));
}
// check sh_info
if (sect_hdr.sh_flags & SHF_INFO_LINK) {
if (sect_hdr.sh_info == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info == SHN_UNDEF.", i));
}
if (sect_hdr.sh_info >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info is out of range.", i));
}
} else {
if (sect_hdr.sh_info != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info != 0.", i));
}
}
break;
case SHT_HASH:
if (sect_hdr.sh_link == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link == SHN_UNDEF.", i));
}
if (sect_hdr.sh_link >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link is out of range.", i));
}
if (new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_SYMTAB && new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_DYNSYM) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: bad value of sh_link.", i));
}
if (sect_hdr.sh_info != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info != 0.", i));
}
break;
case SHT_DYNAMIC:
if (sect_hdr.sh_entsize != sizeof(Elf64_Dyn)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_entsize != sizeof(Elf64_Dyn).", i));
}
// check sh_link
if (sect_hdr.sh_link == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link == SHN_UNDEF.", i));
}
if (sect_hdr.sh_link >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link is out of range.", i));
}
if (new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_STRTAB) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: bad value of sh_link.", i));
}
// check sh_info
if (sect_hdr.sh_info != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info != 0.", i));
}
break;
case SHT_REL:
if (sect_hdr.sh_entsize != sizeof(Elf64_Rel)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_entsize != sizeof(Elf64_Rel).", i));
}
// check sh_link
if (sect_hdr.sh_link == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link == SHN_UNDEF.", i));
}
if (sect_hdr.sh_link >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link is out of range.", i));
}
if (new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_SYMTAB && new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_DYNSYM) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[%u]: bad value of sh_link.", i));
}
// check sh_info
if (sect_hdr.sh_flags & SHF_INFO_LINK) {
if (sect_hdr.sh_info == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info == SHN_UNDEF.", i));
}
if (sect_hdr.sh_info >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info is out of range.", i));
}
} else {
if (sect_hdr.sh_info != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_info != 0.", i));
}
}
break;
case SHT_DYNSYM:
if (sect_hdr.sh_entsize != sizeof(Elf64_Sym)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_entsize != sizeof(Elf64_Dyn).", i));
}
// check sh_link
if (sect_hdr.sh_link == SHN_UNDEF) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link == SHN_UNDEF.", i));
}
if (sect_hdr.sh_link >= new_image.m_elf_header->e_shnum) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_link is out of range.", i));
}
if (new_image.m_elf_section_headers[sect_hdr.sh_link].sh_type != SHT_STRTAB) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: bad value of sh_link.", i));
}
// todo: check sh_info
break;
default:
break;
}
if (sect_hdr.sh_type != SHT_NOBITS) {
if (is_address_in_range(address_offset(image_ptr, sect_hdr.sh_offset), sect_hdr.sh_size, image_ptr, image_size) == false) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: image is corrupted.", i));
}
new_image.m_section_fo_lookup_table.emplace(std::make_pair(sect_hdr.sh_offset, new_image.m_elf_section_headers + i));
}
if (sect_hdr.sh_addr) {
if (sect_hdr.sh_addralign && sect_hdr.sh_addr % sect_hdr.sh_addralign != 0) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: Elf64_Shdr[{}]: sh_addr is not aligned to sh_addralign.", i));
}
new_image.m_section_va_lookup_table.emplace(std::make_pair(sect_hdr.sh_addr, &new_image.m_elf_section_headers[i]));
}
}
// parse program header, second parse
for (size_t i = 0; i < new_image.m_elf_header->e_phnum; ++i) {
auto& prog_hdr = new_image.m_elf_program_headers[i];
if (prog_hdr.p_type == PT_DYNAMIC) {
auto seg_dynamic_base = address_offset_cast<Elf64_Dyn*>(image_ptr, prog_hdr.p_offset);
auto seg_dyncmic_size = prog_hdr.p_filesz;
// first parse
for (size_t j = 0; j * sizeof(Elf64_Dyn) < seg_dyncmic_size && seg_dynamic_base[j].d_tag != DT_NULL; ++j) {
auto& dyn_entry = seg_dynamic_base[j];
switch (dyn_entry.d_tag) {
case DT_RELA:
new_image.m_dynamic_rela = &seg_dynamic_base[j];
break;
case DT_RELAENT:
if (seg_dynamic_base[j].d_un.d_val != sizeof(Elf64_Rela)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: the value of DT_RELAENT.dval != sizeof(Elf64_Rela).");
}
break;
case DT_RELASZ:
new_image.m_dynamic_relasz = &seg_dynamic_base[j];
break;
case DT_REL:
new_image.m_dynamic_rel = &seg_dynamic_base[j];
break;
case DT_RELENT:
if (seg_dynamic_base[j].d_un.d_val != sizeof(Elf64_Rel)) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: the value of DT_RELENT.dval != sizeof(Elf64_Rel).");
}
break;
case DT_RELSZ:
new_image.m_dynamic_relsz = &seg_dynamic_base[j];
break;
case DT_PLTGOT:
new_image.m_dynamic_pltgot = &seg_dynamic_base[j];
break;
case DT_JMPREL:
new_image.m_dynamic_jmprel = &seg_dynamic_base[j];
break;
case DT_PLTREL:
if (seg_dynamic_base[j].d_un.d_val == DT_REL || seg_dynamic_base[j].d_un.d_val == DT_RELA) {
new_image.m_dynamic_pltrel = &seg_dynamic_base[j];
} else {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Bad ELF file: the value of DT_PLTREL.dval is neither DT_REL nor DT_RELA.");
}
break;
case DT_PLTRELSZ:
new_image.m_dynamic_pltrelsz = &seg_dynamic_base[j];
break;
case DT_STRTAB:
new_image.m_dynamic_strtab = &seg_dynamic_base[j];
break;
case DT_SYMTAB:
new_image.m_dynamic_symtab = &seg_dynamic_base[j];
break;
default:
break;
}
}
}
}
if (new_image.m_dynamic_rela && new_image.m_dynamic_relasz) {
auto rela_base = new_image.convert_va_to_ptr<Elf64_Rela*>(new_image.m_dynamic_rela->d_un.d_ptr);
auto rela_size = new_image.m_dynamic_relasz->d_un.d_val;
for (size_t i = 0; i * sizeof(Elf64_Rela) < rela_size; ++i) {
auto reloc_va = rela_base[i].r_offset;
auto reloc_type = ELF64_R_TYPE(rela_base[i].r_info);
switch(reloc_type) {
case R_X86_64_64:
case R_X86_64_GLOB_DAT:
case R_X86_64_RELATIVE:
new_image.m_relocation_distribute.emplace(std::make_pair(reloc_va, 8));
break;
default:
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Unsupported ELF file: unhandled relocation type({}).", reloc_type));
}
}
}
if (new_image.m_dynamic_rel && new_image.m_dynamic_relsz) {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Unsupported ELF file: DT_REL is not parsed.");
}
if (new_image.m_dynamic_jmprel && new_image.m_dynamic_pltrel && new_image.m_dynamic_pltrelsz) {
if (new_image.m_dynamic_pltrel->d_un.d_val == DT_RELA) {
auto jmprel_base = new_image.convert_va_to_ptr<Elf64_Rela*>(new_image.m_dynamic_jmprel->d_un.d_ptr);
auto jmprel_size = new_image.m_dynamic_pltrelsz->d_un.d_val;
for (size_t i = 0; i * sizeof(Elf64_Rela) < jmprel_size; ++i) {
auto reloc_va = jmprel_base[i].r_offset;
auto reloc_type = ELF64_R_TYPE(jmprel_base[i].r_info);
if (reloc_type == R_X86_64_JUMP_SLOT) {
new_image.m_relocation_distribute.emplace(std::make_pair(reloc_va, 8));
} else {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: bad relocation type({}) in JMPREL relocation table.", reloc_type));
}
}
} else {
auto jmprel_base = new_image.convert_va_to_ptr<Elf64_Rel*>(new_image.m_dynamic_jmprel->d_un.d_ptr);
auto jmprel_size = new_image.m_dynamic_pltrelsz->d_un.d_val;
for (size_t i = 0; i * sizeof(Elf64_Rela) < jmprel_size; ++i) {
auto reloc_va = jmprel_base[i].r_offset;
auto reloc_type = ELF64_R_TYPE(jmprel_base[i].r_info);
if (reloc_type == R_X86_64_JUMP_SLOT) {
new_image.m_relocation_distribute.emplace(std::make_pair(reloc_va, 8));
} else {
throw parse_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Bad ELF file: bad relocation type({}) in JMPREL relocation table.", reloc_type));
}
}
}
}
return new_image;
}
[[nodiscard]]
size_t elf64_interpreter::elf_size() const noexcept {
return m_elf_size;
}
[[nodiscard]]
Elf64_Ehdr* elf64_interpreter::elf_header() const noexcept {
return m_elf_header;
}
[[nodiscard]]
Elf64_Phdr* elf64_interpreter::elf_program_header(size_t n) const {
if (n < m_elf_header->e_phnum) {
return m_elf_program_headers + n;
} else {
throw exceptions::index_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Out of range.");
}
}
[[nodiscard]]
Elf64_Phdr* elf64_interpreter::elf_program_header_from_fo(fo_t file_offset) const {
auto it = m_segment_fo_lookup_table.upper_bound(file_offset);
if (it != m_segment_fo_lookup_table.begin()) {
--it;
if (it->second->p_offset <= file_offset && file_offset < it->second->p_offset + it->second->p_filesz) {
return it->second;
}
}
throw bad_fo_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("File offset({:#x}) doesn't point to any segment."));
}
[[nodiscard]]
Elf64_Phdr* elf64_interpreter::elf_program_header_from_rva(rva_t rva) const {
return elf_program_header_from_va(convert_rva_to_va(rva));
}
[[nodiscard]]
Elf64_Phdr* elf64_interpreter::elf_program_header_from_va(va_t va) const {
auto it = m_segment_va_lookup_table.upper_bound(va);
if (it != m_segment_va_lookup_table.begin()) {
--it;
if (it->second->p_vaddr <= va && va < it->second->p_vaddr + it->second->p_memsz) {
return it->second;
}
}
throw bad_va_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Invalid virtual address({:#016x}).", va));
}
[[nodiscard]]
size_t elf64_interpreter::elf_program_headers_num() const noexcept {
return m_elf_header->e_shnum;
}
[[nodiscard]]
Elf64_Shdr* elf64_interpreter::elf_section_header(size_t n) const {
if (n < m_elf_header->e_shnum) {
return m_elf_section_headers + n;
} else {
throw exceptions::index_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Out of range.");
}
}
[[nodiscard]]
Elf64_Shdr* elf64_interpreter::elf_section_header(std::string_view section_name) const {
auto it = m_section_name_lookup_table.find(section_name);
if (it != m_section_name_lookup_table.end()) {
return it->second;
} else {
throw exceptions::key_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Section `{}` is not found.", section_name.data()));
}
}
[[nodiscard]]
size_t elf64_interpreter::elf_section_headers_num() const noexcept {
return m_elf_header->e_shnum;
}
[[nodiscard]]
elf64_interpreter::fo_t elf64_interpreter::convert_rva_to_fo(rva_t rva) const {
return convert_va_to_fo(convert_rva_to_va(rva));
}
[[nodiscard]]
elf64_interpreter::fo_t elf64_interpreter::convert_va_to_fo(va_t va) const {
auto it = m_segment_va_lookup_table.upper_bound(va);
if (it != m_segment_va_lookup_table.begin()) {
--it;
if (it->second->p_vaddr <= va && va < it->second->p_vaddr + it->second->p_memsz) {
if (va - it->second->p_vaddr < it->second->p_filesz) {
return it->second->p_offset + (va - it->second->p_vaddr);
} else {
throw bad_va_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Virtual address({:#016x}) doesn't have corresponding file offset.", va));
}
}
}
throw bad_va_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("Invalid virtual address({:#016x})", va));
}
[[nodiscard]]
elf64_interpreter::rva_t elf64_interpreter::convert_fo_to_rva(fo_t file_offset) const {
return convert_va_to_rva(convert_fo_to_va(file_offset));
}
elf64_interpreter::rva_t elf64_interpreter::convert_va_to_rva(va_t va) const {
return va - m_segment_va_lookup_table.begin()->first;
}
[[nodiscard]]
elf64_interpreter::va_t elf64_interpreter::convert_fo_to_va(fo_t file_offset) const {
auto it = m_segment_fo_lookup_table.upper_bound(file_offset);
if (it != m_segment_fo_lookup_table.begin()) {
--it;
if (it->second->p_offset <= file_offset && file_offset < it->second->p_offset + it->second->p_filesz) {
return it->second->p_vaddr + (file_offset - it->second->p_offset);
}
}
throw bad_fo_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), fmt::format("File offset({:#x}) doesn't have corresponding virtual address.", file_offset));
}
[[nodiscard]]
elf64_interpreter::va_t elf64_interpreter::convert_rva_to_va(rva_t rva) const {
return m_segment_va_lookup_table.begin()->first + rva;
}
[[nodiscard]]
std::optional<elf64_interpreter::va_t> elf64_interpreter::elf_dynamic_rela() const {
return m_dynamic_rela ? std::make_optional(m_dynamic_rela->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<size_t> elf64_interpreter::elf_dynamic_relasz() const {
return m_dynamic_relasz ? std::make_optional(m_dynamic_relasz->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<elf64_interpreter::va_t> elf64_interpreter::elf_dynamic_rel() const {
return m_dynamic_rel ? std::make_optional(m_dynamic_rel->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<size_t> elf64_interpreter::elf_dynamic_relsz() const {
return m_dynamic_relsz ? std::make_optional(m_dynamic_relsz->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<elf64_interpreter::va_t> elf64_interpreter::elf_dynamic_pltgot() const {
return m_dynamic_pltgot ? std::make_optional(m_dynamic_pltgot->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<elf64_interpreter::va_t> elf64_interpreter::elf_dynamic_jmprel() const {
return m_dynamic_jmprel ? std::make_optional(m_dynamic_jmprel->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<int> elf64_interpreter::elf_dynamic_pltrel() const {
return m_dynamic_pltrel ? std::make_optional(m_dynamic_pltrel->d_un.d_val) : std::nullopt;
}
[[nodiscard]]
std::optional<size_t> elf64_interpreter::elf_dynamic_pltrelsz() const {
return m_dynamic_pltrelsz ? std::make_optional(m_dynamic_pltrelsz->d_un.d_val) : std::nullopt;
}
[[nodiscard]]
std::optional<elf64_interpreter::va_t> elf64_interpreter::elf_dynamic_symtab() const {
return m_dynamic_symtab ? std::make_optional(m_dynamic_symtab->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
std::optional<elf64_interpreter::va_t> elf64_interpreter::elf_dynamic_strtab() const {
return m_dynamic_strtab ? std::make_optional(m_dynamic_strtab->d_un.d_ptr) : std::nullopt;
}
[[nodiscard]]
const std::map<elf64_interpreter::va_t, size_t>& elf64_interpreter::relocation_distribute() const {
return m_relocation_distribute;
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,237 +0,0 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <elf.h>
#include <map>
#include <string>
#include <optional>
#include "exception.hpp"
#include "memory_utility.hpp"
namespace nkg {
class elf64_interpreter {
public:
using fo_t = uintptr_t;
using rva_t = uintptr_t;
using va_t = uintptr_t;
class parse_error;
class bad_fo_exception;
class bad_va_exception;
private:
size_t m_elf_size;
Elf64_Ehdr* m_elf_header;
Elf64_Phdr* m_elf_program_headers;
Elf64_Shdr* m_elf_section_headers;
std::map<Elf64_Addr, Elf64_Phdr*> m_segment_va_lookup_table;
std::map<Elf64_Off, Elf64_Phdr*> m_segment_fo_lookup_table;
std::map<Elf64_Addr, Elf64_Shdr*> m_section_va_lookup_table;
std::map<Elf64_Off, Elf64_Shdr*> m_section_fo_lookup_table;
std::map<std::string_view, Elf64_Shdr*> m_section_name_lookup_table;
Elf64_Dyn* m_dynamic_rela;
Elf64_Dyn* m_dynamic_relasz;
Elf64_Dyn* m_dynamic_rel;
Elf64_Dyn* m_dynamic_relsz;
Elf64_Dyn* m_dynamic_pltgot;
Elf64_Dyn* m_dynamic_jmprel;
Elf64_Dyn* m_dynamic_pltrel;
Elf64_Dyn* m_dynamic_pltrelsz;
Elf64_Dyn* m_dynamic_symtab;
Elf64_Dyn* m_dynamic_strtab;
std::map<va_t, size_t> m_relocation_distribute;
elf64_interpreter();
public:
[[nodiscard]]
static elf64_interpreter parse(void* image_ptr, size_t image_size);
[[nodiscard]]
size_t elf_size() const noexcept;
template<typename return_t = void*>
[[nodiscard]]
return_t elf_base() const noexcept {
static_assert(std::is_pointer_v<return_t>);
return reinterpret_cast<return_t>(m_elf_header);
}
template<typename return_t = void*>
[[nodiscard]]
return_t elf_offset(fo_t offset) const noexcept {
static_assert(std::is_pointer_v<return_t>);
return address_offset_cast<return_t>(m_elf_header, offset);
}
[[nodiscard]]
Elf64_Ehdr* elf_header() const noexcept;
[[nodiscard]]
Elf64_Phdr* elf_program_header(size_t n) const;
[[nodiscard]]
Elf64_Phdr* elf_program_header_from_fo(fo_t file_offset) const;
[[nodiscard]]
Elf64_Phdr* elf_program_header_from_rva(rva_t rva) const;
[[nodiscard]]
Elf64_Phdr* elf_program_header_from_va(va_t va) const;
[[nodiscard]]
size_t elf_program_headers_num() const noexcept;
[[nodiscard]]
Elf64_Shdr* elf_section_header(size_t n) const;
[[nodiscard]]
Elf64_Shdr* elf_section_header(std::string_view section_name) const;
[[nodiscard]]
size_t elf_section_headers_num() const noexcept;
template<typename return_t = void*>
[[nodiscard]]
return_t elf_section_view(size_t n, fo_t offset = 0) const {
return elf_offset<return_t>(elf_section_header(n)->sh_offset + offset);
}
template<typename return_t = void*>
[[nodiscard]]
return_t elf_section_view(std::string_view section_name, fo_t offset = 0) const {
return elf_offset<return_t>(elf_section_header(section_name)->sh_offset + offset);
}
template<typename ptr_t>
[[nodiscard]]
fo_t convert_ptr_to_fo(ptr_t ptr) const {
return address_delta(ptr, m_elf_header);
}
[[nodiscard]]
fo_t convert_rva_to_fo(rva_t rva) const;
[[nodiscard]]
fo_t convert_va_to_fo(va_t va) const;
[[nodiscard]]
rva_t convert_fo_to_rva(fo_t file_offset) const;
template<typename ptr_t>
[[nodiscard]]
rva_t convert_ptr_to_rva(ptr_t ptr) const {
return convert_fo_to_rva(convert_ptr_to_fo(ptr));
}
rva_t convert_va_to_rva(va_t va) const;
[[nodiscard]]
va_t convert_fo_to_va(fo_t file_offset) const;
[[nodiscard]]
va_t convert_rva_to_va(rva_t rva) const;
template<typename ptr_t>
va_t convert_ptr_to_va(ptr_t ptr) const {
return convert_fo_to_va(convert_ptr_to_fo(ptr));
}
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t convert_fo_to_ptr(fo_t offset) const {
return elf_offset<ptr_t>(offset);
}
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t convert_rva_to_ptr(rva_t rva) const {
return convert_fo_to_ptr<ptr_t>(convert_rva_to_fo(rva));
}
template<typename ptr_t = void*>
[[nodiscard]]
ptr_t convert_va_to_ptr(va_t va) const {
return convert_fo_to_ptr<ptr_t>(convert_va_to_fo(va));
}
template<typename return_t = void*, typename callable_t>
[[nodiscard]]
return_t search_section(size_t n, callable_t&& pred_func) const noexcept {
auto sect_hdr = elf_section_header(n);
auto sect_view = elf_offset<uint8_t*>(sect_hdr->sh_offset);
for (size_t i = 0; i < sect_hdr->sh_size; ++i) {
if (pred_func(sect_view, i, sect_hdr->sh_size)) {
return reinterpret_cast<return_t>(sect_view + i);
}
}
return nullptr;
}
template<typename return_t = void*, typename callable_t>
[[nodiscard]]
return_t search_section(std::string_view section_name, callable_t&& pred_func) const noexcept {
auto sect_hdr = elf_section_header(section_name);
auto sect_view = elf_offset<uint8_t*>(sect_hdr->sh_offset);
for (size_t i = 0; i < sect_hdr->sh_size; ++i) {
if (pred_func(sect_view, i, sect_hdr->sh_size)) {
return reinterpret_cast<return_t>(sect_view + i);
}
}
return nullptr;
}
[[nodiscard]]
std::optional<va_t> elf_dynamic_rela() const;
[[nodiscard]]
std::optional<size_t> elf_dynamic_relasz() const;
[[nodiscard]]
std::optional<va_t> elf_dynamic_rel() const;
[[nodiscard]]
std::optional<size_t> elf_dynamic_relsz() const;
[[nodiscard]]
std::optional<va_t> elf_dynamic_pltgot() const;
[[nodiscard]]
std::optional<va_t> elf_dynamic_jmprel() const;
[[nodiscard]]
std::optional<int> elf_dynamic_pltrel() const;
[[nodiscard]]
std::optional<size_t> elf_dynamic_pltrelsz() const;
[[nodiscard]]
std::optional<va_t> elf_dynamic_symtab() const;
[[nodiscard]]
std::optional<va_t> elf_dynamic_strtab() const;
[[nodiscard]]
const std::map<va_t, size_t>& relocation_distribute() const;
};
class elf64_interpreter::parse_error : public ::nkg::exception {
using ::nkg::exception::exception;
};
class elf64_interpreter::bad_fo_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
class elf64_interpreter::bad_va_exception : public ::nkg::exception {
using ::nkg::exception::exception;
};
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,4 @@
#include "keystone_assembler.hpp"
#include "resource_traits/keystone/keystone_alloc.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\keystone_assembler.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
@ -20,15 +19,14 @@ namespace nkg {
}
}
[[nodiscard]]
std::vector<uint8_t> keystone_assembler::assemble(std::string_view asm_string, uint64_t asm_address) const {
resource_wrapper machine_code{ resource_traits::keystone::keystone_alloc{} };
size_t machine_code_size = 0;
size_t stat_count = 0;
if (ks_asm(m_keystone_engine.get(), asm_string.data(), asm_address, machine_code.unsafe_addressof(), &machine_code_size, &stat_count) < 0) {
auto err = ks_errno(m_keystone_engine.get());
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"ks_asm failed.");
throw backend_error(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), err, u8"ks_option failed.");
}
return std::vector<uint8_t>(machine_code.get(), machine_code.get() + machine_code_size);

View File

@ -12,7 +12,33 @@ namespace nkg {
class keystone_assembler {
public:
class backend_error;
class backend_error : public ::nkg::exception {
public:
using error_code_t = ks_err;
private:
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, error_code_t keystone_err, std::string_view message) noexcept :
::nkg::exception(file, line, message), m_error_code(keystone_err), m_error_string(ks_strerror(keystone_err)) {}
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return true;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
return m_error_code;
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
return m_error_string;
}
};
private:
resource_wrapper<resource_traits::keystone::keystone_handle> m_keystone_engine;
@ -22,36 +48,7 @@ namespace nkg {
void option(ks_opt_type option_type, size_t option_value);
[[nodiscard]]
std::vector<uint8_t> assemble(std::string_view asm_string, uint64_t asm_address = 0) const;
};
class keystone_assembler::backend_error : public ::nkg::exception {
public:
using error_code_t = ks_err;
private:
error_code_t m_error_code;
std::string m_error_string;
public:
backend_error(std::string_view file, int line, error_code_t keystone_err, std::string_view message) noexcept :
::nkg::exception(file, line, message), m_error_code(keystone_err), m_error_string(ks_strerror(keystone_err)) {}
[[nodiscard]]
virtual bool error_code_exists() const noexcept override {
return true;
}
[[nodiscard]]
virtual intptr_t error_code() const noexcept override {
return m_error_code;
}
[[nodiscard]]
virtual const std::string& error_string() const noexcept override {
return m_error_string;
}
};
}

View File

@ -1,295 +0,0 @@
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <filesystem>
#include <optional>
#include <fmt/format.h>
#include "resource_wrapper.hpp"
#include "resource_traits/cxx_object_traits.hpp"
#include "resource_traits/unix_os/file_descriptor.hpp"
#include "resource_traits/unix_os/map_view.hpp"
#include "rsa_cipher.hpp"
#include "elf64_interpreter.hpp"
#include "patch_solution.hpp"
#include "patch_solution_since_16.0.7.0.hpp"
#include "exception.hpp"
#include "exceptions/unix_exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() ".\\navicat-patcher\\main.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
void welcome() {
puts("***************************************************");
puts("* navicat-patcher by @DoubleLabyrinth *");
puts("* version: 16.0.7.0-3 *");
puts("***************************************************");
puts("");
}
void help() {
puts("Usage:");
puts(" navicat-patcher [--dry-run] <Navicat root directory> [RSA-2048 private key file]");
puts("");
puts(" [--dry-run] Run patcher without applying any patches.");
puts(" This parameter is optional.");
puts("");
puts(" <Navicat root directory> Path to a directory where Navicat locates.");
puts(" This parameter is mandatory.");
puts("");
puts(" [RSA-2048 private key file] Path to an RSA-2048 private key file.");
puts(" If not specified, an RSA-2048 private key file");
puts(" named \"RegPrivateKey.pem\" will be generated.");
puts(" This parameter is optional.");
puts("");
puts("Example:");
puts(" ./navicat-patcher ~/navicat16-premium-en-patched");
puts("");
}
bool parse_cmdline(int argc, char* argv[], bool& dry_run, std::filesystem::path& navicat_root, std::filesystem::path& rsa_keyfile) {
if (argc == 2) {
dry_run = false;
navicat_root = argv[1];
rsa_keyfile.clear();
return true;
} else if (argc == 3) {
if (strcmp(argv[1], "--dry-run") == 0) {
dry_run = true;
navicat_root = argv[2];
rsa_keyfile.clear();
return true;
} else {
dry_run = false;
navicat_root = argv[1];
rsa_keyfile = argv[2];
return true;
}
} else if (argc == 4) {
if (strcmp(argv[1], "--dry-run") == 0) {
dry_run = true;
navicat_root = argv[2];
rsa_keyfile = argv[3];
return true;
} else {
return false;
}
} else {
return false;
}
}
void select_patch_solutions(nkg::resource_wrapper<nkg::resource_traits::cxx_object_traits<nkg::patch_solution>>& solution0) {
return;
}
void load_rsa_privkey(nkg::rsa_cipher& cipher, std::filesystem::path& rsa_key_file, nkg::patch_solution* solution0) {
if (!rsa_key_file.empty()) {
printf("[*] Import RSA-2048 private key from\n");
printf(" %s\n", rsa_key_file.native().c_str());
cipher.import_private_key_file(rsa_key_file.native());
if (solution0 && !solution0->check_rsa_privkey(cipher)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "The RSA private key you provide cannot be used.");
}
} else {
printf("[*] Generating new RSA private key, it may take a long time...\n");
do {
cipher.generate_key(2048);
} while (solution0 && !solution0->check_rsa_privkey(cipher)); // re-generate RSA key if one of `check_rsa_privkey` returns false
}
printf("[*] Your RSA private key:\n%s\n", cipher.export_private_key_string().c_str());
}
template<typename... args_t>
bool all_patch_solutions_are_suppressed(args_t&&... args) {
return (!args.is_valid() && ...);
}
void detect_backup(const std::filesystem::path& file_path) {
std::filesystem::path backup_path = file_path.native() + ".bak";
if (std::filesystem::is_regular_file(backup_path)) {
while (true) {
printf("[*] Previous backup %s is detected. Delete? (y/n)", backup_path.native().c_str());
auto select = getchar();
while (select != '\n' && getchar() != '\n') {}
if (select == 'Y' || select == 'y') {
std::filesystem::remove(backup_path);
break;
} else if (select == 'N' || select == 'n') {
throw nkg::exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Backup file still exists. Patch abort!");
} else {
continue;
}
}
}
}
void make_backup(const std::filesystem::path& file_path) {
std::filesystem::path backup_path = file_path.native() + ".bak";
if (std::filesystem::exists(backup_path)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Previous backup is detected.")
.push_hint(fmt::format("Please delete {} and try again.", backup_path.native()));
} else {
std::filesystem::copy_file(file_path, backup_path);
}
}
int main(int argc, char* argv[]) {
welcome();
bool dry_run = false;
std::filesystem::path navicat_root;
std::filesystem::path rsa_key_file;
if (!parse_cmdline(argc, argv, dry_run, navicat_root, rsa_key_file)) {
help();
return -1;
}
try {
if (!std::filesystem::is_directory(navicat_root)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "Navicat root directory path doesn't point to a directory.")
.push_hint("Are you sure the path you specified is correct?")
.push_hint(fmt::format("The path you specified: {}", navicat_root.native()));
}
if (!rsa_key_file.empty() && !std::filesystem::is_regular_file(rsa_key_file)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "RSA private key file path doesn't point to a file.")
.push_hint("Are you sure the path you specified is correct?")
.push_hint(fmt::format("The path you specified: {}", rsa_key_file.native()));
}
nkg::rsa_cipher cipher;
std::filesystem::path libcc_filepath = navicat_root / "usr" / "lib" / "libcc.so";
nkg::resource_wrapper libcc_fd{ nkg::resource_traits::unix_os::file_descriptor{} };
nkg::resource_wrapper libcc_stat{ nkg::resource_traits::cxx_object_traits<struct stat>{} };
nkg::resource_wrapper libcc_map_view{ nkg::resource_traits::unix_os::map_view{}, [&libcc_stat](void* p) { munmap(p, libcc_stat->st_size); } };
std::optional<nkg::elf64_interpreter> libcc_interpreter;
nkg::resource_wrapper solution0{ nkg::resource_traits::cxx_object_traits<nkg::patch_solution>{} };
// open libcc.dll
libcc_fd.set(open(libcc_filepath.native().c_str(), O_RDWR));
if (libcc_fd.is_valid()) {
printf("[+] Try to open libcc.dll ... OK!\n");
} else {
if (errno == ENOENT) {
printf("[-] Try to open libcc.dll ... NOT FOUND!\n");
} else {
throw nkg::exceptions::unix_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), errno, "open failed.");
}
}
if (libcc_fd.is_valid()) {
libcc_stat.set(new struct stat());
if (fstat(libcc_fd.get(), libcc_stat.get()) != 0) {
throw nkg::exceptions::unix_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), errno, "fstat failed.");
}
libcc_map_view.set(mmap(nullptr, libcc_stat->st_size, PROT_READ | PROT_WRITE, MAP_SHARED, libcc_fd.get(), 0));
if (!libcc_map_view.is_valid()) {
throw nkg::exceptions::unix_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), errno, "mmap failed.");
}
libcc_interpreter = nkg::elf64_interpreter::parse(libcc_map_view.get(), libcc_stat->st_size);
solution0.set(new nkg::patch_solution_since<16, 0, 7, 0>(libcc_interpreter.value()));
}
puts("");
// find patch and decide which solution will be applied
if (solution0.is_valid()) {
auto patch_found = solution0->find_patch();
puts("");
if (!patch_found) {
solution0.release();
}
}
select_patch_solutions(solution0);
if (all_patch_solutions_are_suppressed(solution0)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), "All patch solutions are suppressed. Patch abort!")
.push_hint("Are you sure your navicat has not been patched/modified before?");
}
// load key
load_rsa_privkey(cipher, rsa_key_file, solution0.get());
// apply patch solutions
if (dry_run) {
puts("*******************************************************");
puts("* DRY-RUN MODE ENABLE! *");
puts("* NO PATCH WILL BE APPLIED! *");
puts("*******************************************************");
} else {
// save private key if not given
if (rsa_key_file.empty()) {
cipher.export_private_key_file("RegPrivateKey.pem");
}
// detecting backups
if (solution0.is_valid()) {
detect_backup(libcc_filepath);
}
// make backup
if (solution0.is_valid()) {
make_backup(libcc_filepath);
}
// make patch
// no way to go back from here :-)
if (solution0.is_valid()) {
solution0->make_patch(cipher);
}
// print new key file path
if (rsa_key_file.empty()) {
printf("[*] New RSA-2048 private key has been saved to\n");
printf(" %s\n", (std::filesystem::current_path() / "RegPrivateKey.pem").c_str());
}
puts("");
puts("*******************************************************");
puts("* PATCH HAS BEEN DONE SUCCESSFULLY! *");
puts("* HAVE FUN AND ENJOY~ *");
puts("*******************************************************");
}
return 0;
} catch (nkg::exception& e) {
printf("[-] %s:%d ->\n", e.source_file().c_str(), e.source_line());
printf(" %s\n", e.custom_message().c_str());
if (e.error_code_exists()) {
printf(" %s (0x%zx)\n", e.error_string().c_str(), e.error_code());
}
for (auto& hint : e.hints()) {
printf(" HINT: %s\n", hint.c_str());
}
return -1;
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE

View File

@ -1,136 +0,0 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <type_traits>
namespace nkg {
template<typename ptr1_t, typename ptr2_t>
[[nodiscard]]
inline ptrdiff_t address_delta(ptr1_t ptr1, ptr2_t ptr2) noexcept {
static_assert(std::is_pointer_v<ptr1_t> && std::is_pointer_v<ptr2_t>);
return reinterpret_cast<const volatile char*>(ptr1) - reinterpret_cast<const volatile char*>(ptr2);
}
template<typename ptr_t>
[[nodiscard]]
inline ptr_t address_offset(ptr_t ptr, ptrdiff_t off) noexcept {
static_assert(std::is_pointer_v<ptr_t>);
return reinterpret_cast<ptr_t>(
const_cast<char*>(
reinterpret_cast<const volatile char*>(ptr) + off
)
);
}
template<typename return_ptr_t, typename ptr_t>
[[nodiscard]]
inline return_ptr_t address_offset_cast(ptr_t ptr, ptrdiff_t off) noexcept {
static_assert(std::is_pointer_v<return_ptr_t> && std::is_pointer_v<ptr_t>);
return reinterpret_cast<return_ptr_t>(address_offset(ptr, off));
}
template<typename ptr_t, typename begin_ptr_t, typename end_ptr_t>
[[nodiscard]]
inline bool is_address_in_range(ptr_t ptr, begin_ptr_t begin, end_ptr_t end) {
static_assert(std::is_pointer_v<ptr_t> && std::is_pointer_v<begin_ptr_t> && std::is_pointer_v<end_ptr_t>);
auto _ptr = reinterpret_cast<const volatile char*>(ptr);
auto _begin = reinterpret_cast<const volatile char*>(begin);
auto _end = reinterpret_cast<const volatile char*>(end);
return _begin <= _ptr && _ptr < _end;
}
template<typename ptr_t, typename base_ptr_t>
[[nodiscard]]
inline bool is_address_in_range(ptr_t ptr, base_ptr_t base, size_t size) {
static_assert(std::is_pointer_v<ptr_t> && std::is_pointer_v<base_ptr_t>);
return is_address_in_range(ptr, base, address_offset(base, size));
}
template<typename ptr1_t, typename ptr2_t, typename begin_ptr_t, typename end_ptr_t>
[[nodiscard]]
inline bool is_address_in_range(ptr1_t ptr1, ptr2_t ptr2, begin_ptr_t begin, end_ptr_t end) {
static_assert(std::is_pointer_v<ptr1_t> && std::is_pointer_v<ptr2_t> && std::is_pointer_v<begin_ptr_t> && std::is_pointer_v<end_ptr_t>);
auto _ptr1 = reinterpret_cast<const volatile char*>(ptr1);
auto _ptr2 = reinterpret_cast<const volatile char*>(ptr2);
auto _begin = reinterpret_cast<const volatile char*>(begin);
auto _end = reinterpret_cast<const volatile char*>(end);
return _begin <= _ptr1 && _ptr1 <= _ptr2 && _ptr2 <= _end;
}
template<typename ptr_t, typename begin_ptr_t, typename end_ptr_t>
[[nodiscard]]
inline bool is_address_in_range(ptr_t ptr, size_t size, begin_ptr_t begin, end_ptr_t end) {
static_assert(std::is_pointer_v<ptr_t> && std::is_pointer_v<begin_ptr_t> && std::is_pointer_v<end_ptr_t>);
return is_address_in_range(ptr, address_offset(ptr, size), begin, end);
}
template<typename ptr1_t, typename ptr2_t, typename base_ptr_t>
[[nodiscard]]
inline bool is_address_in_range(ptr1_t ptr1, ptr2_t ptr2, base_ptr_t base, size_t size) {
static_assert(std::is_pointer_v<ptr1_t> && std::is_pointer_v<ptr2_t> && std::is_pointer_v<base_ptr_t>);
return is_address_in_range(ptr1, ptr2, base, address_offset(base, size));
}
template<typename ptr_t, typename base_ptr_t>
[[nodiscard]]
inline bool is_address_in_range(ptr_t p, size_t s, base_ptr_t base, size_t size) {
static_assert(std::is_pointer_v<ptr_t>);
static_assert(std::is_pointer_v<base_ptr_t>);
return is_address_in_range(p, address_offset(p, s), base, address_offset(base, size));
}
// template<typename __ReadType, typename __PtrType>
// [[nodiscard]]
// inline __ReadType AddressRead(__PtrType p) noexcept {
// static_assert(std::is_trivial_v<__ReadType> && std::is_standard_layout_v<__ReadType>);
// static_assert(std::is_pointer_v<__PtrType>);
// return *reinterpret_cast<const volatile __ReadType*>(p);
// }
//
// template<typename __ReadType, typename __PtrType>
// [[nodiscard]]
// inline __ReadType AddressRead(__PtrType p, ptrdiff_t offset) noexcept {
// static_assert(std::is_trivial_v<__ReadType> && std::is_standard_layout_v<__ReadType>);
// static_assert(std::is_pointer_v<__PtrType>);
// return *reinterpret_cast<const volatile __ReadType*>(
// reinterpret_cast<const volatile char*>(p) + offset
// );
// }
//
// template<typename __ReadType, typename __PtrType>
// [[nodiscard]]
// inline __ReadType AddressRead(__PtrType p, size_t scale, ptrdiff_t index) noexcept {
// static_assert(std::is_trivial_v<__ReadType> && std::is_standard_layout_v<__ReadType>);
// static_assert(std::is_pointer_v<__PtrType>);
// return *reinterpret_cast<const volatile __ReadType*>(
// reinterpret_cast<const volatile char*>(p) + scale * index
// );
// }
//
// template<typename __WriteType, typename __PtrType>
// inline void AddressWrite(__PtrType p, const __WriteType& value) noexcept {
// static_assert(std::is_trivial_v<__WriteType> && std::is_standard_layout_v<__WriteType>);
// static_assert(std::is_pointer_v<__PtrType>);
// *reinterpret_cast<volatile __WriteType*>(p) = value;
// }
//
// template<typename __WriteType, typename __PtrType>
// inline void AddressWrite(__PtrType p, ptrdiff_t offset, const __WriteType& value) noexcept {
// static_assert(std::is_trivial_v<__WriteType> && std::is_standard_layout_v<__WriteType>);
// static_assert(std::is_pointer_v<__PtrType>);
// *reinterpret_cast<volatile __WriteType*>(
// reinterpret_cast<volatile char*>(p) + offset
// ) = value;
// }
//
// template<typename __WriteType, typename __PtrType>
// inline void AddressWrite(__PtrType p, size_t scale, ptrdiff_t index, const __WriteType& value) noexcept {
// static_assert(std::is_trivial_v<__WriteType> && std::is_standard_layout_v<__WriteType>);
// static_assert(std::is_pointer_v<__PtrType>);
// *reinterpret_cast<volatile __WriteType*>(
// reinterpret_cast<volatile char*>(p) + scale * index
// ) = value;
// }
}

View File

@ -0,0 +1,210 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{1b6920eb-e6ed-465f-9600-b5f816752375}</ProjectGuid>
<RootNamespace>navicatpatcher</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
<Import Project="..\common\common.vcxitems" Label="Shared" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)\bin\$(PlatformTarget)-$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)\obj\$(PlatformTarget)-$(Configuration)\$(ProjectName)\</IntDir>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<VcpkgUseStatic>true</VcpkgUseStatic>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="i386_emulator.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="image_interpreter.cpp" />
<ClCompile Include="keystone_assembler.cpp" />
<ClCompile Include="patch_solution_since_16.0.7.0.amd64.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="amd64_emulator.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.generic.cpp" />
<ClCompile Include="patch_solution_since_16.0.7.0.i386.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClCompile>
<ClCompile Include="wmain.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="i386_emulator.hpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ClInclude>
<ClInclude Include="keystone_assembler.hpp" />
<ClInclude Include="patch_solution.hpp" />
<ClInclude Include="image_interpreter.hpp" />
<ClInclude Include="patch_solution_since.hpp" />
<ClInclude Include="patch_solution_since_16.0.7.0.hpp" />
<ClInclude Include="amd64_emulator.hpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ClInclude>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="wmain.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="image_interpreter.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="amd64_emulator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="keystone_assembler.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="i386_emulator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="patch_solution.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution_since_16.0.7.0.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution_since.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="image_interpreter.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="amd64_emulator.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="keystone_assembler.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="i386_emulator.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>

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>

View File

@ -0,0 +1,591 @@
#define _CRT_SECURE_NO_WARNINGS
#include "amd64_emulator.hpp"
#include "keystone_assembler.hpp"
#include "patch_solution_since_16.0.7.0.hpp"
#include <algorithm>
#include <fmt/format.h>
namespace nkg {
patch_solution_since<16, 0, 7, 0>::patch_solution_since(image_interpreter& libcc_interpreter) :
m_libcc_interpreter(libcc_interpreter),
m_va_CSRegistrationInfoFetcher_WIN_vtable(0),
m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey(0),
m_va_iat_entry_malloc(0) {}
bool patch_solution_since<16, 0, 7, 0>::find_patch() {
auto CSRegistrationInfoFetcher_WIN_type_descriptor_name =
m_libcc_interpreter.search_section<const uint8_t*>(
".data",
[](const uint8_t* p, size_t s) {
if (s < sizeof(".?AVCSRegistrationInfoFetcher_WIN@@")) {
return false;
}
return strcmp(reinterpret_cast<const char*>(p), ".?AVCSRegistrationInfoFetcher_WIN@@") == 0;
}
);
if (CSRegistrationInfoFetcher_WIN_type_descriptor_name == nullptr) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_WIN is not found. (failure label 0)\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_WIN_rtti_type_descriptor = CSRegistrationInfoFetcher_WIN_type_descriptor_name - 0x10;
auto CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_rva = m_libcc_interpreter.convert_ptr_to_rva(CSRegistrationInfoFetcher_WIN_rtti_type_descriptor);
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor =
m_libcc_interpreter.search_section<const uint8_t*>(
".rdata",
[this, CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_rva](const uint8_t* p, size_t s) {
if (reinterpret_cast<uintptr_t>(p) % sizeof(uint32_t) != 0) {
return false;
}
if (s < sizeof(uint32_t)) {
return false;
}
if (*reinterpret_cast<const uint32_t*>(p) != CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_rva) {
return false;
}
if (s < sizeof(uint32_t) * 2) {
return false;
}
auto maybe_CSRegistrationInfoFetcher_WIN_rtti_class_hierarchy_descriptor_rva = reinterpret_cast<const uint32_t*>(p)[1];
try {
return memcmp(m_libcc_interpreter.image_section_header_from_rva(maybe_CSRegistrationInfoFetcher_WIN_rtti_class_hierarchy_descriptor_rva)->Name, ".rdata\x00\x00", 8) == 0;
} catch (nkg::exception&) {
return false;
}
}
);
if (CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor == nullptr) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_WIN is not found. (failure label 1)\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator = CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor - 0xC;
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator);
auto CSRegistrationInfoFetcher_WIN_vtable_before =
m_libcc_interpreter.search_section<const uint8_t*>(
".rdata",
[CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va](const uint8_t* p, size_t s) {
if (reinterpret_cast<uintptr_t>(p) % sizeof(uint64_t) != 0) {
return false;
}
if (s < sizeof(uint64_t)) {
return false;
}
return *reinterpret_cast<const uint64_t*>(p) == CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va;
}
);
if (CSRegistrationInfoFetcher_WIN_vtable_before == nullptr) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Vftable for CSRegistrationInfoFetcher_WIN is not found.\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_WIN_vtable =
reinterpret_cast<const image_interpreter::va_t*>(CSRegistrationInfoFetcher_WIN_vtable_before + sizeof(image_interpreter::va_t));
m_va_CSRegistrationInfoFetcher_WIN_vtable = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_vtable);
m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = CSRegistrationInfoFetcher_WIN_vtable[6];
wprintf(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x%016llx\n", m_va_CSRegistrationInfoFetcher_WIN_vtable);
wprintf(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x%016llx\n", m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey);
amd64_emulator x64_emulator;
x64_emulator.context_set("heap_base", uint64_t{ 0x00007fff00000000 });
x64_emulator.context_set("heap_size", size_t{ 0x1000 * 32 });
x64_emulator.context_set("heap_records", std::map<uint64_t, uint64_t>{});
x64_emulator.context_set("stack_base", uint64_t{ 0x00007fffffff0000 });
x64_emulator.context_set("stack_size", size_t{ 0x1000 * 32 });
x64_emulator.context_set("stack_top", uint64_t{ x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") });
x64_emulator.context_set("dead_area_base", uint64_t{ 0xfffffffffffff000 });
x64_emulator.context_set("dead_area_size", size_t{ 0x1000 });
x64_emulator.context_set("iat_base", uint64_t{ m_libcc_interpreter.convert_rva_to_va(m_libcc_interpreter.image_nt_headers()->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) });
x64_emulator.context_set("iat_size", size_t{ m_libcc_interpreter.image_nt_headers()->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size });
x64_emulator.context_set("external_api_stub_area_base", uint64_t{ 0xffff800000000000 });
x64_emulator.context_set("external_api_stub_area_size", size_t{ (x64_emulator.context_get<size_t>("iat_size") / 8 + 0xfff) / 0x1000 * 0x1000 });
x64_emulator.context_set("external_api_impl", std::map<std::string, uint64_t>{});
x64_emulator.context_set("external_api_impl_area_base", uint64_t{ 0xffff900000000000 });
x64_emulator.context_set("external_api_impl_area_size", size_t{ 0 });
x64_emulator.context_set("gs_base", uint64_t{ 0xffffa00000000000 });
x64_emulator.context_set("gs_size", size_t{ 0x1000 });
x64_emulator.context_set("start_address", static_cast<uint64_t>(m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey));
x64_emulator.context_set("dead_address", x64_emulator.context_get<uint64_t>("dead_area_base"));
// allocate heap
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("heap_base"), x64_emulator.context_get<size_t>("heap_size"), UC_PROT_READ | UC_PROT_WRITE);
// allocate stack
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("stack_top"), x64_emulator.context_get<size_t>("stack_size"), UC_PROT_READ | UC_PROT_WRITE);
// allocate dead area
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("dead_area_base"), x64_emulator.context_get<size_t>("dead_area_size"), UC_PROT_READ | UC_PROT_EXEC);
// allocate and hook read access to IAT
{
auto iat_base = x64_emulator.context_get<uint64_t>("iat_base");
auto iat_size = x64_emulator.context_get<size_t>("iat_size");
auto external_api_stub_area_base = x64_emulator.context_get<uint64_t>("external_api_stub_area_base");
auto iat_page_base = iat_base / 0x1000 * 0x1000;
auto iat_page_count = (iat_base - iat_page_base + iat_size + 0xfff) / 0x1000;
x64_emulator.mem_map(iat_page_base, iat_page_count * 0x1000, UC_PROT_READ);
x64_emulator.hook_add<UC_HOOK_MEM_READ>(
[this, &x64_emulator, iat_base, external_api_stub_area_base](uc_mem_type type, uint64_t address, size_t size, int64_t value) {
auto rva = m_libcc_interpreter.convert_va_to_rva(address);
auto import_lookup_entry = m_libcc_interpreter.import_lookup_entry_from_rva(rva);
if (import_lookup_entry && !IMAGE_SNAP_BY_ORDINAL(import_lookup_entry->u1.Ordinal)) {
auto import_by_name_entry = m_libcc_interpreter.convert_rva_to_ptr<PIMAGE_IMPORT_BY_NAME>(import_lookup_entry->u1.AddressOfData);
if (strcmp(import_by_name_entry->Name, "memcpy") == 0) {
uint64_t impl_address = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["memcpy"];
x64_emulator.mem_write(address, &impl_address, sizeof(impl_address));
} else if (strcmp(import_by_name_entry->Name, "memcmp") == 0) {
uint64_t impl_address = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["memcmp"];
x64_emulator.mem_write(address, &impl_address, sizeof(impl_address));
} else {
uint64_t stub_address = external_api_stub_area_base + (address - iat_base) / sizeof(IMAGE_THUNK_DATA);
x64_emulator.mem_write(address, &stub_address, sizeof(stub_address));
}
} else {
x64_emulator.emu_stop();
}
},
iat_base,
iat_base + iat_size - 1
);
}
// allocate and setup external api stub area
{
auto external_api_stub_area_base = x64_emulator.context_get<uint64_t>("external_api_stub_area_base");
auto external_api_stub_area_size = x64_emulator.context_get<size_t>("external_api_stub_area_size");
x64_emulator.mem_map(external_api_stub_area_base, external_api_stub_area_size, UC_PROT_READ | UC_PROT_EXEC);
x64_emulator.mem_write(external_api_stub_area_base, std::vector<uint8_t>(external_api_stub_area_size, 0xc3)); // c3 -> ret
x64_emulator.hook_add<UC_HOOK_CODE>(
[this, &x64_emulator, external_api_stub_area_base](uint64_t address, size_t size) {
auto iat_base = x64_emulator.context_get<uint64_t>("iat_base");
auto from_va = iat_base + (address - external_api_stub_area_base) * sizeof(IMAGE_THUNK_DATA);
auto from_rva = m_libcc_interpreter.convert_va_to_rva(from_va);
auto import_lookup_entry = m_libcc_interpreter.import_lookup_entry_from_rva(from_rva);
if (import_lookup_entry && !IMAGE_SNAP_BY_ORDINAL(import_lookup_entry->u1.Ordinal)) {
auto import_by_name_entry = m_libcc_interpreter.convert_rva_to_ptr<PIMAGE_IMPORT_BY_NAME>(import_lookup_entry->u1.AddressOfData);
if (strcmp(import_by_name_entry->Name, "malloc") == 0) {
m_va_iat_entry_malloc = from_va;
uint64_t alloc_size;
x64_emulator.reg_read(UC_X86_REG_RCX, &alloc_size);
auto& heap_records = x64_emulator.context_get<std::map<uint64_t, uint64_t>&>("heap_records");
auto predecessor_chunk =
std::adjacent_find(
heap_records.begin(),
heap_records.end(),
[alloc_size](const auto& chunk0, const auto& chunk1) { return chunk1.first - (chunk0.first + chunk0.second) >= alloc_size; }
);
uint64_t alloc_p;
if (predecessor_chunk != heap_records.end()) {
alloc_p = predecessor_chunk->first + predecessor_chunk->second;
} else {
auto heap_base = x64_emulator.context_get<uint64_t>("heap_base");
auto heap_size = x64_emulator.context_get<uint64_t>("heap_size");
auto free_space_base = heap_records.size() > 0 ? heap_records.rbegin()->first + heap_records.rbegin()->second : heap_base;
auto free_space_size = heap_base + heap_size - free_space_base;
if (free_space_size < alloc_size) {
auto heap_expand_base = heap_base + heap_size;
auto heap_expand_size = (alloc_size - free_space_size + 0xfff) / 0x1000 * 0x1000;
x64_emulator.mem_map(heap_expand_base, heap_expand_size, UC_PROT_READ | UC_PROT_WRITE);
}
alloc_p = free_space_base;
}
heap_records[alloc_p] = alloc_size;
x64_emulator.reg_write(UC_X86_REG_RAX, &alloc_p);
} else if (strcmp(import_by_name_entry->Name, "free") == 0) {
uint64_t alloc_p;
x64_emulator.reg_read(UC_X86_REG_RCX, &alloc_p);
auto& heap_records = x64_emulator.context_get<std::map<uint64_t, uint64_t>&>("heap_records");
auto chunk = heap_records.find(alloc_p);
if (chunk != heap_records.end()) {
heap_records.erase(chunk);
} else {
x64_emulator.emu_stop();
}
} else {
x64_emulator.emu_stop();
}
} else {
x64_emulator.emu_stop();
}
},
external_api_stub_area_base,
external_api_stub_area_base + external_api_stub_area_size - 1
);
}
// allocate and setup external api impl area
{
keystone_assembler x64_assembler{ KS_ARCH_X86, KS_MODE_64 };
std::map<std::string, std::vector<uint8_t>> machine_code_list =
{
std::make_pair(
"memcpy",
x64_assembler.assemble(
"push rdi;"
"push rsi;"
"mov rdi, rcx;"
"mov rsi, rdx;"
"mov rcx, r8;"
"rep movs byte ptr [rdi], byte ptr [rsi];"
"pop rsi;"
"pop rdi;"
"ret;"
)
),
std::make_pair(
"memcmp",
x64_assembler.assemble(
" push rdi;"
" push rsi;"
" mov rsi, rcx;"
" mov rdi, rdx;"
" mov rcx, r8;"
" cmp rcx, rcx;"
" repe cmps byte ptr [rsi], byte ptr [rdi];"
" jz cmp_eq;"
"cmp_not_eq:"
" movsx eax, byte ptr [rsi - 1];"
" movsx ecx, byte ptr [rdi - 1];"
" sub eax, ecx;"
" jmp final;"
"cmp_eq:"
" xor eax, eax;"
"final:"
" pop rsi;"
" pop rdi;"
" ret;"
)
),
std::make_pair(
"memmove",
x64_assembler.assemble(
" push rdi;"
" push rsi;"
" cmp rdx, rcx;"
" jb reverse_copy;"
"copy:"
" mov rdi, rcx;"
" mov rsi, rdx;"
" mov rcx, r8;"
" rep movsb byte ptr[rdi], byte ptr[rsi];"
" jmp final;"
"reverse_copy:"
" std;"
" lea rdi, qword ptr[rcx + r8 - 1];"
" lea rsi, qword ptr[rdx + r8 - 1];"
" mov rcx, r8;"
" rep movsb byte ptr[rdi], byte ptr[rsi];"
" cld;"
"final:"
" pop rsi;"
" pop rdi;"
" ret;"
)
)
};
auto& external_api_impl = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl");
auto& external_api_impl_area_base = x64_emulator.context_get<uint64_t&>("external_api_impl_area_base");
auto& external_api_impl_area_size = x64_emulator.context_get<size_t&>("external_api_impl_area_size");
auto p = external_api_impl_area_base;
for (const auto& name_code_pair : machine_code_list) {
external_api_impl[name_code_pair.first] = p;
p = (p + name_code_pair.second.size() + 0xf) / 0x10 * 0x10;
}
external_api_impl_area_size = (p + 0xfff) / 0x1000 * 0x1000 - external_api_impl_area_base;
x64_emulator.mem_map(external_api_impl_area_base, external_api_impl_area_size, UC_PROT_READ | UC_PROT_EXEC);
for (const auto& name_code_pair : machine_code_list) {
x64_emulator.mem_write(external_api_impl[name_code_pair.first], name_code_pair.second);
}
}
// allocate and hook access to gs area
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("gs_base"), x64_emulator.context_get<size_t>("gs_size"), UC_PROT_READ | UC_PROT_WRITE);
x64_emulator.msr_write(0xC0000101, x64_emulator.context_get<uint64_t>("gs_base")); // set gs base address
x64_emulator.hook_add<UC_HOOK_MEM_READ>(
[this, &x64_emulator](uc_mem_type access, uint64_t address, size_t size, int64_t value) {
auto gs_base = x64_emulator.context_get<uint64_t>("gs_base");
switch (address - gs_base) {
case 0x10: // qword ptr gs:[0x10] -> Stack Limit / Ceiling of stack (low address)
{
uint64_t val = x64_emulator.context_get<uint64_t>("stack_top");
x64_emulator.mem_write(address, &val, size);
}
break;
default:
x64_emulator.emu_stop();
break;
}
},
x64_emulator.context_get<uint64_t>("gs_base"),
x64_emulator.context_get<uint64_t>("gs_base") + x64_emulator.context_get<size_t>("gs_size") - 1
);
// x64_emulator.hook_add<UC_HOOK_CODE>([](uint64_t address, size_t size) { wprintf_s(L"code_trace, address = 0x%016zx\n", address); });
x64_emulator.hook_add<UC_HOOK_MEM_UNMAPPED>(
[this, &x64_emulator](uc_mem_type access, uint64_t address, size_t size, int64_t value) -> bool {
try {
auto fault_section = m_libcc_interpreter.image_section_header_from_va(address);
auto page_base = address / 0x1000 * 0x1000;
auto page_size = 0x1000;
uint32_t page_perms = UC_PROT_NONE;
if (fault_section->Characteristics & IMAGE_SCN_MEM_READ) {
page_perms |= UC_PROT_READ;
}
if (fault_section->Characteristics & IMAGE_SCN_MEM_WRITE) {
page_perms |= UC_PROT_WRITE;
}
if (fault_section->Characteristics & IMAGE_SCN_MEM_EXECUTE) {
page_perms |= UC_PROT_EXEC;
}
x64_emulator.mem_map(page_base, page_size, page_perms);
x64_emulator.mem_write(page_base, m_libcc_interpreter.convert_va_to_ptr<const void*>(page_base), page_size);
return true;
} catch (::nkg::exception&) {
return false;
}
}
);
// set rbp, rsp
uint64_t init_rbp = x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") / 4;
uint64_t init_rsp = x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") / 2;
x64_emulator.reg_write(UC_X86_REG_RBP, &init_rbp);
x64_emulator.reg_write(UC_X86_REG_RSP, &init_rsp);
// set return address
auto retaddr = x64_emulator.context_get<uint64_t>("dead_address");
x64_emulator.mem_write(init_rsp, &retaddr, sizeof(retaddr));
// set argument registers
uint64_t init_rcx = 0; // `this` pointer of CSRegistrationInfoFetcher_WIN, but we don't need it for now.
uint64_t init_rdx = init_rsp + 0x40; // a pointer to stack memory which stores return value
x64_emulator.reg_write(UC_X86_REG_RCX, &init_rcx);
x64_emulator.reg_write(UC_X86_REG_RDX, &init_rdx);
//
// start emulate
//
try {
x64_emulator.emu_start(x64_emulator.context_get<uint64_t>("start_address"), x64_emulator.context_get<uint64_t>("dead_address"));
} catch (nkg::exception&) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Code emulation failed.\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
wprintf_s(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x%016llx\n", m_va_iat_entry_malloc);
//
// get result
//
// on AMD64 platform, `std::string` has follow memory layout:
// ------------------------------
// | offset | size |
// ------------------------------
// | +0 | 0x10 | `char[16]: a small string buffer` OR `char*: a large string buffer pointer`
// ------------------------------
// | +0x10 | 0x8 | size_t: string length
// ------------------------------
// | +0x18 | 0x8 | size_t: capacity
// ------------------------------
//
uint64_t encoded_key_length;
x64_emulator.mem_read(init_rdx + 0x10, &encoded_key_length, sizeof(encoded_key_length));
if (encoded_key_length != official_encoded_key.length()) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: unexpected encoded key length(%llu).\n", encoded_key_length);
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
uint64_t encoded_key_ptr;
x64_emulator.mem_read(init_rdx, &encoded_key_ptr, sizeof(encoded_key_ptr));
auto encoded_key = x64_emulator.mem_read(encoded_key_ptr, encoded_key_length);
if (memcmp(encoded_key.data(), official_encoded_key.data(), encoded_key.size()) == 0) {
wprintf_s(L"[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.\n");
return true;
} else {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: official encoded key is not found.\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
}
bool patch_solution_since<16, 0, 7, 0>::check_rsa_privkey(const rsa_cipher& cipher) {
return true; // no requirements
}
void patch_solution_since<16, 0, 7, 0>::make_patch(const rsa_cipher& cipher) {
auto encoded_key = _build_encoded_key(cipher);
auto CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey =
m_libcc_interpreter.convert_va_to_ptr<uint8_t*>(m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey);
std::vector<std::string> patch_code_chunks;
patch_code_chunks.emplace_back("push rdi;");
patch_code_chunks.emplace_back("push rsi;");
patch_code_chunks.emplace_back("push rbx;");
patch_code_chunks.emplace_back("push rbp;");
patch_code_chunks.emplace_back("mov rbp, rsp;");
patch_code_chunks.emplace_back("mov rbx, rdx;");
patch_code_chunks.emplace_back("sub rsp, 0x20;");
patch_code_chunks.emplace_back(fmt::format("mov rcx, {:#x};", encoded_key.length() + 1));
patch_code_chunks.emplace_back(fmt::format("call qword ptr [{:#016x}];", m_va_iat_entry_malloc));
patch_code_chunks.emplace_back("add rsp, 0x20;");
{
std::vector<uint64_t> push_values((encoded_key.length() + 1 + 7) / 8, 0);
memcpy(push_values.data(), encoded_key.data(), encoded_key.length());
std::for_each(
push_values.crbegin(),
push_values.crend(),
[&patch_code_chunks](uint64_t x) {
patch_code_chunks.emplace_back(fmt::format("mov rdx, {:#016x};", x));
patch_code_chunks.emplace_back("push rdx;");
}
);
}
patch_code_chunks.emplace_back("mov rdi, rax;");
patch_code_chunks.emplace_back("mov rsi, rsp;");
patch_code_chunks.emplace_back(fmt::format("mov rcx, {:#x};", encoded_key.length() + 1));
patch_code_chunks.emplace_back("rep movs byte ptr [rdi], byte ptr [rsi];");
patch_code_chunks.emplace_back("mov qword ptr [rbx], rax;");
patch_code_chunks.emplace_back(fmt::format("mov qword ptr [rbx + 0x10], {:#x};", encoded_key.length()));
patch_code_chunks.emplace_back(fmt::format("mov qword ptr [rbx + 0x18], {:#x};", encoded_key.length() + 1));
patch_code_chunks.emplace_back("mov rax, rbx;");
patch_code_chunks.emplace_back("leave;");
patch_code_chunks.emplace_back("pop rbx;");
patch_code_chunks.emplace_back("pop rsi;");
patch_code_chunks.emplace_back("pop rdi;");
patch_code_chunks.emplace_back("ret;");
//auto patch_code = keystone_assembler{ KS_ARCH_X86, KS_MODE_64 }
// .assemble(
// fmt::format(
// " push rdi;"
// " push rsi;"
// " push rbx;"
// " mov rbx, rdx;"
// "allocate_string_buf:"
// " mov rcx, {encoded_key_length:#x} + 1;"
// " sub rsp, 0x20;"
// " call qword ptr [{m_va_iat_entry_malloc:#x}];"
// " add rsp, 0x20;"
// "write_our_own_key_to_string_buf:"
// " mov rdi, rax;"
// " lea rsi, qword ptr [end_of_code + rip];"
// " mov rcx, 0x188;"
// " rep movs byte ptr [rdi], byte ptr [rsi];"
// " mov byte ptr [rdi], 0;"
// "craft_std_string:"
// " mov qword ptr [rbx], rax;"
// " mov qword ptr [rbx + 0x10], {encoded_key_length:#x};"
// " mov qword ptr [rbx + 0x18], {encoded_key_length:#x} + 1;"
// "final:"
// " mov rax, rbx;"
// " pop rbx;"
// " pop rsi;"
// " pop rdi;"
// " ret;"
// "end_of_code:",
// fmt::arg("encoded_key_length", encoded_key.length()),
// fmt::arg("m_va_iat_entry_malloc", m_va_iat_entry_malloc)
// ),
// m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey
// );
std::vector<uint8_t> assembled_patch_code;
{
keystone_assembler x86_assembler{ KS_ARCH_X86, KS_MODE_64 };
auto current_va = m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey;
auto next_reloc = m_libcc_interpreter.relocation_distribute().lower_bound(m_libcc_interpreter.convert_va_to_rva(current_va));
for (const auto& patch_code_chunk : patch_code_chunks) {
auto assembled_patch_code_chunk = x86_assembler.assemble(patch_code_chunk, current_va);
while (true) {
auto next_reloc_va = m_libcc_interpreter.convert_rva_to_va(next_reloc->first);
auto next_reloc_size = next_reloc->second;
if (current_va + assembled_patch_code_chunk.size() + 2 <= next_reloc_va) { // 2 -> size of machine code "jmp rel8"
assembled_patch_code.insert(assembled_patch_code.end(), assembled_patch_code_chunk.begin(), assembled_patch_code_chunk.end());
current_va += assembled_patch_code_chunk.size();
break;
} else if (current_va + 2 <= next_reloc_va) {
auto next_va = next_reloc_va + next_reloc_size;
auto assembled_jmp = x86_assembler.assemble(fmt::format("jmp {:#016x};", next_va), current_va);
auto assembled_padding = std::vector<uint8_t>(next_va - (current_va + assembled_jmp.size()), 0xcc); // 0xcc -> int3
assembled_patch_code.insert(assembled_patch_code.end(), assembled_jmp.begin(), assembled_jmp.end());
assembled_patch_code.insert(assembled_patch_code.end(), assembled_padding.begin(), assembled_padding.end());
current_va = next_va;
++next_reloc;
} else {
__assume(false); // impossible to reach here
}
}
}
}
memcpy(CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey, assembled_patch_code.data(), assembled_patch_code.size());
wprintf_s(L"[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.\n");
}
}

View File

@ -1,816 +0,0 @@
#include "patch_solution_since_16.0.7.0.hpp"
#include <cstddef>
#include <regex>
#include "keystone_assembler.hpp"
#include <fmt/format.h>
namespace nkg {
uint64_t patch_solution_since<16, 0, 7, 0>::_emulator_append_external_api_impl(amd64_emulator& x64_emulator, std::string_view api_name, const std::vector<uint8_t>& api_impl) {
auto& external_api_impl = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl");
auto& external_api_impl_area_base = x64_emulator.context_get<uint64_t&>("external_api_impl_area_base");
auto& external_api_impl_area_size = x64_emulator.context_get<size_t&>("external_api_impl_area_size");
auto& external_api_impl_append_address = x64_emulator.context_get<uint64_t&>("external_api_impl_append_address");
auto p = external_api_impl_append_address;
if (p + api_impl.size() > external_api_impl_area_base + external_api_impl_area_size) {
auto expand_size = ((p + api_impl.size()) - (external_api_impl_area_base + external_api_impl_area_size) + 0xfff) / 0x1000 * 0x1000;
x64_emulator.mem_map(external_api_impl_area_base + external_api_impl_area_size, expand_size, UC_PROT_READ | UC_PROT_EXEC);
external_api_impl_area_size += expand_size;
}
x64_emulator.mem_write(p, api_impl);
external_api_impl[std::string(api_name)] = p;
external_api_impl_append_address = (p + api_impl.size() + 0xf) / 0x10 * 0x10;
return p;
}
uint64_t patch_solution_since<16, 0, 7, 0>::_emulator_malloc(amd64_emulator& x64_emulator, size_t alloc_size) {
auto& heap_records = x64_emulator.context_get<std::map<uint64_t, uint64_t>&>("heap_records");
auto predecessor_chunk =
std::adjacent_find(heap_records.begin(), heap_records.end(), [alloc_size](auto& chunk0, auto& chunk1) { return chunk1.first - (chunk0.first + chunk0.second) >= alloc_size; });
uint64_t alloc_p;
if (predecessor_chunk != heap_records.end()) {
alloc_p = predecessor_chunk->first + predecessor_chunk->second;
} else {
auto heap_base = x64_emulator.context_get<uint64_t>("heap_base");
auto heap_size = x64_emulator.context_get<uint64_t>("heap_size");
auto free_space_base = heap_records.empty() ? heap_base : heap_records.rbegin()->first + heap_records.rbegin()->second;
auto free_space_size = heap_base + heap_size - free_space_base;
if (free_space_size < alloc_size) {
auto heap_expand_base = heap_base + heap_size;
auto heap_expand_size = (alloc_size - free_space_size + 0xfff) / 0x1000 * 0x1000;
x64_emulator.mem_map(heap_expand_base, heap_expand_size, UC_PROT_READ | UC_PROT_WRITE);
}
alloc_p = free_space_base;
}
heap_records[alloc_p] = alloc_size;
return alloc_p;
}
void patch_solution_since<16, 0, 7, 0>::_emulator_free(amd64_emulator& x64_emulator, uint64_t alloc_p) {
auto& heap_records = x64_emulator.context_get<std::map<uint64_t, uint64_t>&>("heap_records");
auto chunk = heap_records.find(alloc_p);
if (chunk != heap_records.end()) {
heap_records.erase(chunk);
} else {
printf("[-] patch_solution_since<16, 0, 7, 0>: emulator tries to free 0x%016lx which is not allocated by malloc.\n", alloc_p);
x64_emulator.emu_stop();
}
}
bool patch_solution_since<16, 0, 7, 0>::_emulator_page_fault_handler(amd64_emulator& x64_emulator, uc_mem_type access, uint64_t address, size_t size, int64_t value) {
try {
auto fault_segment = m_libcc_interpreter.elf_program_header_from_va(address);
auto page_base = address / 0x1000 * 0x1000;
auto page_size = 0x1000;
uint32_t page_perms = UC_PROT_NONE;
if (fault_segment->p_flags & PF_R) {
page_perms |= UC_PROT_READ;
}
if (fault_segment->p_flags & PF_W) {
page_perms |= UC_PROT_WRITE;
}
if (fault_segment->p_flags & PF_X) {
page_perms |= UC_PROT_EXEC;
}
x64_emulator.mem_map(page_base, page_size, page_perms);
x64_emulator.mem_write(page_base, m_libcc_interpreter.convert_va_to_ptr<const void*>(page_base), page_size);
auto dynamic_pltgot = m_libcc_interpreter.elf_dynamic_pltgot();
if (dynamic_pltgot.has_value() && page_base <= dynamic_pltgot.value() + 0x8 && dynamic_pltgot.value() + 0x10 <= page_base + page_size) {
uint64_t dead_address = x64_emulator.context_get<uint64_t>("dead_address");
x64_emulator.mem_write(dynamic_pltgot.value() + 0x8, &dead_address, sizeof(dead_address));
}
if (dynamic_pltgot.has_value() && page_base <= dynamic_pltgot.value() + 0x10 && dynamic_pltgot.value() + 0x18 <= page_base + page_size) {
uint64_t dl_runtime_resolve = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["dl_runtime_resolve"];
x64_emulator.mem_write(dynamic_pltgot.value() + 0x10, &dl_runtime_resolve, sizeof(dl_runtime_resolve));
}
return true;
} catch (::nkg::exception&) {
return false;
}
}
void patch_solution_since<16, 0, 7, 0>::_emulator_dl_runtime_resolve_handler(amd64_emulator& x64_emulator, uint64_t address, size_t size) {
uint64_t rsp;
x64_emulator.reg_read(UC_X86_REG_RSP, &rsp);
uint64_t reloc_idx;
x64_emulator.mem_read(rsp + 0x8, &reloc_idx, sizeof(reloc_idx));
uint64_t reloc_va;
Elf64_Sym* reloc_sym;
uint32_t reloc_type;
char* reloc_sym_name;
if (m_libcc_interpreter.elf_dynamic_pltrel().value() == DT_REL) {
auto jmp_reloc_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Rel*>(m_libcc_interpreter.elf_dynamic_jmprel().value());
auto symbol_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Sym*>(m_libcc_interpreter.elf_dynamic_symtab().value());
auto string_table = m_libcc_interpreter.convert_va_to_ptr<char*>(m_libcc_interpreter.elf_dynamic_strtab().value());
reloc_va = jmp_reloc_table[reloc_idx].r_offset;
reloc_sym = &symbol_table[ELF64_R_SYM(jmp_reloc_table[reloc_idx].r_info)];
reloc_type = ELF64_R_TYPE(jmp_reloc_table[reloc_idx].r_info);
reloc_sym_name = &string_table[reloc_sym->st_name];
} else { // m_libcc_interpreter.elf_dynamic_pltrel().value() == DT_RELA
auto jmp_reloc_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Rela*>(m_libcc_interpreter.elf_dynamic_jmprel().value());
auto symbol_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Sym*>(m_libcc_interpreter.elf_dynamic_symtab().value());
auto string_table = m_libcc_interpreter.convert_va_to_ptr<char*>(m_libcc_interpreter.elf_dynamic_strtab().value());
reloc_va = jmp_reloc_table[reloc_idx].r_offset;
reloc_sym = &symbol_table[ELF64_R_SYM(jmp_reloc_table[reloc_idx].r_info)];
reloc_type = ELF64_R_TYPE(jmp_reloc_table[reloc_idx].r_info);
reloc_sym_name = &string_table[reloc_sym->st_name];
}
if (strcmp(reloc_sym_name, "strlen") == 0) {
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["strlen"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm") == 0) {
// std::string::_M_append(char const*, unsigned long)
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else if (strcmp(reloc_sym_name, "_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7compareEPKc") == 0) {
// std::string::compare(char const*) const
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7compareEPKc"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9push_backEc") == 0) {
// std::string::push_back(char)
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9push_backEc"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendEPKc") == 0) {
// std::string::append(char const*)
m_va_pltgot_std_string_append = reloc_va;
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendEPKc"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendEPKcm") == 0) {
// std::string::append(char const*, unsigned long)
// redirect to `std::string::_M_append(char const*, unsigned long)`
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE10_M_disposeEv") == 0) {
// std::string::_M_dispose()
auto external_api_impl_va =
x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl")["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE10_M_disposeEv"];
x64_emulator.mem_write(reloc_va, &external_api_impl_va, sizeof(external_api_impl_va));
// external api address is resolved, set `qword ptr [rsp] = external_api_impl_va` in order to jump there
x64_emulator.mem_write(rsp, &external_api_impl_va, sizeof(external_api_impl_va));
} else {
printf("[-] patch_solution_since<16, 0, 7, 0>: PLT GOT entry `%s` is not resolved.\n", reloc_sym_name);
x64_emulator.emu_stop();
}
}
void patch_solution_since<16, 0, 7, 0>::_emulator_malloc_handler(amd64_emulator& x64_emulator, uint64_t address, size_t size) {
uint64_t rdi;
x64_emulator.reg_read(UC_X86_REG_RDI, &rdi);
uint64_t rax = _emulator_malloc(x64_emulator, rdi);
x64_emulator.reg_write(UC_X86_REG_RAX, &rax);
}
void patch_solution_since<16, 0, 7, 0>::_emulator_free_handler(amd64_emulator& x64_emulator, uint64_t address, size_t size) {
uint64_t rdi;
x64_emulator.reg_read(UC_X86_REG_RDI, &rdi);
_emulator_free(x64_emulator, rdi);
}
std::string patch_solution_since<16, 0, 7, 0>::_build_encoded_key(const rsa_cipher& cipher) {
auto encoded_key = cipher.export_public_key_string_pem();
encoded_key = std::regex_replace(encoded_key, std::regex("-----BEGIN PUBLIC KEY-----"), "");
encoded_key = std::regex_replace(encoded_key, std::regex("-----END PUBLIC KEY-----"), "");
encoded_key = std::regex_replace(encoded_key, std::regex("\n"), "");
return encoded_key;
}
std::list<std::pair<elf64_interpreter::va_t, size_t>> patch_solution_since<16, 0, 7, 0>::_calculate_reliable_areas() const {
std::list<std::pair<elf64_interpreter::va_t, size_t>> reliable_areas;
for (const auto& [base, size] : m_tracing) {
auto tracing_block_begin_va = base;
auto tracing_block_end_va = base + size;
auto va = tracing_block_begin_va;
auto next_reloc = m_libcc_interpreter.relocation_distribute().lower_bound(va);
while (va < tracing_block_end_va) {
if (next_reloc == m_libcc_interpreter.relocation_distribute().end() || tracing_block_end_va <= next_reloc->first) {
reliable_areas.emplace_back(std::make_pair(va, static_cast<size_t>(tracing_block_end_va - va)));
break;
} else {
reliable_areas.emplace_back(std::make_pair(va, static_cast<size_t>(next_reloc->first - va)));
va = next_reloc->first + next_reloc->second;
++next_reloc;
}
}
}
return reliable_areas;
}
patch_solution_since<16, 0, 7, 0>::patch_solution_since(elf64_interpreter& libcc_interpreter) :
m_libcc_interpreter(libcc_interpreter),
m_va_CSRegistrationInfoFetcher_LINUX_vtable(0),
m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey(0),
m_va_pltgot_std_string_append(0) {}
bool patch_solution_since<16, 0, 7, 0>::find_patch() {
if (m_libcc_interpreter.elf_header()->e_machine != EM_X86_64) {
printf("[-] patch_solution_since<16, 0, 7, 0>: Not x86-64 elf binary.\n");
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_LINUX_typeinfo_name =
m_libcc_interpreter.search_section<uint8_t*>(
".rodata",
[](const uint8_t* base, size_t off, size_t size) {
return (size - off) >= sizeof("31CSRegistrationInfoFetcher_LINUX") && strcmp(address_offset_cast<const char*>(base, off), "31CSRegistrationInfoFetcher_LINUX") == 0;
}
);
if (CSRegistrationInfoFetcher_LINUX_typeinfo_name == nullptr) {
printf("[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_LINUX is not found. (failure label 0)\n");
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_LINUX_typeinfo_name_va =
m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_LINUX_typeinfo_name);
auto CSRegistrationInfoFetcher_LINUX_typeinfo =
m_libcc_interpreter.search_section<uint8_t*>(
".data.rel.ro",
[CSRegistrationInfoFetcher_LINUX_typeinfo_name_va](const uint8_t* base, size_t off, size_t size) {
return off % 8 == 0 && (size - (off + 8)) >= 8 && *address_offset_cast<const uint64_t*>(base, off + 8) == CSRegistrationInfoFetcher_LINUX_typeinfo_name_va;
}
);
if (CSRegistrationInfoFetcher_LINUX_typeinfo == nullptr) {
printf("[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_LINUX is not found. (failure label 1)\n");
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_LINUX_typeinfo_va =
m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_LINUX_typeinfo);
auto CSRegistrationInfoFetcher_LINUX_vftable_before =
m_libcc_interpreter.search_section<uint64_t*>(
".data.rel.ro",
[CSRegistrationInfoFetcher_LINUX_typeinfo_va](const uint8_t* base, size_t off, size_t size) {
return off % 8 == 0 && (size - off) >= 8 && *address_offset_cast<const uint64_t*>(base, off) == CSRegistrationInfoFetcher_LINUX_typeinfo_va;
}
);
if (CSRegistrationInfoFetcher_LINUX_vftable_before == nullptr) {
printf("[-] patch_solution_since<16, 0, 7, 0>: Vftable for CSRegistrationInfoFetcher_LINUX is not found.\n");
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
}
auto CSRegistrationInfoFetcher_LINUX_vftable = CSRegistrationInfoFetcher_LINUX_vftable_before + 1;
m_va_CSRegistrationInfoFetcher_LINUX_vtable = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_LINUX_vftable);
m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey = CSRegistrationInfoFetcher_LINUX_vftable[7];
printf("[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_LINUX_vtable = 0x%016lx\n", m_va_CSRegistrationInfoFetcher_LINUX_vtable);
printf("[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey = 0x%016lx\n", m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey);
amd64_emulator x64_emulator;
x64_emulator.context_set("heap_base", uint64_t{ 0x00007fff00000000 });
x64_emulator.context_set("heap_size", size_t{ 0x1000 * 32 });
x64_emulator.context_set("heap_records", std::map<uint64_t, uint64_t>{});
x64_emulator.context_set("stack_base", uint64_t{ 0x00007fffffff0000 });
x64_emulator.context_set("stack_size", size_t{ 0x1000 * 32 });
x64_emulator.context_set("stack_top", uint64_t{ x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") });
x64_emulator.context_set("dead_area_base", uint64_t{ 0xfffffffffffff000 });
x64_emulator.context_set("dead_area_size", size_t{ 0x1000 });
x64_emulator.context_set("external_api_impl", std::map<std::string, uint64_t>{});
x64_emulator.context_set("external_api_impl_area_base", uint64_t{ 0xffff900000000000 });
x64_emulator.context_set("external_api_impl_area_size", size_t{ 0 });
x64_emulator.context_set("external_api_impl_append_address", x64_emulator.context_get<uint64_t>("external_api_impl_area_base"));
x64_emulator.context_set("start_address", static_cast<uint64_t>(m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey));
x64_emulator.context_set("dead_address", x64_emulator.context_get<uint64_t>("dead_area_base"));
// allocate heap
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("heap_base"), x64_emulator.context_get<size_t>("heap_size"), UC_PROT_READ | UC_PROT_WRITE);
// allocate stack
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("stack_top"), x64_emulator.context_get<size_t>("stack_size"), UC_PROT_READ | UC_PROT_WRITE);
// allocate dead area
x64_emulator.mem_map(x64_emulator.context_get<uint64_t>("dead_area_base"), x64_emulator.context_get<size_t>("dead_area_size"), UC_PROT_READ | UC_PROT_EXEC);
// allocate and setup external api impl area
{
keystone_assembler x64_assembler{ KS_ARCH_X86, KS_MODE_64 };
auto& external_api_impl = x64_emulator.context_get<std::map<std::string, uint64_t>&>("external_api_impl");
auto& external_api_impl_append_address = x64_emulator.context_get<uint64_t&>("external_api_impl_append_address");
_emulator_append_external_api_impl
(
x64_emulator, "dl_runtime_resolve",
x64_assembler.assemble
(
" nop;"
" mov rax, qword ptr [rsp];"
" add rsp, 0x10;"
" cmp rax, 0;"
" je just_ret;"
" jmp rax;"
"just_ret:"
" ret;"
)
);
_emulator_append_external_api_impl(x64_emulator, "malloc", x64_assembler.assemble("ret;"));
_emulator_append_external_api_impl(x64_emulator, "free", x64_assembler.assemble("ret;"));
_emulator_append_external_api_impl
(
x64_emulator, "strlen",
x64_assembler.assemble
(
"xor rcx, rcx;"
"dec rcx;"
"xor rax, rax;"
"repne scasb byte ptr [rdi];"
"not rcx;"
"dec rcx;"
"mov rax, rcx;"
"ret;"
)
);
_emulator_append_external_api_impl
(
x64_emulator, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm",
x64_assembler.assemble
(
fmt::format
(
" push r12;"
" push r13;"
" push r14;"
" push r15;"
" mov r12, qword ptr [rdi];"
" mov r13, qword ptr [rdi + 0x8];"
" mov r14, 15;"
" lea rax, qword ptr [rdi + 0x10];"
" cmp r12, rax;"
" cmovne r14, qword ptr [rdi + 0x10];"
" xor r15, r15;"
" lea rax, qword ptr [r13 + rdx];"
" cmp rax, r14;"
" jbe append_string;"
"reallocate:"
" push rdi;"
" push rsi;"
" push rdx;"
" lea r14, qword ptr [r13 + rdx];"
" lea rdi, qword ptr [r14 + 0x1];"
" mov rax, {malloc:#016x};"
" call rax;"
" mov rdi, rax;"
" mov rsi, r12;"
" mov rcx, r13;"
" rep movs byte ptr [rdi], byte ptr [rsi];"
" mov r12, rax;"
" mov rdi, qword ptr [rsp + 0x10];"
" lea rax, qword ptr [rdi + 0x10];"
" mov rdi, qword ptr [rdi];"
" cmp rdi, rax;"
" je label_0;"
" mov rax, {free:#016x};"
" call rax;"
"label_0:"
" pop rdx;"
" pop rsi;"
" pop rdi;"
" mov r15b, 0x1;"
"append_string:"
" push rdi;"
" push rsi;"
" lea rdi, qword ptr [r12 + r13];"
" mov rcx, rdx;"
" rep movs byte ptr [rdi], byte ptr [rsi];"
" mov byte ptr [rdi], 0;"
" pop rsi;"
" pop rdi;"
" add r13, rdx;"
"update_string_struct:"
" mov qword ptr [rdi + 0x8], r13;"
" test r15, r15;"
" jz final;"
" mov qword ptr [rdi], r12;"
" mov qword ptr [rdi + 0x10], r14;"
"final:"
" mov rax, rdi;"
" pop r15;"
" pop r14;"
" pop r13;"
" pop r12;"
" ret;",
fmt::arg("malloc", external_api_impl["malloc"]),
fmt::arg("free", external_api_impl["free"])
)
)
);
_emulator_append_external_api_impl
(
x64_emulator, "_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7compareEPKc",
x64_assembler.assemble
(
// rcx = strlen(rsi);
" push rsi;"
" xor rcx, rcx;"
" dec rcx;"
"strlen_loop:"
" inc rcx;"
" cmp byte ptr [rsi + rcx], 0x00;"
" jne strlen_loop;"
" pop rsi;"
// rdx = rcx;
// rcx = min(this->_M_string_length, rcx);
" mov rdx, rcx;"
" cmp qword ptr [rdi + 0x8], rcx;"
" cmovb rcx, qword ptr [rdi + 0x8];"
// if (rcx == 0 || memcmp(this->_M_dataplus, rsi, rcx) == 0) goto compare_length;
" test rcx, rcx;"
" jz compare_length;"
"memcmp:"
" push rdi;"
" push rsi;"
" mov rdi, qword ptr [rdi];"
" xchg rsi, rdi;"
" repe cmps byte ptr [rsi], byte ptr [rdi];"
" pop rsi;"
" pop rdi;"
" jl return_negative;"
" jg return_positive;"
"compare_length:"
" cmp qword ptr [rdi + 0x8], rdx;"
" ja return_positive;"
" jb return_negative;"
"return_zero:"
" xor eax, eax;"
" ret;"
"return_positive:"
" mov eax, 1;"
" ret;"
"return_negative:"
" mov eax, 0xffffffff;"
" ret;"
)
);
_emulator_append_external_api_impl
(
x64_emulator, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9push_backEc",
x64_assembler.assemble
(
fmt::format
(
" push rsi;"
" mov rsi, rsp;"
" mov rdx, 0x1;"
" mov rax, {_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm:#016x};"
" call rax;"
" pop rsi;"
" ret;",
fmt::arg("_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm", external_api_impl["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm"])
)
)
);
_emulator_append_external_api_impl
(
x64_emulator, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendEPKc",
x64_assembler.assemble
(
fmt::format
(
" push rsi;"
" xor rdx, rdx;"
" dec rdx;"
"strlen_loop:"
" inc rdx;"
" cmp byte ptr [rsi + rdx], 0x00;"
" jne strlen_loop;"
" pop rsi;"
" mov rax, {_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm:#016x};"
" jmp rax;",
fmt::arg("_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm", external_api_impl["_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm"])
)
)
);
_emulator_append_external_api_impl
(
x64_emulator, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE10_M_disposeEv",
x64_assembler.assemble
(
fmt::format
(
" mov rcx, qword ptr [rdi];"
" lea rdx, qword ptr [rdi + 0x10];"
" cmp rcx, rdx;"
" je return;"
" mov rdi, rcx;"
" mov rax, {free:#016x};"
" call rax;"
"return:"
" ret",
fmt::arg("free", external_api_impl["free"])
)
)
);
x64_emulator.hook_add<UC_HOOK_CODE>
(std::bind(&patch_solution_since::_emulator_dl_runtime_resolve_handler, this, std::ref(x64_emulator), std::placeholders::_1, std::placeholders::_2), external_api_impl["dl_runtime_resolve"], external_api_impl["dl_runtime_resolve"]);
x64_emulator.hook_add<UC_HOOK_CODE>
(std::bind(&patch_solution_since::_emulator_malloc_handler, this, std::ref(x64_emulator), std::placeholders::_1, std::placeholders::_2), external_api_impl["malloc"], external_api_impl["malloc"]);
x64_emulator.hook_add<UC_HOOK_CODE>
(std::bind(&patch_solution_since::_emulator_free_handler, this, std::ref(x64_emulator), std::placeholders::_1, std::placeholders::_2), external_api_impl["free"], external_api_impl["free"]);
}
// set page fault handler
x64_emulator.hook_add<UC_HOOK_MEM_UNMAPPED>
(std::bind(&patch_solution_since::_emulator_page_fault_handler, this, std::ref(x64_emulator), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
// set rbp, rsp
uint64_t init_rbp = x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") / 4;
uint64_t init_rsp = x64_emulator.context_get<uint64_t>("stack_base") - x64_emulator.context_get<size_t>("stack_size") / 2;
x64_emulator.reg_write(UC_X86_REG_RBP, &init_rbp);
x64_emulator.reg_write(UC_X86_REG_RSP, &init_rsp);
// set return address
auto retaddr = x64_emulator.context_get<uint64_t>("dead_address");
x64_emulator.mem_write(init_rsp, &retaddr, sizeof(retaddr));
// set argument registers
uint64_t init_rdi = init_rsp + 0x40; // a pointer to stack memory which stores return value
x64_emulator.reg_write(UC_X86_REG_RDI, &init_rdi);
std::list<std::pair<elf64_interpreter::va_t, size_t>> tracing;
x64_emulator.hook_add<UC_HOOK_CODE>(
[&x64_emulator, &tracing, stack_frame_index = 0](uint64_t address, size_t size) mutable {
std::byte instruction_data[16]; // a x86-64 instruction is 16-bytes long at most
x64_emulator.mem_read(address, instruction_data, size);
if (stack_frame_index == 0) {
if (tracing.size() > 0 && tracing.back().first + tracing.back().second == address) {
tracing.back().second += size;
} else {
tracing.emplace_back(std::make_pair(address, size));
}
}
bool is_near_call =
instruction_data[0] == std::byte{ 0xe8 } ||
instruction_data[0] == std::byte{ 0xff } && (instruction_data[1] & std::byte{ 0b00111000 }) == std::byte{ 0b00010000 }; // FF /2
if (is_near_call) {
++stack_frame_index;
return;
}
bool is_near_ret =
instruction_data[0] == std::byte{ 0xc2 } ||
instruction_data[0] == std::byte{ 0xc3 };
if (is_near_ret) {
--stack_frame_index;
return;
}
}
);
// start emulate
try {
x64_emulator.emu_start(x64_emulator.context_get<uint64_t>("start_address"), x64_emulator.context_get<uint64_t>("dead_address"));
} catch (amd64_emulator::backend_error& e) {
printf("[-] patch_solution_since<16, 0, 7, 0>: Code emulation failed. %s\n", e.error_string().c_str());
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
if (m_va_pltgot_std_string_append == 0) {
if (m_libcc_interpreter.elf_dynamic_pltrel().value() == DT_REL) {
auto jmp_reloc_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Rel*>(m_libcc_interpreter.elf_dynamic_jmprel().value());
auto jmp_reloc_table_size = m_libcc_interpreter.elf_dynamic_pltrelsz().value() / sizeof(Elf64_Rel);
auto symbol_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Sym*>(m_libcc_interpreter.elf_dynamic_symtab().value());
auto string_table = m_libcc_interpreter.convert_va_to_ptr<char*>(m_libcc_interpreter.elf_dynamic_strtab().value());
for (size_t i = 0; i < jmp_reloc_table_size; ++i) {
auto reloc_va = jmp_reloc_table[i].r_offset;
auto reloc_sym = &symbol_table[ELF64_R_SYM(jmp_reloc_table[i].r_info)];
auto reloc_type = ELF64_R_TYPE(jmp_reloc_table[i].r_info);
auto reloc_sym_name = &string_table[reloc_sym->st_name];
if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendEPKc") == 0) {
m_va_pltgot_std_string_append = reloc_va;
break;
}
}
} else { // m_libcc_interpreter.elf_dynamic_pltrel().value() == DT_RELA
auto jmp_reloc_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Rela*>(m_libcc_interpreter.elf_dynamic_jmprel().value());
auto jmp_reloc_table_size = m_libcc_interpreter.elf_dynamic_pltrelsz().value() / sizeof(Elf64_Rela);
auto symbol_table = m_libcc_interpreter.convert_va_to_ptr<Elf64_Sym*>(m_libcc_interpreter.elf_dynamic_symtab().value());
auto string_table = m_libcc_interpreter.convert_va_to_ptr<char*>(m_libcc_interpreter.elf_dynamic_strtab().value());
for (size_t i = 0; i < jmp_reloc_table_size; ++i) {
auto reloc_va = jmp_reloc_table[i].r_offset;
auto reloc_sym = &symbol_table[ELF64_R_SYM(jmp_reloc_table[i].r_info)];
auto reloc_type = ELF64_R_TYPE(jmp_reloc_table[i].r_info);
auto reloc_sym_name = &string_table[reloc_sym->st_name];
if (strcmp(reloc_sym_name, "_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendEPKc") == 0) {
m_va_pltgot_std_string_append = reloc_va;
break;
}
}
}
}
if (m_va_pltgot_std_string_append) {
printf("[*] patch_solution_since<16, 0, 7, 0>: m_va_pltgot_std_string_append = 0x%016lx\n", m_va_pltgot_std_string_append);
} else {
printf("[*] patch_solution_since<16, 0, 7, 0>: std::string::append(const char*) is not found.\n");
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
m_tracing = std::move(tracing);
//
// get result
//
// on AMD64 platform, `std::string` has follow memory layout:
// ------------------------------
// | offset | size |
// ------------------------------
// | +0 | 0x8 | char*: raw string ptr
// ------------------------------
// | +0x8 | 0x8 | size_t: string length
// ------------------------------
// | +0x10 | 0x8 | `char[16]: a small string buffer` OR `size_t: capacity`
// ------------------------------
//
uint64_t encoded_key_length;
x64_emulator.mem_read(init_rdi + 0x8, &encoded_key_length, sizeof(encoded_key_length));
if (encoded_key_length != official_encoded_key.length()) {
printf("[-] patch_solution_since<16, 0, 7, 0>: unexpected encoded key length(%lu).\n", encoded_key_length);
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
uint64_t encoded_key_ptr;
x64_emulator.mem_read(init_rdi, &encoded_key_ptr, sizeof(encoded_key_ptr));
auto encoded_key = x64_emulator.mem_read(encoded_key_ptr, encoded_key_length);
if (memcmp(encoded_key.data(), official_encoded_key.data(), encoded_key.size()) == 0) {
printf("[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.\n");
return true;
} else {
printf("[-] patch_solution_since<16, 0, 7, 0>: official encoded key is not found.\n");
printf("[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
}
bool patch_solution_since<16, 0, 7, 0>::check_rsa_privkey(const rsa_cipher& cipher) {
return cipher.bits() == 2048;
}
void patch_solution_since<16, 0, 7, 0>::make_patch(const rsa_cipher& cipher) {
auto new_encoded_key = _build_encoded_key(cipher);
auto CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey =
m_libcc_interpreter.convert_va_to_ptr<uint8_t*>(m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey);
std::vector<std::string> patch_code_chunks;
patch_code_chunks.emplace_back("push rbp;");
patch_code_chunks.emplace_back("mov rbp, rsp;");
patch_code_chunks.emplace_back("lea rax, qword ptr [rdi + 0x10];");
patch_code_chunks.emplace_back("mov qword ptr [rdi], rax;");
patch_code_chunks.emplace_back("mov qword ptr [rdi + 0x8], 0;");
{
std::vector<uint64_t> push_values((new_encoded_key.length() + 1 + 7) / 8, 0);
memcpy(push_values.data(), new_encoded_key.data(), new_encoded_key.length());
std::for_each
(
push_values.crbegin(),
push_values.crend(),
[&patch_code_chunks](uint64_t x) {
patch_code_chunks.emplace_back(fmt::format("mov rax, {:#016x};", x));
patch_code_chunks.emplace_back("push rax;");
}
);
}
patch_code_chunks.emplace_back("mov rsi, rsp;");
patch_code_chunks.emplace_back(fmt::format("call qword ptr [{:#016x}];", m_va_pltgot_std_string_append)); // keystone will emit `call qword ptr [rip+xxx]` here
patch_code_chunks.emplace_back("leave;");
patch_code_chunks.emplace_back("ret;");
auto x86_assembler = keystone_assembler{ KS_ARCH_X86, KS_MODE_64 };
auto reliable_areas = _calculate_reliable_areas();
auto current_va = m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey;
auto current_ptr = m_libcc_interpreter.convert_va_to_ptr<uint8_t*>(current_va);
auto current_reliable_area = reliable_areas.begin();
auto current_reliable_area_begin_va = current_reliable_area->first;
auto current_reliable_area_end_va = current_reliable_area_begin_va + current_reliable_area->second;
for (const auto& patch_code_chunk : patch_code_chunks) {
while (true) {
auto assembled_patch_code_chunk = x86_assembler.assemble(patch_code_chunk, current_va);
constexpr size_t jmp_code_max_size = 1 + sizeof(uint32_t);
if (current_reliable_area_begin_va <= current_va && current_va + assembled_patch_code_chunk.size() + jmp_code_max_size <= current_reliable_area_end_va) {
memcpy(current_ptr, assembled_patch_code_chunk.data(), assembled_patch_code_chunk.size());
current_va += assembled_patch_code_chunk.size();
current_ptr += assembled_patch_code_chunk.size();
break;
} else {
auto next_reliable_area = std::next(current_reliable_area);
while (next_reliable_area->second < 0x10) {
next_reliable_area = std::next(next_reliable_area);
}
auto assembled_jmp = x86_assembler.assemble(fmt::format("jmp {:#016x};", next_reliable_area->first), current_va);
memcpy(current_ptr, assembled_jmp.data(), assembled_jmp.size());
current_va = next_reliable_area->first;
current_ptr = m_libcc_interpreter.convert_va_to_ptr<uint8_t*>(next_reliable_area->first);
current_reliable_area = next_reliable_area;
current_reliable_area_begin_va = current_reliable_area->first;
current_reliable_area_end_va = current_reliable_area_begin_va + current_reliable_area->second;
}
}
}
printf("[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.\n");
}
}

View File

@ -0,0 +1,16 @@
#include "patch_solution_since_16.0.7.0.hpp"
#include <regex>
namespace nkg {
std::string patch_solution_since<16, 0, 7, 0>::_build_encoded_key(const rsa_cipher& cipher) {
auto encoded_key = cipher.export_public_key_string_pem();
encoded_key = std::regex_replace(encoded_key, std::regex("-----BEGIN PUBLIC KEY-----"), "");
encoded_key = std::regex_replace(encoded_key, std::regex("-----END PUBLIC KEY-----"), "");
encoded_key = std::regex_replace(encoded_key, std::regex("\n"), "");
return encoded_key;
}
}

View File

@ -1,9 +1,9 @@
#pragma once
#include <string>
#include <list>
#include "patch_solution_since.hpp"
#include "elf64_interpreter.hpp"
#include "amd64_emulator.hpp"
#include "image_interpreter.hpp"
#include <any>
#include <string>
#include <map>
namespace nkg {
@ -11,33 +11,16 @@ namespace nkg {
class patch_solution_since<16, 0, 7, 0> final : public patch_solution {
private:
static inline std::string_view official_encoded_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw1dqF3SkCaAAmMzs889IqdW9M2dIdh3jG9yPcmLnmJiGpBF4E9VHSMGe8oPAy2kJDmdNt4BcEygvssEfginva5t5jm352UAoDosUJkTXGQhpAWMF4fBmBpO3EedG62rOsqMBgmSdAyxCSPBRJIOFR0QgZFbRnU0frj34fiVmgYiLuZSAmIbs8ZxiHPdp1oD4tUpvsFci4QJtYNjNnGU2WPH6rvChGl1IRKrxMtqLielsvajUjyrgOC6NmymYMvZNER3htFEtL1eQbCyTfDmtYyQ1Wt4Ot12lxf0wVIR5mcGN7XCXJRHOFHSf1gzXWabRSvmt1nrl7sW6cjxljuuQawIDAQAB";
image_interpreter& m_libcc_interpreter;
image_interpreter::va_t m_va_CSRegistrationInfoFetcher_WIN_vtable;
image_interpreter::va_t m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey;
image_interpreter::va_t m_va_iat_entry_malloc;
elf64_interpreter& m_libcc_interpreter;
elf64_interpreter::va_t m_va_CSRegistrationInfoFetcher_LINUX_vtable;
elf64_interpreter::va_t m_va_CSRegistrationInfoFetcher_LINUX_GenerateRegistrationKey;
elf64_interpreter::va_t m_va_pltgot_std_string_append;
std::list<std::pair<elf64_interpreter::va_t, size_t>> m_tracing;
uint64_t _emulator_append_external_api_impl(amd64_emulator& x64_emulator, std::string_view api_name, const std::vector<uint8_t>& api_impl);
uint64_t _emulator_malloc(amd64_emulator& x64_emulator, size_t alloc_size);
void _emulator_free(amd64_emulator& x64_emulator, uint64_t alloc_p);
bool _emulator_page_fault_handler(amd64_emulator& x64_emulator, uc_mem_type access, uint64_t address, size_t size, int64_t value);
void _emulator_dl_runtime_resolve_handler(amd64_emulator& x64_emulator, uint64_t address, size_t size);
void _emulator_malloc_handler(amd64_emulator& x64_emulator, uint64_t address, size_t size);
void _emulator_free_handler(amd64_emulator& x64_emulator, uint64_t address, size_t size);
static std::string _build_encoded_key(const rsa_cipher& cipher);
std::list<std::pair<elf64_interpreter::va_t, size_t>> _calculate_reliable_areas() const;
std::string _build_encoded_key(const rsa_cipher& cipher);
public:
patch_solution_since(elf64_interpreter& libcc_interpreter);
patch_solution_since(image_interpreter& libcc_interpreter);
[[nodiscard]]
virtual bool find_patch() override;

View File

@ -0,0 +1,629 @@
#define _CRT_SECURE_NO_WARNINGS
#include "i386_emulator.hpp"
#include "keystone_assembler.hpp"
#include "patch_solution_since_16.0.7.0.hpp"
#include <algorithm>
#include <fmt/format.h>
namespace nkg {
patch_solution_since<16, 0, 7, 0>::patch_solution_since(image_interpreter& libcc_interpreter) :
m_libcc_interpreter(libcc_interpreter),
m_va_CSRegistrationInfoFetcher_WIN_vtable(0),
m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey(0),
m_va_iat_entry_malloc(0) {}
bool patch_solution_since<16, 0, 7, 0>::find_patch() {
auto CSRegistrationInfoFetcher_WIN_type_descriptor_name =
m_libcc_interpreter.search_section<const uint8_t*>(
".data",
[](const uint8_t* p, size_t s) {
if (s < sizeof(".?AVCSRegistrationInfoFetcher_WIN@@")) {
return false;
}
return strcmp(reinterpret_cast<const char*>(p), ".?AVCSRegistrationInfoFetcher_WIN@@") == 0;
}
);
if (CSRegistrationInfoFetcher_WIN_type_descriptor_name == nullptr) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_WIN is not found. (failure label 0)\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_WIN_rtti_type_descriptor = CSRegistrationInfoFetcher_WIN_type_descriptor_name - 0x8;
auto CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_va = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_rtti_type_descriptor);
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor =
m_libcc_interpreter.search_section<const uint8_t*>(
".rdata",
[this, CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_va](const uint8_t* p, size_t s) {
if (reinterpret_cast<uintptr_t>(p) % sizeof(uint32_t) != 0) {
return false;
}
if (s < sizeof(uint32_t)) {
return false;
}
if (*reinterpret_cast<const uint32_t*>(p) != CSRegistrationInfoFetcher_WIN_rtti_type_descriptor_va) {
return false;
}
if (s < sizeof(uint32_t) * 2) {
return false;
}
auto maybe_CSRegistrationInfoFetcher_WIN_rtti_class_hierarchy_descriptor_va = reinterpret_cast<const uint32_t*>(p)[1];
try {
return memcmp(m_libcc_interpreter.image_section_header_from_va(maybe_CSRegistrationInfoFetcher_WIN_rtti_class_hierarchy_descriptor_va)->Name, ".rdata\x00\x00", 8) == 0;
} catch (nkg::exception&) {
return false;
}
}
);
if (CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor == nullptr) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: RTTI info for CSRegistrationInfoFetcher_WIN is not found. (failure label 1)\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator = CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_pTypeDescriptor - 0xC;
auto CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator);
auto CSRegistrationInfoFetcher_WIN_vtable_before =
m_libcc_interpreter.search_section<const uint8_t*>(
".rdata",
[CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va](const uint8_t* p, size_t s) {
if (reinterpret_cast<uintptr_t>(p) % sizeof(uint32_t) != 0) {
return false;
}
if (s < sizeof(uint32_t)) {
return false;
}
return *reinterpret_cast<const uint32_t*>(p) == CSRegistrationInfoFetcher_WIN_rtti_complete_object_locator_va;
}
);
if (CSRegistrationInfoFetcher_WIN_vtable_before == nullptr) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Vftable for CSRegistrationInfoFetcher_WIN is not found.\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
auto CSRegistrationInfoFetcher_WIN_vtable =
reinterpret_cast<const uint32_t*>(CSRegistrationInfoFetcher_WIN_vtable_before + sizeof(uint32_t));
m_va_CSRegistrationInfoFetcher_WIN_vtable = m_libcc_interpreter.convert_ptr_to_va(CSRegistrationInfoFetcher_WIN_vtable);
m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = CSRegistrationInfoFetcher_WIN_vtable[6];
wprintf(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x%08x\n", m_va_CSRegistrationInfoFetcher_WIN_vtable);
wprintf(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x%08x\n", m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey);
i386_emulator x86_emulator;
x86_emulator.context_set("heap_base", uint32_t{ 0x7f000000 });
x86_emulator.context_set("heap_size", size_t{ 0x1000 * 32 });
x86_emulator.context_set("heap_records", std::map<uint32_t, uint32_t>{});
x86_emulator.context_set("stack_base", uint32_t{ 0x7fff0000 });
x86_emulator.context_set("stack_size", size_t{ 0x1000 * 32 });
x86_emulator.context_set("stack_top", uint32_t{ x86_emulator.context_get<uint32_t>("stack_base") - x86_emulator.context_get<size_t>("stack_size") });
x86_emulator.context_set("r0_to_r3_stub_area_base", uint32_t{ 0xffffe000 });
x86_emulator.context_set("r0_to_r3_stub_area_size", size_t{ 0x1000 });
x86_emulator.context_set("dead_area_base", uint32_t{ 0xfffff000 });
x86_emulator.context_set("dead_area_size", size_t{ 0x1000 });
x86_emulator.context_set("iat_base", uint32_t{ m_libcc_interpreter.convert_rva_to_va(m_libcc_interpreter.image_nt_headers()->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) });
x86_emulator.context_set("iat_size", size_t{ m_libcc_interpreter.image_nt_headers()->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size });
x86_emulator.context_set("external_api_stub_area_base", uint32_t{ 0x80000000 });
x86_emulator.context_set("external_api_stub_area_size", size_t{ (x86_emulator.context_get<size_t>("iat_size") / 8 + 0xfff) / 0x1000 * 0x1000 });
x86_emulator.context_set("external_api_impl", std::map<std::string, uint32_t>{});
x86_emulator.context_set("external_api_impl_area_base", uint32_t{ 0x90000000 });
x86_emulator.context_set("external_api_impl_area_size", size_t{ 0 });
x86_emulator.context_set("gdt_base", uint32_t{ 0xffff0000 });
x86_emulator.context_set("gdt_size", size_t{ 0x1000 });
x86_emulator.context_set("fs_base", uint32_t{ 0xa0000000 });
x86_emulator.context_set("fs_size", size_t{ 0x1000 });
x86_emulator.context_set("start_address", static_cast<uint32_t>(m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey));
x86_emulator.context_set("dead_address", x86_emulator.context_get<uint32_t>("dead_area_base"));
// allocate heap
x86_emulator.mem_map(x86_emulator.context_get<uint32_t>("heap_base"), x86_emulator.context_get<size_t>("heap_size"), UC_PROT_READ | UC_PROT_WRITE);
// allocate stack
x86_emulator.mem_map(x86_emulator.context_get<uint32_t>("stack_top"), x86_emulator.context_get<size_t>("stack_size"), UC_PROT_READ | UC_PROT_WRITE);
// allocate r0_to_r3_stub area
x86_emulator.mem_map(x86_emulator.context_get<uint32_t>("r0_to_r3_stub_area_base"), x86_emulator.context_get<size_t>("r0_to_r3_stub_area_size"), UC_PROT_READ | UC_PROT_EXEC);
x86_emulator.mem_write(x86_emulator.context_get<uint32_t>("r0_to_r3_stub_area_base"), keystone_assembler{ KS_ARCH_X86, KS_MODE_32 }.assemble("iretd;"));
// allocate dead area
x86_emulator.mem_map(x86_emulator.context_get<uint32_t>("dead_area_base"), x86_emulator.context_get<size_t>("dead_area_size"), UC_PROT_READ | UC_PROT_EXEC);
// allocate and hook read access to IAT
{
auto iat_base = x86_emulator.context_get<uint32_t>("iat_base");
auto iat_size = x86_emulator.context_get<size_t>("iat_size");
auto external_api_stub_area_base = x86_emulator.context_get<uint32_t>("external_api_stub_area_base");
auto iat_page_base = iat_base / 0x1000 * 0x1000;
auto iat_page_count = (iat_base - iat_page_base + iat_size + 0xfff) / 0x1000;
x86_emulator.mem_map(iat_page_base, iat_page_count * 0x1000, UC_PROT_READ);
x86_emulator.hook_add<UC_HOOK_MEM_READ>(
[this, &x86_emulator, iat_base, external_api_stub_area_base](uc_mem_type type, uint32_t address, size_t size, int32_t value) {
auto rva = m_libcc_interpreter.convert_va_to_rva(address);
auto import_lookup_entry = m_libcc_interpreter.import_lookup_entry_from_rva(rva);
if (import_lookup_entry && !IMAGE_SNAP_BY_ORDINAL(import_lookup_entry->u1.Ordinal)) {
auto import_by_name_entry = m_libcc_interpreter.convert_rva_to_ptr<PIMAGE_IMPORT_BY_NAME>(import_lookup_entry->u1.AddressOfData);
if (strcmp(import_by_name_entry->Name, "memcpy") == 0) {
uint32_t impl_address = x86_emulator.context_get<std::map<std::string, uint32_t>&>("external_api_impl")["memcpy"];
x86_emulator.mem_write(address, &impl_address, sizeof(impl_address));
} else {
uint32_t stub_address = external_api_stub_area_base + (address - iat_base) / sizeof(IMAGE_THUNK_DATA);
x86_emulator.mem_write(address, &stub_address, sizeof(stub_address));
}
} else {
x86_emulator.emu_stop();
}
},
iat_base,
iat_base + iat_size - 1
);
}
// allocate and setup external api stub area
{
auto external_api_stub_area_base = x86_emulator.context_get<uint32_t>("external_api_stub_area_base");
auto external_api_stub_area_size = x86_emulator.context_get<size_t>("external_api_stub_area_size");
x86_emulator.mem_map(external_api_stub_area_base, external_api_stub_area_size, UC_PROT_READ | UC_PROT_EXEC);
x86_emulator.mem_write(external_api_stub_area_base, std::vector<uint8_t>(external_api_stub_area_size, 0xc3)); // c3 -> ret
x86_emulator.hook_add<UC_HOOK_CODE>(
[this, &x86_emulator, external_api_stub_area_base](uint32_t address, size_t size) {
auto iat_base = x86_emulator.context_get<uint32_t>("iat_base");
auto from_va = iat_base + (address - external_api_stub_area_base) * sizeof(IMAGE_THUNK_DATA);
auto from_rva = m_libcc_interpreter.convert_va_to_rva(from_va);
auto import_lookup_entry = m_libcc_interpreter.import_lookup_entry_from_rva(from_rva);
if (import_lookup_entry && !IMAGE_SNAP_BY_ORDINAL(import_lookup_entry->u1.Ordinal)) {
auto import_by_name_entry = m_libcc_interpreter.convert_rva_to_ptr<PIMAGE_IMPORT_BY_NAME>(import_lookup_entry->u1.AddressOfData);
if (strcmp(import_by_name_entry->Name, "malloc") == 0) {
m_va_iat_entry_malloc = from_va;
uint32_t esp;
x86_emulator.reg_read(UC_X86_REG_ESP, &esp);
uint32_t alloc_size;
x86_emulator.mem_read(esp + 4, &alloc_size, sizeof(alloc_size));
auto& heap_records = x86_emulator.context_get<std::map<uint32_t, uint32_t>&>("heap_records");
auto predecessor_chunk =
std::adjacent_find(
heap_records.begin(),
heap_records.end(),
[alloc_size](const auto& chunk0, const auto& chunk1) { return chunk1.first - (chunk0.first + chunk0.second) >= alloc_size; }
);
uint32_t alloc_p;
if (predecessor_chunk != heap_records.end()) {
alloc_p = predecessor_chunk->first + predecessor_chunk->second;
} else {
auto heap_base = x86_emulator.context_get<uint32_t>("heap_base");
auto heap_size = x86_emulator.context_get<uint32_t>("heap_size");
auto free_space_base = heap_records.size() > 0 ? heap_records.rbegin()->first + heap_records.rbegin()->second : heap_base;
auto free_space_size = heap_base + heap_size - free_space_base;
if (free_space_size < alloc_size) {
auto heap_expand_base = heap_base + heap_size;
auto heap_expand_size = (alloc_size - free_space_size + 0xfff) / 0x1000 * 0x1000;
x86_emulator.mem_map(heap_expand_base, heap_expand_size, UC_PROT_READ | UC_PROT_WRITE);
}
alloc_p = free_space_base;
}
heap_records[alloc_p] = alloc_size;
x86_emulator.reg_write(UC_X86_REG_EAX, &alloc_p);
} else if (strcmp(import_by_name_entry->Name, "free") == 0) {
uint32_t esp;
x86_emulator.reg_read(UC_X86_REG_ESP, &esp);
uint32_t alloc_p;
x86_emulator.mem_read(esp + 4, &alloc_p, sizeof(alloc_p));
auto& heap_records = x86_emulator.context_get<std::map<uint32_t, uint32_t>&>("heap_records");
auto chunk = heap_records.find(alloc_p);
if (chunk != heap_records.end()) {
heap_records.erase(chunk);
} else {
x86_emulator.emu_stop();
}
} else {
x86_emulator.emu_stop();
}
} else {
x86_emulator.emu_stop();
}
},
external_api_stub_area_base,
external_api_stub_area_base + external_api_stub_area_size - 1
);
}
// allocate and setup external api impl area
{
keystone_assembler x86_assembler{ KS_ARCH_X86, KS_MODE_32 };
std::map<std::string, std::vector<uint8_t>> machine_code_list =
{
std::make_pair(
"memcpy",
x86_assembler.assemble(
"push edi;"
"push esi;"
"mov eax, dword ptr [esp + 0x8 + 0x4];"
"mov edi, eax;"
"mov esi, dword ptr [esp + 0x8 + 0x8];"
"mov ecx, dword ptr [esp + 0x8 + 0xc];"
"rep movs byte ptr [edi], byte ptr [esi];"
"pop esi;"
"pop edi;"
"ret;"
)
)
};
auto& external_api_impl = x86_emulator.context_get<std::map<std::string, uint32_t>&>("external_api_impl");
auto& external_api_impl_area_base = x86_emulator.context_get<uint32_t&>("external_api_impl_area_base");
auto& external_api_impl_area_size = x86_emulator.context_get<size_t&>("external_api_impl_area_size");
auto p = external_api_impl_area_base;
for (const auto& name_code_pair : machine_code_list) {
external_api_impl[name_code_pair.first] = p;
p = (p + name_code_pair.second.size() + 0xf) / 0x10 * 0x10;
}
external_api_impl_area_size = (p + 0xfff) / 0x1000 * 0x1000 - external_api_impl_area_base;
x86_emulator.mem_map(external_api_impl_area_base, external_api_impl_area_size, UC_PROT_READ | UC_PROT_EXEC);
for (const auto& name_code_pair : machine_code_list) {
x86_emulator.mem_write(external_api_impl[name_code_pair.first], name_code_pair.second);
}
}
// allocate and setup GDT, segment registers
{
auto gdt_base = x86_emulator.context_get<uint32_t>("gdt_base");
auto gdt_size = x86_emulator.context_get<size_t>("gdt_size");
x86_emulator.mem_map(gdt_base, gdt_size, UC_PROT_READ | UC_PROT_WRITE);
x86_emulator.create_gdt_entry(gdt_base, 0, 0, 0, 0); // null segment descriptor
// -------------------------------------------------------- access_byte
// 0x80 -> present bit
// (0 << 5) -> DPL is set to 0
// 0x10 -> code/data segment
// 0x08 -> executable segment
// !(0x4) -> not conforming code segment
// 0x02 -> code segment is readable
// !(0x01) -> accessed bit, this bit is managed by CPU
// -------------------------------------------------------- flags
// 0x08 -> 4k granularity
// 0x04 -> 32-bit protected mode segment
// !(0x01) -> AVL bit is not used
x86_emulator.create_gdt_entry(gdt_base + 1 * 0x8, 0x00000000, 0xfffff, 0x80 | (0 << 5) | 0x10 | 0x08 | !(0x04) | 0x02 | !(0x01), 0x08 | 0x04 | !(0x01)); // kernel code segment
// -------------------------------------------------------- access_byte
// 0x80 -> present bit
// (0 << 5) -> DPL is set to 0
// 0x10 -> code/data segment
// !(0x08) -> data segment
// !(0x4) -> segment grows up
// 0x02 -> data segment is writable
// !(0x01) -> accessed bit, this bit is managed by CPU
// -------------------------------------------------------- flags
// 0x08 -> 4k granularity
// 0x04 -> 32-bit protected mode segment
// !(0x01) -> AVL bit is not used
x86_emulator.create_gdt_entry(gdt_base + 2 * 0x8, 0x00000000, 0xfffff, 0x80 | (0 << 5) | 0x10 | !(0x08) | !(0x04) | 0x02 | !(0x01), 0x08 | 0x04 | !(0x01)); // kernel data segment
// -------------------------------------------------------- access_byte
// 0x80 -> present bit
// (3 << 5) -> DPL is set to 3
// 0x10 -> code/data segment
// 0x08 -> executable segment
// !(0x4) -> not conforming code segment
// 0x02 -> code segment is readable
// !(0x01) -> accessed bit, this bit is managed by CPU
// -------------------------------------------------------- flags
// 0x08 -> 4k granularity
// 0x04 -> 32-bit protected mode segment
// !(0x01) -> AVL bit is not used
x86_emulator.create_gdt_entry(gdt_base + 3 * 0x8, 0x00000000, 0xfffff, 0x80 | (3 << 5) | 0x10 | 0x08 | !(0x04) | 0x02 | !(0x01), 0x08 | 0x04 | !(0x01)); // user code segment
// -------------------------------------------------------- access_byte
// 0x80 -> present bit
// (3 << 5) -> DPL is set to 3
// 0x10 -> code/data segment
// !(0x08) -> data segment
// !(0x4) -> segment grows up
// 0x02 -> data segment is writable
// !(0x01) -> accessed bit, this bit is managed by CPU
// -------------------------------------------------------- flags
// 0x08 -> 4k granularity
// 0x04 -> 32-bit protected mode segment
// !(0x01) -> AVL bit is not used
x86_emulator.create_gdt_entry(gdt_base + 4 * 0x8, 0x00000000, 0xfffff, 0x80 | (3 << 5) | 0x10 | !(0x08) | !(0x04) | 0x02 | !(0x01), 0x08 | 0x04 | !(0x01)); // user data segment
// -------------------------------------------------------- access_byte
// 0x80 -> present bit
// (3 << 5) -> DPL is set to 3
// 0x10 -> code/data segment
// !(0x08) -> data segment
// !(0x4) -> segment grows up
// 0x02 -> data segment is writable
// !(0x01) -> accessed bit, this bit is managed by CPU
// -------------------------------------------------------- flags
// !(0x08) -> 1-byte granularity
// 0x04 -> 32-bit protected mode segment
// !(0x01) -> AVL bit is not used
auto fs_base = x86_emulator.context_get<uint32_t>("fs_base");
auto fs_size = x86_emulator.context_get<size_t>("fs_size");
x86_emulator.create_gdt_entry(gdt_base + 7 * 0x8, fs_base, fs_size - 1, 0x80 | (3 << 5) | 0x10 | !(0x08) | !(0x04) | 0x02 | !(0x01), !(0x08) | 0x04 | !(0x01)); // user fs segment
uc_x86_mmr gdtr = {};
gdtr.base = gdt_base;
gdtr.limit = gdt_base + gdt_size - 1;
x86_emulator.reg_write(UC_X86_REG_GDTR, &gdtr);
uint16_t cs, ds, es, fs, gs, ss;
cs = (1 << 3) | (0 << 2) | (0); // use kernel code segmet
ss = (2 << 3) | (0 << 2) | (0); // use kernel data segmet
ds = es = (4 << 3) | (0 << 2) | (3); // use user data segment
fs = (7 << 3) | (0 << 2) | (3); // use user fs segment
gs = 0; // not used
uint32_t eflags;
x86_emulator.reg_read(UC_X86_REG_EFLAGS, &eflags);
x86_emulator.reg_write(UC_X86_REG_CS, &cs);
x86_emulator.reg_write(UC_X86_REG_SS, &ss);
x86_emulator.reg_write(UC_X86_REG_DS, &ds);
x86_emulator.reg_write(UC_X86_REG_ES, &es);
x86_emulator.reg_write(UC_X86_REG_FS, &fs);
x86_emulator.reg_write(UC_X86_REG_GS, &gs);
}
// allocate and hook access to fs area
{
auto fs_base = x86_emulator.context_get<uint32_t>("fs_base");
auto fs_size = x86_emulator.context_get<size_t>("fs_size");
x86_emulator.mem_map(fs_base, fs_size, UC_PROT_READ | UC_PROT_WRITE);
x86_emulator.hook_add<UC_HOOK_MEM_READ>(
[this, &x86_emulator, fs_base](uc_mem_type access, uint32_t address, size_t size, int64_t value) {
switch (address - fs_base) {
case 0:
if (size == 4) {
// Current Structured Exception Handling (SEH) frame, leave it NULL
} else {
x86_emulator.emu_stop();
}
break;
default:
x86_emulator.emu_stop();
break;
}
},
fs_base,
fs_base + fs_size - 1
);
}
// x86_emulator.hook_add<UC_HOOK_CODE>([](uint32_t address, uint32_t size) { wprintf_s(L"code_trace, address = 0x%08x\n", address); });
x86_emulator.hook_add<UC_HOOK_MEM_UNMAPPED>(
[this, &x86_emulator](uc_mem_type access, uint32_t address, size_t size, int64_t value) -> bool {
try {
auto fault_section = m_libcc_interpreter.image_section_header_from_va(address);
auto page_base = address / 0x1000 * 0x1000;
auto page_size = 0x1000;
uint32_t page_perms = UC_PROT_NONE;
if (fault_section->Characteristics & IMAGE_SCN_MEM_READ) {
page_perms |= UC_PROT_READ;
}
if (fault_section->Characteristics & IMAGE_SCN_MEM_WRITE) {
page_perms |= UC_PROT_WRITE;
}
if (fault_section->Characteristics & IMAGE_SCN_MEM_EXECUTE) {
page_perms |= UC_PROT_EXEC;
}
x86_emulator.mem_map(page_base, page_size, page_perms);
x86_emulator.mem_write(page_base, m_libcc_interpreter.convert_va_to_ptr<const void*>(page_base), page_size);
return true;
} catch (::nkg::exception&) {
return false;
}
}
);
// set ebp, esp
uint32_t init_ebp = x86_emulator.context_get<uint32_t>("stack_base") - x86_emulator.context_get<size_t>("stack_size") / 4;
uint32_t init_esp = x86_emulator.context_get<uint32_t>("stack_base") - x86_emulator.context_get<size_t>("stack_size") / 2;
x86_emulator.reg_write(UC_X86_REG_EBP, &init_ebp);
x86_emulator.reg_write(UC_X86_REG_ESP, &init_esp);
// setup iretd context
uint32_t ring3_eip = x86_emulator.context_get<uint32_t>("start_address");
uint32_t ring3_cs = (3 << 3) | (0 << 2) | (3); // use user code segment
uint32_t ring3_eflags; x86_emulator.reg_read(UC_X86_REG_EFLAGS, &ring3_eflags);
uint32_t ring3_esp = init_esp + 5 * 4;
uint32_t ring3_ss = (4 << 3) | (0 << 2) | (3); // use user data segment
x86_emulator.mem_write(init_esp, &ring3_eip, sizeof(ring3_eip));
x86_emulator.mem_write(init_esp + 0x4, &ring3_cs, sizeof(ring3_cs));
x86_emulator.mem_write(init_esp + 0x8, &ring3_eflags, sizeof(ring3_eflags));
x86_emulator.mem_write(init_esp + 0xc, &ring3_esp, sizeof(ring3_esp));
x86_emulator.mem_write(init_esp + 0x10, &ring3_ss, sizeof(ring3_ss));
// set ring3 retaddr
uint32_t ring3_retaddr = x86_emulator.context_get<uint32_t>("dead_address");
x86_emulator.mem_write(ring3_esp, &ring3_retaddr, sizeof(ring3_retaddr));
// set argument registers
uint32_t init_ecx = 0; // `this` pointer of CSRegistrationInfoFetcher_WIN, but we don't need it for now.
uint32_t retval_addr = ring3_esp + 0x40; // a pointer to stack memory which stores return value
x86_emulator.reg_write(UC_X86_REG_ECX, &init_ecx);
x86_emulator.mem_write(ring3_esp + 4, &retval_addr, sizeof(retval_addr)); // write to dword ptr [ring3_esp + 4]
//
// start emulate
//
try {
x86_emulator.emu_start(x86_emulator.context_get<uint32_t>("r0_to_r3_stub_area_base"), x86_emulator.context_get<uint32_t>("dead_address"));
} catch (nkg::exception&) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Code emulation failed.\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
wprintf_s(L"[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x%08x\n", m_va_iat_entry_malloc);
//
// get result
//
// on I386 platform, `std::string` has follow memory layout:
// ------------------------------
// | offset | size |
// ------------------------------
// | +0 | 0x10 | `char[16]: a small string buffer` OR `char*: a large string buffer pointer`
// ------------------------------
// | +0x10 | 0x4 | size_t: string length
// ------------------------------
// | +0x14 | 0x4 | size_t: capacity
// ------------------------------
//
uint32_t encoded_key_length;
x86_emulator.mem_read(retval_addr + 0x10, &encoded_key_length, sizeof(encoded_key_length));
if (encoded_key_length != official_encoded_key.length()) {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Unexpected encoded key length(%u).\n", encoded_key_length);
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
uint32_t encoded_key_ptr;
x86_emulator.mem_read(retval_addr, &encoded_key_ptr, sizeof(encoded_key_ptr));
auto encoded_key = x86_emulator.mem_read(encoded_key_ptr, encoded_key_length);
if (memcmp(encoded_key.data(), official_encoded_key.data(), encoded_key.size()) == 0) {
wprintf_s(L"[+] patch_solution_since<16, 0, 7, 0>: Official encoded key is found.\n");
return true;
} else {
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: Official encoded key is not found.\n");
wprintf_s(L"[-] patch_solution_since<16, 0, 7, 0>: This patch solution will be suppressed.\n");
return false;
}
}
bool patch_solution_since<16, 0, 7, 0>::check_rsa_privkey(const rsa_cipher& cipher) {
return true; // no requirements
}
void patch_solution_since<16, 0, 7, 0>::make_patch(const rsa_cipher& cipher) {
auto encoded_key = _build_encoded_key(cipher);
auto CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey =
m_libcc_interpreter.convert_va_to_ptr<uint8_t*>(m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey);
std::vector<std::string> patch_code_chunks;
patch_code_chunks.emplace_back("push edi;");
patch_code_chunks.emplace_back("push esi;");
patch_code_chunks.emplace_back("push ebx;");
patch_code_chunks.emplace_back("push ebp;");
patch_code_chunks.emplace_back("mov ebp, esp;");
patch_code_chunks.emplace_back("call label; label: pop ebx; sub ebx, label;"); // ebx <- relocation shift value
patch_code_chunks.emplace_back(fmt::format("mov eax, {:#08x};", m_va_iat_entry_malloc));
patch_code_chunks.emplace_back("add eax, ebx;");
patch_code_chunks.emplace_back("mov eax, dword ptr [eax];"); // eax <- address of `malloc`
patch_code_chunks.emplace_back(fmt::format("push {:#x};", encoded_key.length() + 1));
patch_code_chunks.emplace_back("call eax;");
patch_code_chunks.emplace_back("add esp, 0x4;");
{
std::vector<uint32_t> push_values((encoded_key.length() + 1 + 3) / 4, 0);
memcpy(push_values.data(), encoded_key.data(), encoded_key.length());
std::for_each(push_values.crbegin(), push_values.crend(), [&patch_code_chunks](uint32_t x) { patch_code_chunks.emplace_back(fmt::format("push {:#08x};", x)); });
}
patch_code_chunks.emplace_back("mov edi, eax;");
patch_code_chunks.emplace_back("mov esi, esp;");
patch_code_chunks.emplace_back(fmt::format("mov ecx, {:#x};", encoded_key.length() + 1));
patch_code_chunks.emplace_back("rep movs byte ptr [edi], byte ptr [esi];");
patch_code_chunks.emplace_back("mov edx, dword ptr [ebp + 0x14];");
patch_code_chunks.emplace_back("mov dword ptr [edx], eax;");
patch_code_chunks.emplace_back(fmt::format("mov dword ptr [edx + 0x10], {:#x};", encoded_key.length()));
patch_code_chunks.emplace_back(fmt::format("mov dword ptr [edx + 0x14], {:#x};", encoded_key.length() + 1));
patch_code_chunks.emplace_back("mov eax, edx;");
patch_code_chunks.emplace_back("leave;");
patch_code_chunks.emplace_back("pop ebx;");
patch_code_chunks.emplace_back("pop esi;");
patch_code_chunks.emplace_back("pop edi;");
patch_code_chunks.emplace_back("ret 4;");
std::vector<uint8_t> assembled_patch_code;
{
keystone_assembler x86_assembler{ KS_ARCH_X86, KS_MODE_32 };
auto current_va = m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey;
auto next_reloc = m_libcc_interpreter.relocation_distribute().lower_bound(m_libcc_interpreter.convert_va_to_rva(current_va));
for (const auto& patch_code_chunk : patch_code_chunks) {
auto assembled_patch_code_chunk = x86_assembler.assemble(patch_code_chunk, current_va);
while (true) {
auto next_reloc_va = m_libcc_interpreter.convert_rva_to_va(next_reloc->first);
auto next_reloc_size = next_reloc->second;
if (current_va + assembled_patch_code_chunk.size() + 2 <= next_reloc_va) { // 2 -> size of machine code "jmp rel8"
assembled_patch_code.insert(assembled_patch_code.end(), assembled_patch_code_chunk.begin(), assembled_patch_code_chunk.end());
current_va += assembled_patch_code_chunk.size();
break;
} else if (current_va + 2 <= next_reloc_va) {
auto next_va = next_reloc_va + next_reloc_size;
auto assembled_jmp = x86_assembler.assemble(fmt::format("jmp {:#08x};", next_va), current_va);
auto assembled_padding = std::vector<uint8_t>(next_va - (current_va + assembled_jmp.size()), 0xcc); // 0xcc -> int3
assembled_patch_code.insert(assembled_patch_code.end(), assembled_jmp.begin(), assembled_jmp.end());
assembled_patch_code.insert(assembled_patch_code.end(), assembled_padding.begin(), assembled_padding.end());
current_va = next_va;
++next_reloc;
} else {
__assume(false); // impossible to reach here
}
}
}
}
memcpy(CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey, assembled_patch_code.data(), assembled_patch_code.size());
wprintf_s(L"[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.\n");
}
}

295
navicat-patcher/wmain.cpp Normal file
View File

@ -0,0 +1,295 @@
#include <stdio.h>
#include <windows.h>
#include <fmt/format.h>
#include <filesystem>
#include <optional>
#include "cp_converter.hpp"
#include "resource_wrapper.hpp"
#include "resource_traits/cxx_object_traits.hpp"
#include "resource_traits/win32/file_handle.hpp"
#include "resource_traits/win32/generic_handle.hpp"
#include "resource_traits/win32/map_view_ptr.hpp"
#include "rsa_cipher.hpp"
#include "image_interpreter.hpp"
#include "patch_solution.hpp"
#include "patch_solution_since_16.0.7.0.hpp"
#include "exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#include "exceptions/win32_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-patcher\\wmain.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
void welcome() {
_putws(L"***************************************************");
_putws(L"* navicat-patcher by @DoubleLabyrinth *");
_putws(L"* version: 16.0.7.0-2 *");
_putws(L"***************************************************");
_putws(L"");
}
void help() {
_putws(L"Usage:");
_putws(L" navicat-patcher.exe [-dry-run] <Navicat Install Path> [RSA-2048 PEM File Path]");
_putws(L"");
_putws(L" [-dry-run] Run patcher without applying any patches.");
_putws(L" This parameter is optional.");
_putws(L"");
_putws(L" <Navicat Install Path> Path to a directory where Navicat is installed.");
_putws(L" This parameter is mandatory.");
_putws(L"");
_putws(L" [RSA-2048 PEM File Path] Path to an RSA-2048 private key file.");
_putws(L" If not specified, an RSA-2048 private key file");
_putws(L" named \"RegPrivateKey.pem\" will be generated.");
_putws(L" This parameter is optional.");
_putws(L"");
_putws(L"Example:");
_putws(L" navicat-patcher.exe \"C:\\Program Files\\PremiumSoft\\Navicat Premium 12\"");
_putws(L"");
}
bool parse_cmdline(int argc, wchar_t* argv[], bool& dry_run, std::filesystem::path& navicat_install_path, std::filesystem::path& rsa_privkey_filepath) {
if (argc == 2) {
dry_run = false;
navicat_install_path = argv[1];
rsa_privkey_filepath.clear();
return true;
} else if (argc == 3) {
if (_wcsicmp(argv[1], L"-dry-run") == 0) {
dry_run = true;
navicat_install_path = argv[2];
rsa_privkey_filepath.clear();
return true;
} else {
dry_run = false;
navicat_install_path = argv[1];
rsa_privkey_filepath = argv[2];
return true;
}
} else if (argc == 4) {
if (_wcsicmp(argv[1], L"-dry-run") == 0) {
dry_run = true;
navicat_install_path = argv[2];
rsa_privkey_filepath = argv[3];
return true;
} else {
return false;
}
} else {
return false;
}
}
void select_patch_solutions
(nkg::resource_wrapper<nkg::resource_traits::cxx_object_traits<nkg::patch_solution>>& solution0)
{
return;
}
void load_rsa_privkey(nkg::rsa_cipher& cipher, std::filesystem::path& rsa_privkey_filepath, nkg::patch_solution* solution0) {
if (!rsa_privkey_filepath.empty()) {
wprintf_s(L"[*] Import RSA-2048 private key from\n");
wprintf_s(L" %s\n", rsa_privkey_filepath.native().c_str());
cipher.import_private_key_file(rsa_privkey_filepath);
if (solution0 && !solution0->check_rsa_privkey(cipher)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"The RSA private key you provide cannot be used.");
}
} else {
wprintf_s(L"[*] Generating new RSA private key, it may take a long time...\n");
do {
cipher.generate_key(2048);
} while (solution0 && !solution0->check_rsa_privkey(cipher)); // re-generate RSA key if one of `check_rsa_privkey` returns false
}
wprintf_s(L"[*] Your RSA private key:\n%s\n", nkg::cp_converter<CP_UTF8, -1>::convert(cipher.export_private_key_string()).c_str());
}
template<typename... args_t>
bool all_patch_solutions_are_suppressed(args_t&&... args) {
return (!args.is_valid() && ...);
}
void detect_backup(const std::filesystem::path& file_path) {
std::filesystem::path backup_path = file_path.native() + L".bak";
if (std::filesystem::is_regular_file(backup_path)) {
while (true) {
wprintf_s(L"[*] Previous backup %s is detected. Delete? (y/n)", backup_path.native().c_str());
auto select = getwchar();
while (select != L'\n' && getwchar() != L'\n') {}
if (select == L'Y' || select == L'y') {
std::filesystem::remove(backup_path);
break;
} else if (select == TEXT('N') || select == TEXT('n')) {
throw nkg::exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Backup file still exists. Patch abort!");
} else {
continue;
}
}
}
}
void make_backup(const std::filesystem::path& file_path) {
std::filesystem::path backup_path = file_path.native() + L".bak";
if (std::filesystem::exists(backup_path)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Previous backup is detected.")
.push_hint(fmt::format(u8"Please delete {} and try again.", nkg::cp_converter<-1, CP_UTF8>::convert(backup_path.native())));
} else {
std::filesystem::copy_file(file_path, backup_path);
}
}
int wmain(int argc, wchar_t* argv[]) {
welcome();
bool dry_run = false;
std::filesystem::path navicat_install_path;
std::filesystem::path rsa_privkey_filepath;
if (parse_cmdline(argc, argv, dry_run, navicat_install_path, rsa_privkey_filepath)) {
try {
if (!std::filesystem::is_directory(navicat_install_path)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Navicat install path doesn't point to a directory.")
.push_hint(u8"Are you sure the path you specified is correct?")
.push_hint(fmt::format(u8"The path you specified: {}", nkg::cp_converter<-1, CP_UTF8>::convert(navicat_install_path.native())));
}
if (!rsa_privkey_filepath.empty() && !std::filesystem::is_regular_file(rsa_privkey_filepath)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"RSA key file path doesn't point to a file.")
.push_hint(u8"Are you sure the path you specified is correct?")
.push_hint(fmt::format(u8"The path you specified: {}", nkg::cp_converter<-1, CP_UTF8>::convert(rsa_privkey_filepath.native())));
}
nkg::rsa_cipher cipher;
std::filesystem::path libcc_filepath = navicat_install_path / "libcc.dll";
nkg::resource_wrapper libcc_handle{ nkg::resource_traits::win32::file_handle{} };
nkg::resource_wrapper libcc_map_handle{ nkg::resource_traits::win32::generic_handle{} };
nkg::resource_wrapper libcc_map_view{ nkg::resource_traits::win32::map_view_ptr{} };
std::optional<nkg::image_interpreter> libcc_interpreter;
nkg::resource_wrapper solution0{ nkg::resource_traits::cxx_object_traits<nkg::patch_solution>{} };
// open libcc.dll
libcc_handle.set(CreateFileW(libcc_filepath.native().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL));
if (libcc_handle.is_valid()) {
wprintf_s(L"[+] Try to open libcc.dll ... OK!\n");
} else {
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
wprintf_s(L"[-] Try to open libcc.dll ... NOT FOUND!\n");
} else {
throw nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"Failed to open libcc.dll");
}
}
if (libcc_handle.is_valid()) {
libcc_map_handle.set(CreateFileMapping(libcc_handle.get(), NULL, PAGE_READWRITE, 0, 0, NULL));
if (!libcc_map_handle.is_valid()) {
throw nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"CreateFileMapping failed.");
}
libcc_map_view.set(MapViewOfFile(libcc_map_handle.get(), FILE_MAP_ALL_ACCESS, 0, 0, 0));
if (!libcc_map_view.is_valid()) {
throw nkg::exceptions::win32_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), GetLastError(), u8"MapViewOfFile failed.");
}
libcc_interpreter = nkg::image_interpreter::parse(libcc_map_view.get(), true);
solution0.set(new nkg::patch_solution_since<16, 0, 7, 0>(libcc_interpreter.value()));
}
_putws(L"");
// find patch and decide which solution will be applied
if (solution0.is_valid()) {
auto patch_found = solution0->find_patch();
_putws(L"");
if (!patch_found) {
solution0.release();
}
}
select_patch_solutions(solution0);
if (all_patch_solutions_are_suppressed(solution0)) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"All patch solutions are suppressed. Patch abort!")
.push_hint(u8"Are you sure your navicat has not been patched/modified before?");
}
// load key
load_rsa_privkey(cipher, rsa_privkey_filepath, solution0.get());
// apply patch solutions
if (dry_run) {
_putws(L"*******************************************************");
_putws(L"* DRY-RUN MODE ENABLE! *");
_putws(L"* NO PATCH WILL BE APPLIED! *");
_putws(L"*******************************************************");
} else {
// save private key if not given
if (rsa_privkey_filepath.empty()) {
cipher.export_private_key_file(u8"RegPrivateKey.pem");
}
// detecting backups
if (solution0.is_valid()) {
detect_backup(libcc_filepath);
}
// make backup
if (solution0.is_valid()) {
make_backup(libcc_filepath);
}
// make patch
// no way to go back from here :-)
if (solution0.is_valid()) {
solution0->make_patch(cipher);
}
// print new key file path
if (rsa_privkey_filepath.empty()) {
wprintf_s(L"[*] New RSA-2048 private key has been saved to\n");
wprintf_s(L" %s\n", (std::filesystem::current_path() / L"RegPrivateKey.pem").c_str());
wprintf_s(L"\n");
}
_putws(L"");
_putws(L"*******************************************************");
_putws(L"* PATCH HAS BEEN DONE SUCCESSFULLY! *");
_putws(L"* HAVE FUN AND ENJOY~ *");
_putws(L"*******************************************************");
}
return 0;
} catch (nkg::exception& e) {
wprintf_s(L"[-] %s:%d ->\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.source_file()).c_str(), e.source_line());
wprintf_s(L" %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.custom_message()).c_str());
if (e.error_code_exists()) {
wprintf_s(L" %s (0x%zx)\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.error_string()).c_str(), e.error_code());
}
for (auto& hint : e.hints()) {
wprintf_s(L" HINT: %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(hint).c_str());
}
return -1;
}
} else {
help();
return -1;
}
}
#undef NKG_CURRENT_SOURCE_LINE
#undef NKG_CURRENT_SOURCE_FILE