首次提交

This commit is contained in:
xiaochou164 2023-08-12 17:14:31 +08:00
parent f2e13a2a84
commit bd8ca5821d
114 changed files with 13016 additions and 1 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

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

@ -0,0 +1,33 @@
#include "navicat_serial_generator.hpp"
#include <iostream>
#include "exceptions/operation_canceled_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\CollectInformation.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
[[nodiscard]]
navicat_serial_generator CollectInformationNormal(int procution_type, int language, int version) {
navicat_serial_generator sn_generator;
sn_generator.set_software_type(static_cast<navicat_software_type>(procution_type));
sn_generator.set_software_language(static_cast<navicat_software_language>(language));
sn_generator.set_software_version(version);
return sn_generator;
}
[[nodiscard]]
navicat_serial_generator CollectInformationAdvanced(std::uint8_t procution_type, std::uint8_t lang1, std::uint8_t lang2, int version) {
navicat_serial_generator sn_generator;
sn_generator.set_software_type(procution_type);
sn_generator.set_software_language(lang1, lang2);
sn_generator.set_software_version(version);
return sn_generator;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -0,0 +1,201 @@
#include "exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#include "exceptions/win32_exception.hpp"
#include "resource_wrapper.hpp"
#include "resource_traits/win32/file_handle.hpp"
#include "cp_converter.hpp"
#include "base64_rfc4648.hpp"
#include "navicat_serial_generator.hpp"
#include "rsa_cipher.hpp"
#include <iostream>
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\GenerateLicense.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
std::wstring GenerateLicenseText(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator, std::wstring username,
std::wstring organization, std::wstring b64_request_code) {
std::string u8_username;
std::string u8_organization;
std::vector<std::uint8_t> request_code;
std::string u8_request_info;
std::string u8_response_info;
std::vector<std::uint8_t> response_code;
std::wstring b64_response_code;
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
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();
}
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//
// begin to parse
//
json.Parse(u8_request_info.c_str());
//
// remove "Platform" info
//
json.RemoveMember(u8"P");
//
// set "Name" info
//
N_Key.SetString(u8"N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
//
// set "Organization" info
//
O_Key.SetString(u8"O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
//
// set "Time" info
//
T_Key.SetString(u8"T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
//
// add "Name", "Organization" and "Time"
//
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
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));
return b64_response_code;
}
void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::string utf8SerialNumber = sn_generator.serial_number();
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
std::string u8_response_info;
std::vector<std::uint8_t> response_code;
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
}
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
}
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::Value K_Key;
rapidjson::Value K_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Parse("{}");
K_Key.SetString("K", 1);
K_Value.SetString(utf8SerialNumber.c_str(), static_cast<rapidjson::SizeType>(utf8SerialNumber.length()));
N_Key.SetString("N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
O_Key.SetString("O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
json.AddMember(K_Key, K_Value, json.GetAllocator());
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
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 (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::wcout << L"[+] license_file has been generated." << std::endl;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

Binary file not shown.

View File

@ -0,0 +1,107 @@

// NavicatCracker.cpp: 定义应用程序的类行为。
//
#include "pch.h"
#include "framework.h"
#include "NavicatCracker.h"
#include "NavicatCrackerDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CNavicatCrackerApp
BEGIN_MESSAGE_MAP(CNavicatCrackerApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CNavicatCrackerApp 构造
CNavicatCrackerApp::CNavicatCrackerApp()
{
// 支持重新启动管理器
m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART;
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的 CNavicatCrackerApp 对象
CNavicatCrackerApp theApp;
// CNavicatCrackerApp 初始化
BOOL CNavicatCrackerApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。 否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// 创建 shell 管理器,以防对话框包含
// 任何 shell 树视图控件或 shell 列表视图控件。
CShellManager *pShellManager = new CShellManager;
// 激活“Windows Native”视觉管理器以便在 MFC 控件中启用主题
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
CNavicatCrackerDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此放置处理何时用
// “确定”来关闭对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用
// “取消”来关闭对话框的代码
}
else if (nResponse == -1)
{
TRACE(traceAppMsg, 0, "警告: 对话框创建失败,应用程序将意外终止。\n");
TRACE(traceAppMsg, 0, "警告: 如果您在对话框上使用 MFC 控件,则无法 #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS。\n");
}
// 删除上面创建的 shell 管理器。
if (pShellManager != nullptr)
{
delete pShellManager;
}
#if !defined(_AFXDLL) && !defined(_AFX_NO_MFC_CONTROLS_IN_DIALOGS)
ControlBarCleanUp();
#endif
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}

View File

@ -0,0 +1,32 @@

// NavicatCracker.h: PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含 'pch.h' 以生成 PCH"
#endif
#include "resource.h" // 主符号
// CNavicatCrackerApp:
// 有关此类的实现,请参阅 NavicatCracker.cpp
//
class CNavicatCrackerApp : public CWinApp
{
public:
CNavicatCrackerApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CNavicatCrackerApp theApp;

Binary file not shown.

View File

@ -0,0 +1,415 @@
<?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>17.0</VCProjectVersion>
<ProjectGuid>{759AFCD1-1227-4070-B12E-4658EC908FE3}</ProjectGuid>
<Keyword>MFCProj</Keyword>
<RootNamespace>NavicatCracker</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>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<UseOfMfc>Static</UseOfMfc>
</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)\New</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>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<IgnoreSpecificDefaultLibraries>uafxcw.lib;LIBCMT.lib</IgnoreSpecificDefaultLibraries>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
<AdditionalDependencies>uafxcw.lib;LIBCMT.lib</AdditionalDependencies>
<IgnoreAllDefaultLibraries>
</IgnoreAllDefaultLibraries>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0804</Culture>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<IgnoreSpecificDefaultLibraries>uafxcw.lib;LIBCMT.lib</IgnoreSpecificDefaultLibraries>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
<AdditionalDependencies>uafxcw.lib;LIBCMT.lib</AdditionalDependencies>
<IgnoreAllDefaultLibraries>
</IgnoreAllDefaultLibraries>
<UACExecutionLevel>RequireAdministrator</UACExecutionLevel>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0804</Culture>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_WINDOWS;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<IgnoreSpecificDefaultLibraries>uafxcw.lib;LIBCMT.lib</IgnoreSpecificDefaultLibraries>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
<AdditionalDependencies>uafxcw.lib;LIBCMT.lib</AdditionalDependencies>
<IgnoreAllDefaultLibraries>
</IgnoreAllDefaultLibraries>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0804</Culture>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_WINDOWS;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<LanguageStandard>stdcpp17</LanguageStandard>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<AdditionalIncludeDirectories>$(MSBuildThisFileDirectory);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<Optimization>MaxSpeed</Optimization>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<IgnoreSpecificDefaultLibraries>uafxcw.lib;LIBCMT.lib</IgnoreSpecificDefaultLibraries>
<AdditionalLibraryDirectories>
</AdditionalLibraryDirectories>
<AdditionalDependencies>uafxcw.lib;LIBCMT.lib</AdditionalDependencies>
<IgnoreAllDefaultLibraries>
</IgnoreAllDefaultLibraries>
</Link>
<Midl>
<MkTypLibCompatible>false</MkTypLibCompatible>
<ValidateAllParameters>true</ValidateAllParameters>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</Midl>
<ResourceCompile>
<Culture>0x0804</Culture>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="NavicatCracker.cpp">
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<ClCompile Include="NavicatCrackerDlg.cpp">
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<ClCompile Include="i386_emulator.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="image_interpreter.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="keystone_assembler.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<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>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<ClCompile Include="amd64_emulator.cpp">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.generic.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<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>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="base32_rfc4648.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="base64_rfc4648.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="CollectInformation.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="GenerateLicense.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="navicat_serial_generator.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">MultiThreaded</RuntimeLibrary>
<RuntimeLibrary Condition="'$(Configuration)|$(Platform)'=='Release|x64'">MultiThreaded</RuntimeLibrary>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="framework.h" />
<ClInclude Include="NavicatCracker.h" />
<ClInclude Include="NavicatCrackerDlg.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="targetver.h" />
<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>
<ClInclude Include="base32_rfc4648.hpp" />
<ClInclude Include="base64_rfc4648.hpp" />
<ClInclude Include="navicat_serial_generator.hpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="NavicatCracker.rc" />
</ItemGroup>
<ItemGroup>
<None Include="res\NavicatCracker.rc2" />
</ItemGroup>
<ItemGroup>
<Image Include="res\610.png" />
<Image Include="res\620.png" />
<Image Include="res\bitmap1.bmp" />
<Image Include="res\MAINICON.ico" />
<Image Include="res\NavicatCracker.ico" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,141 @@
<?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>
<ClInclude Include="NavicatCracker.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="NavicatCrackerDlg.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="framework.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="targetver.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Resource.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="pch.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="amd64_emulator.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="base32_rfc4648.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="base64_rfc4648.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="i386_emulator.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="image_interpreter.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="keystone_assembler.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution_since.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="patch_solution_since_16.0.7.0.hpp">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="navicat_serial_generator.hpp">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="NavicatCracker.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="NavicatCrackerDlg.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="pch.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="amd64_emulator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="CollectInformation.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="GenerateLicense.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.generic.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.i386.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="i386_emulator.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="image_interpreter.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="keystone_assembler.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="patch_solution_since_16.0.7.0.amd64.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="base32_rfc4648.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="base64_rfc4648.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="navicat_serial_generator.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="NavicatCracker.rc">
<Filter>资源文件</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<None Include="res\NavicatCracker.rc2">
<Filter>资源文件</Filter>
</None>
</ItemGroup>
<ItemGroup>
<Image Include="res\NavicatCracker.ico">
<Filter>资源文件</Filter>
</Image>
<Image Include="res\bitmap1.bmp">
<Filter>资源文件</Filter>
</Image>
<Image Include="res\610.png">
<Filter>资源文件</Filter>
</Image>
<Image Include="res\620.png">
<Filter>资源文件</Filter>
</Image>
<Image Include="res\MAINICON.ico">
<Filter>资源文件</Filter>
</Image>
</ItemGroup>
</Project>

View File

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

View File

@ -0,0 +1,563 @@

// NavicatCrackerDlg.cpp: 实现文件
//
#include "pch.h"
#include "framework.h"
#include "NavicatCracker.h"
#include "NavicatCrackerDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define NKG_CURRENT_SOURCE_FILE() u8".\\Navicat-Cracker\\NavicatCrackerDlg.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
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()) {
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 {
do {
cipher.generate_key(2048);
} while (solution0 && !solution0->check_rsa_privkey(cipher)); // re-generate RSA key if one of `check_rsa_privkey` returns false
}
}
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);
}
}
CNavicatCrackerDlg::CNavicatCrackerDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_NavicatCracker_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CNavicatCrackerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_ActivationCode, m_actcode);
DDX_Control(pDX, IDC_CopyBTN, m_copy);
DDX_Control(pDX, IDC_GenActBTN, m_genact);
DDX_Control(pDX, IDC_GenerateBTN, m_genkey);
DDX_Control(pDX, IDC_InstallPath, m_path);
DDX_Control(pDX, IDC_Key, m_key);
DDX_Control(pDX, IDC_LanguageBox, m_lang);
DDX_Control(pDX, IDC_Organ, m_org);
DDX_Control(pDX, IDC_PatchBTN, m_patch);
DDX_Control(pDX, IDC_InstallPath, m_path);
DDX_Control(pDX, IDC_ProductionBox, m_product);
DDX_Control(pDX, IDC_RequestCode, m_reqcode);
DDX_Control(pDX, IDC_UserName, m_name);
DDX_Control(pDX, IDC_VersionBox, m_ver);
DDX_Control(pDX, IDC_KeyFile, m_keyfile);
DDX_Control(pDX, IDC_OpenKeyBTN, m_open);
DDX_Control(pDX, IDC_CheckKey, m_checkkey);
DDX_Control(pDX, IDC_ADVANCE, m_checkadv);
DDX_Control(pDX, IDC_LangHex1, m_langhex1);
DDX_Control(pDX, IDC_LangHex2, m_langhex2);
DDX_Control(pDX, IDC_ProdHex, m_prodhex);
DDX_Control(pDX, IDC_hosts, m_hosts);
DDX_Control(pDX, IDC_Logo, m_logo);
}
BEGIN_MESSAGE_MAP(CNavicatCrackerDlg, CDialogEx)
ON_BN_CLICKED(IDC_PatchBTN, &CNavicatCrackerDlg::OnClickedPatchbtn)
ON_BN_CLICKED(IDC_GenerateBTN, &CNavicatCrackerDlg::OnClickedGeneratebtn)
ON_BN_CLICKED(IDC_GenActBTN, &CNavicatCrackerDlg::OnClickedGenActbtn)
ON_BN_CLICKED(IDC_CopyBTN, &CNavicatCrackerDlg::OnClickedCopybtn)
ON_BN_CLICKED(IDC_CheckKey, &CNavicatCrackerDlg::OnClickedCheckKey)
ON_BN_CLICKED(IDC_OpenKeyBTN, &CNavicatCrackerDlg::OnClickedOpenKeybtn)
ON_BN_CLICKED(IDC_OpenPath, &CNavicatCrackerDlg::OnBnClickedOpenpath)
ON_BN_CLICKED(IDC_ADVANCE, &CNavicatCrackerDlg::OnBnClickedAdvance)
ON_BN_CLICKED(IDC_About, &CNavicatCrackerDlg::OnBnClickedAbout)
ON_BN_CLICKED(IDC_hosts, &CNavicatCrackerDlg::OnBnClickedhosts)
END_MESSAGE_MAP()
// CNavicatCrackerDlg 消息处理程序
BOOL CNavicatCrackerDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
ShowWindow(SW_NORMAL);
// 初始化代码
m_ver.SetCurSel(0);
m_product.SetCurSel(1);
m_lang.SetCurSel(1);
m_path.SetWindowTextW(defaultpath);
m_name.SetWindowTextW(username);
m_org.SetWindowTextW(organization);
m_keyfile.SetWindowTextW(keyfile);
// setup logo png
CBitmap bitmap_logo;
CPngImage png_image;
png_image.Load(IDB_PNG1, nullptr);
bitmap_logo.Attach(png_image.Detach());
m_logo.SetBitmap(bitmap_logo);
m_hosts.SetCheck(TRUE);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CNavicatCrackerDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CNavicatCrackerDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CNavicatCrackerDlg::OnClickedPatchbtn()
{
CString pathData;
m_path.GetWindowTextW(pathData);
// patcher
navicat_install_path = pathData.GetString();
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())));
}
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()) {
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Try to open libcc.dll ... NOT FOUND!");
}
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()));
}
// find patch and decide which solution will be applied
if (solution0.is_valid()) {
auto patch_found = solution0->find_patch();
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
if (m_checkkey.GetCheck()) {
CString cs_keypath{};
m_keyfile.GetWindowTextW(cs_keypath);
rsa_privkey_filepath = cs_keypath.GetString();
if (!PathFileExists(rsa_privkey_filepath.c_str())) {
m_checkkey.SetCheck(FALSE);
OnClickedCheckKey();
rsa_privkey_filepath.clear();
}
}
load_rsa_privkey(cipher, rsa_privkey_filepath, solution0.get());
// 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);
}
// patch hosts
if (m_hosts.GetCheck()) {
LPCWSTR lpshosts = _T("C:\\Windows\\System32\\drivers\\etc\\hosts");
SetFileAttributesW(lpshosts, GetFileAttributes(lpshosts) & ~FILE_ATTRIBUTE_READONLY);
CStdioFile hosts;
if (hosts.Open(lpshosts, CFile::modeWrite)) {
hosts.SeekToEnd();
hosts.WriteString(_T("127.0.0.1\tactivate.navicat.com\n"));
}
else {
AfxMessageBox(L"Can't modify HOSTS file!\nPlease check your permission!", MB_ICONSTOP);
}
hosts.Close();
}
// private key export
if (!m_checkkey.GetCheck()) {
if(AfxMessageBox(L"Patch Success Applied to libcc.dll!\nDO You Want to Export Private Key?", MB_ICONINFORMATION | MB_YESNOCANCEL) == IDYES){
cipher.export_private_key_file(u8"Navicat_2048bit_rsa_private_key.pem");
}
}
else {
AfxMessageBox(L"Patch Success Applied to libcc.dll!\n", MB_ICONINFORMATION | MB_OK);
}
PATCH = TRUE;
}
catch (nkg::exception& e) {
catched_message.Format(L"[-] %s:%d ->\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.source_file()).c_str(), e.source_line());
catched_message.AppendFormat(L" %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.custom_message()).c_str());
if (e.error_code_exists()) {
catched_message.AppendFormat(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()) {
catched_message.AppendFormat(L" HINT: %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(hint).c_str());
}
AfxMessageBox(catched_message, MB_ICONSTOP);
}
catch (std::exception& e) {
catched_message.Format(L"[-] %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.what()).c_str());
AfxMessageBox(catched_message, MB_ICONSTOP);
}
}
void CNavicatCrackerDlg::OnClickedGeneratebtn()
{
int verData;
CString strData;
verData = 16 - m_ver.GetCurSel();
try {
if (!m_checkadv.GetCheck()) {
int proData = m_product.GetCurSel();
int langData = m_lang.GetCurSel();
lpfnCollectInformation = nkg::CollectInformationNormal;
sn_generator = lpfnCollectInformation(proData, langData, verData);
}
else {
CString temp;
std::uint8_t prod, lang1, lang2;
m_prodhex.GetWindowTextW(temp);
prod = static_cast<std::uint8_t>(std::stoul(temp.GetString(), nullptr, 16));
m_langhex1.GetWindowTextW(temp);
lang1 = static_cast<std::uint8_t>(std::stoul(temp.GetString(), nullptr, 16));
m_langhex2.GetWindowTextW(temp);
lang2 = static_cast<std::uint8_t>(std::stoul(temp.GetString(), nullptr, 16));
sn_generator = nkg::CollectInformationAdvanced(prod, lang1, lang2, verData);
}
sn_generator.generate();
m_key.SetWindowTextW(nkg::cp_converter<CP_UTF8, -1>::convert(sn_generator.serial_number_formatted()).c_str());
KEYGEN = TRUE;
}
catch (nkg::exception& e) {
catched_message.Format(L"[-] %s:%d ->\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.source_file()).c_str(), e.source_line());
catched_message.AppendFormat(L" %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.custom_message()).c_str());
if (e.error_code_exists()) {
catched_message.AppendFormat(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()) {
catched_message.AppendFormat(L" HINT: %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(hint).c_str());
}
AfxMessageBox(catched_message, MB_ICONSTOP);
}
catch (std::exception& e) {
catched_message.Format(L"[-] %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.what()).c_str());
if (m_checkadv.GetCheck()) {
catched_message.AppendFormat(L"In ADV mode Production should be 0x00~0xFF.\n");
catched_message.AppendFormat(L"In ADV mode Language(each part) should be 0x00~0xFF.");
}
AfxMessageBox(catched_message, MB_ICONSTOP);
}
catched_message.Empty();
}
void CNavicatCrackerDlg::OnClickedGenActbtn()
{
try {
if (!PATCH) {
if (!m_checkkey.GetCheck()) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Can't Generate Activation Code.")
.push_hint(u8"Please Patch first Or Specified RSA private key.");
}
else {
CString private_path;
m_keyfile.GetWindowTextW(private_path);
cipher.import_private_key_file(nkg::cp_converter<-1, CP_UTF8>::convert(private_path.GetString()));
}
}
if (!KEYGEN) {
throw nkg::exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Can't Generate Activation Code.")
.push_hint(u8"Please Generate a key!");
}
lpfnGenerateLicense = nkg::GenerateLicenseText;
m_name.GetWindowTextW(username);
m_org.GetWindowTextW(organization);
m_reqcode.GetWindowTextW(reqcode);
actcode = lpfnGenerateLicense(cipher, sn_generator, username.GetString(), organization.GetString(), reqcode.GetString()).c_str();
m_actcode.SetWindowTextW(actcode);
}
catch (nkg::exception& e) {
catched_message.Format(L"[-] %s:%d ->\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.source_file()).c_str(), e.source_line());
catched_message.AppendFormat(L" %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.custom_message()).c_str());
if (e.error_code_exists()) {
catched_message.AppendFormat(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()) {
catched_message.AppendFormat(L" HINT: %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(hint).c_str());
}
AfxMessageBox(catched_message, MB_ICONSTOP);
}
catch (std::exception& e) {
catched_message.Format(L"[-] %s\n", nkg::cp_converter<CP_UTF8, -1>::convert(e.what()).c_str());
AfxMessageBox(catched_message, MB_ICONSTOP);
}
catched_message.Empty();
}
void CNavicatCrackerDlg::OnClickedCopybtn()
{
CString source;
m_key.GetWindowTextW(source);
if (OpenClipboard())
{
//防止非ASCII语言复制到剪切板为乱码
int buff_size = source.GetLength();
CStringW strWide = CStringW(source);
int nLen = strWide.GetLength();
HANDLE clipbuffer = ::GlobalAlloc(GMEM_MOVEABLE, (nLen + 1) * 2);
if (!clipbuffer)
{
::CloseClipboard();
return;
}
char* buffer = (char*)::GlobalLock(clipbuffer);
if (buffer != 0) {
memset(buffer, 0, (static_cast<size_t>(nLen) + 1) * 2);
memcpy_s(buffer, nLen * 2, strWide.GetBuffer(0), nLen * 2);
strWide.ReleaseBuffer();
::GlobalUnlock(clipbuffer);
::EmptyClipboard();
::SetClipboardData(CF_UNICODETEXT, clipbuffer);
::CloseClipboard();
}
else {
::CloseClipboard();
return;
}
}
}
void CNavicatCrackerDlg::OnClickedCheckKey()
{
if (m_checkkey.GetCheck()) {
m_keyfile.EnableWindow();
m_open.EnableWindow();
}
else {
m_keyfile.EnableWindow(0);
m_open.EnableWindow(0);
}
}
void CNavicatCrackerDlg::OnClickedOpenKeybtn()
{
CFileDialog openFileDlg(FALSE, L".", L"PrivateKey.pem", OFN_HIDEREADONLY | OFN_READONLY, L"Private Key (*.pem)|*.pem||", NULL);
INT_PTR result = openFileDlg.DoModal();
if (result == IDOK) {
m_keyfile.SetWindowTextW(openFileDlg.GetPathName());
}
// 失焦解决方法:"https://kira-96.github.io/" 一些基本没什么用的MFC技巧
::SetForegroundWindow(::GetDesktopWindow());
this->SetForegroundWindow();
}
void CNavicatCrackerDlg::OnBnClickedOpenpath()
{
CFolderPickerDialog openFolderDlg;
openFolderDlg.m_ofn.lpstrTitle = L"Choose The Navicat Installation Path:";
openFolderDlg.m_ofn.lpstrInitialDir = L".";
INT_PTR result = openFolderDlg.DoModal();
if (result == IDOK) {
m_path.SetWindowTextW(openFolderDlg.GetPathName());
}
::SetForegroundWindow(::GetDesktopWindow());
this->SetForegroundWindow();
}
void CNavicatCrackerDlg::OnBnClickedAdvance()
{
if (m_checkadv.GetCheck()) {
m_lang.ShowWindow(SW_HIDE);
m_product.ShowWindow(SW_HIDE);
m_prodhex.ShowWindow(SW_SHOW);
m_langhex1.ShowWindow(SW_SHOW);
m_langhex2.ShowWindow(SW_SHOW);
}
else {
m_lang.ShowWindow(SW_SHOW);
m_product.ShowWindow(SW_SHOW);
m_prodhex.ShowWindow(SW_HIDE);
m_langhex1.ShowWindow(SW_HIDE);
m_langhex2.ShowWindow(SW_HIDE);
}
}
void CNavicatCrackerDlg::OnBnClickedAbout()
{
AfxMessageBox(L"Author : tgMrZ\nBased on DoubleSine's work\n\n\nDoubleSine yyds!!!", MB_OK | MB_ICONQUESTION);
}
void CNavicatCrackerDlg::OnBnClickedhosts()
{
if (m_hosts.GetCheck()) {
AfxMessageBox(L"Please make sure you have permission to modify HOSTS file!");
}
}

View File

@ -0,0 +1,126 @@

// NavicatCrackerDlg.h: 头文件
//
#pragma once
#include <filesystem>
#include <stdio.h>
#include <windows.h>
#include <fmt/format.h>
#include <optional>
#include <functional>
#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"
#include "base64_rfc4648.hpp"
#include "navicat_serial_generator.hpp"
namespace nkg {
using fnCollectInformation = std::function<navicat_serial_generator(int procution_type, int language, int version)>;
using fnGenerateLicense = std::function<std::wstring(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator, std::wstring _username,
std::wstring _organization, std::wstring _redcode)>;
navicat_serial_generator CollectInformationNormal(int procution_type, int language, int version);
navicat_serial_generator CollectInformationAdvanced(std::uint8_t procution_type, std::uint8_t lang1, std::uint8_t lang2, int version);
std::wstring GenerateLicenseText(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator, std::wstring _username,
std::wstring _organization, std::wstring _redcode);
//void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator);
}
// CNavicatCrackerDlg 对话框
class CNavicatCrackerDlg : public CDialogEx
{
// 构造
public:
CNavicatCrackerDlg(CWnd* pParent = nullptr); // 标准构造函数
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_NavicatCracker_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
public:
std::filesystem::path navicat_install_path;
std::filesystem::path rsa_privkey_filepath;
nkg::rsa_cipher cipher;
nkg::navicat_serial_generator sn_generator;
nkg::fnCollectInformation lpfnCollectInformation;
nkg::fnGenerateLicense lpfnGenerateLicense;
CString catched_message{ };
CString defaultpath{ "C:\\Program Files\\PremiumSoft\\Navicat Premium 16" };
CString username{ "tgMrZ" };
CString organization{ "DoubleSine" };
CString reqcode;
CString actcode;
CString keyfile{ "Navicat_2048bit_rsa_private_key.pem" };
BOOL PATCH{ FALSE }; // patched
BOOL KEYGEN{ FALSE }; // keygened
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
//afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CEdit m_actcode;
CButton m_copy;
CButton m_genact;
CButton m_genkey;
CEdit m_key;
CComboBox m_lang;
CEdit m_org;
CButton m_patch;
CEdit m_path;
CComboBox m_product;
CEdit m_reqcode;
CEdit m_name;
CComboBox m_ver;
afx_msg void OnClickedPatchbtn();
afx_msg void OnClickedGeneratebtn();
afx_msg void OnClickedGenActbtn();
afx_msg void OnClickedCopybtn();
CEdit m_keyfile;
CBitmapButton m_open;
CButton m_checkkey;
CButton m_checkadv;
CEdit m_langhex1;
CEdit m_langhex2;
CEdit m_prodhex;
CButton m_hosts;
afx_msg void OnClickedCheckKey();
afx_msg void OnClickedOpenKeybtn();
afx_msg void OnBnClickedOpenpath();
afx_msg void OnBnClickedAdvance();
afx_msg void OnBnClickedAbout();
afx_msg void OnBnClickedhosts();
CStatic m_logo;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,49 @@
#pragma once
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // 从 Windows 头中排除极少使用的资料
#endif
#include "targetver.h"
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 构造函数将是显式的
// 关闭 MFC 的一些常见且经常可放心忽略的隐藏警告消息
#define _AFX_ALL_WARNINGS
#include <afxwin.h> // MFC 核心组件和标准组件
#include <afxext.h> // MFC 扩展
#include <afxdisp.h> // MFC 自动化类
#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h> // MFC 对 Internet Explorer 4 公共控件的支持
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC 对 Windows 公共控件的支持
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxcontrolbars.h> // MFC 支持功能区和控制条
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif

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

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,19 @@
#pragma once
#include "rsa_cipher.hpp"
namespace nkg {
class patch_solution {
public:
[[nodiscard]]
virtual bool find_patch() = 0;
[[nodiscard]]
virtual bool check_rsa_privkey(const rsa_cipher& cipher) = 0;
virtual void make_patch(const rsa_cipher& cipher) = 0;
virtual ~patch_solution() = default;
};
}

View File

@ -0,0 +1,9 @@
#pragma once
#include "patch_solution.hpp"
namespace nkg {
template<int major_ver0, int major_ver1, int minor_ver0, int minor_ver1>
class patch_solution_since;
}

View File

@ -0,0 +1,608 @@
#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;
}
catch (std::exception&) {
wprintf_s(L"STD EXCEPTION!");
}
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

@ -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

@ -0,0 +1,35 @@
#pragma once
#include "patch_solution_since.hpp"
#include "image_interpreter.hpp"
#include <any>
#include <string>
#include <map>
namespace nkg {
template<>
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;
std::string _build_encoded_key(const rsa_cipher& cipher);
public:
patch_solution_since(image_interpreter& libcc_interpreter);
[[nodiscard]]
virtual bool find_patch() override;
[[nodiscard]]
virtual bool check_rsa_privkey(const rsa_cipher& cipher) override;
virtual void make_patch(const rsa_cipher& cipher) 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");
}
}

5
Navicat-Cracker/pch.cpp Normal file
View File

@ -0,0 +1,5 @@
// pch.cpp: 与预编译标头对应的源文件
#include "pch.h"
// 当使用预编译的头时,需要使用此源文件,编译才能成功。

13
Navicat-Cracker/pch.h Normal file
View File

@ -0,0 +1,13 @@
// pch.h: 这是预编译标头文件。
// 下方列出的文件仅编译一次,提高了将来生成的生成性能。
// 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。
// 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。
// 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。
#ifndef PCH_H
#define PCH_H
// 添加要在此处预编译的标头
#include "framework.h"
#endif //PCH_H

BIN
Navicat-Cracker/res/620.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

View File

@ -0,0 +1,46 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ 生成的包含文件。
// 供 NavicatCracker.rc 使用
//
#define IDM_ABOUTBOX 0x0010
#define IDD_ABOUTBOX 100
#define IDS_ABOUTBOX 101
#define IDD_NavicatCracker_DIALOG 102
#define IDB_PNG1 134
#define IDI_ICON1 135
#define IDR_MAINFRAME 135
#define IDC_InstallPath 1000
#define IDC_PatchBTN 1001
#define IDC_VersionBox 1002
#define IDC_ProductionBox 1003
#define IDC_LanguageBox 1004
#define IDC_Key 1005
#define IDC_GenerateBTN 1006
#define IDC_CopyBTN 1007
#define IDC_UserName 1008
#define IDC_Organ 1009
#define IDC_RequestCode 1011
#define IDC_ActivationCode 1012
#define IDC_GenActBTN 1013
#define IDC_CheckKey 1015
#define IDC_KeyFile 1016
#define IDC_OpenKeyBTN 1017
#define IDC_OpenPath 1018
#define IDC_ADVANCE 1019
#define IDC_ProdHex 1020
#define IDC_LangHex1 1021
#define IDC_LangHex2 1022
#define IDC_About 1024
#define IDC_hosts 1025
#define IDC_Logo 1026
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 136
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1029
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@ -0,0 +1,8 @@
#pragma once
// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。
//如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h
// 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。
#include <SDKDDKVer.h>

View File

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

34
README.zh-CN.md Normal file
View File

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

59
common/common.vcxitems Normal file
View File

@ -0,0 +1,59 @@
<?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">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="$(MSBuildThisFileDirectory)rsa_cipher.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
</ClCompile>
</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

86
common/exception.hpp Normal file
View File

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

View File

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

View File

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

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,20 @@
#include "openssl_exception.hpp"
#include <mutex>
#pragma comment(lib, "libcrypto")
#pragma comment(lib, "crypt32") // required by libcrypto.lib
#pragma comment(lib, "ws2_32") // required by libcrypto.lib
namespace nkg::exceptions {
openssl_exception::openssl_exception(std::string_view file, int line, error_code_t openssl_error_code, std::string_view message) noexcept :
::nkg::exception(file, line, message)
{
static std::once_flag onceflag_load_crypto_strings;
std::call_once(onceflag_load_crypto_strings, []() { ERR_load_crypto_strings(); });
m_error_code = openssl_error_code;
m_error_string = ERR_reason_error_string(m_error_code);
}
}

View File

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

View File

@ -0,0 +1,10 @@
#pragma once
#include "../exception.hpp"
namespace nkg::exceptions {
class operation_canceled_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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

245
common/resource_wrapper.hpp Normal file
View File

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

625
common/rsa_cipher.cpp Normal file
View File

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

161
common/rsa_cipher.hpp Normal file
View File

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

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

60
doc/how-to-build.md Normal file
View File

@ -0,0 +1,60 @@
# navicat-keygen for windows - How to build?
[中文版](how-to-build.zh-CN.md)
## 1. Prerequisites
1. Please make sure that you have __Visual Studio 2022__ or the higher. Because this is a VS2022 project.
2. Please make sure you have installed `vcpkg` and the following libraries:
* `fmt:x64-windows-static`
* `fmt:x86-windows-static`
* `openssl:x64-windows-static`
* `openssl:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `unicorn:x64-windows-static`
* `unicorn:x86-windows-static`
is installed.
You can install them by:
```console
$ vcpkg install fmt:x64-windows-static
$ vcpkg install fmt:x86-windows-static
$ vcpkg install openssl:x64-windows-static
$ vcpkg install openssl:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install unicorn:x64-windows-static
$ vcpkg install unicorn:x86-windows-static
```
3. Your `vcpkg` has been integrated into your __Visual Studio__, which means you have run
```console
$ vcpkg integrate install
```
successfully.
## 2. Build
1. Open this project in __Visual Studio__.
2. Select `Release` configuration.
3. Select `Win32` to build keygen/patcher for 32-bits Navicat.
Or select `x64` to build keygen/patcher for 64-bits Navicat.
4. Select __Build > Build Solution__.
You will see executable files in `bin/` directory.

54
doc/how-to-build.zh-CN.md Normal file
View File

@ -0,0 +1,54 @@
# navicat-keygen for windows - 如何编译?
## 1. 前提条件
1. 请确保你有 __Visual Studio 2022__ 或者更高版本。因为这是一个VS2022项目。
2. 请确保你安装了 `vcpkg` 以及下面几个库:
* `fmt:x64-windows-static`
* `fmt:x86-windows-static`
* `openssl:x64-windows-static`
* `openssl:x86-windows-static`
* `rapidjson:x64-windows-static`
* `rapidjson:x86-windows-static`
* `keystone:x64-windows-static`
* `keystone:x86-windows-static`
* `unicorn:x64-windows-static`
* `unicorn:x86-windows-static`
你可以通过下面的命令来安装它们:
```console
$ vcpkg install fmt:x64-windows-static
$ vcpkg install fmt:x86-windows-static
$ vcpkg install openssl:x64-windows-static
$ vcpkg install openssl:x86-windows-static
$ vcpkg install rapidjson:x64-windows-static
$ vcpkg install rapidjson:x86-windows-static
$ vcpkg install keystone:x64-windows-static
$ vcpkg install keystone:x86-windows-static
$ vcpkg install unicorn:x64-windows-static
$ vcpkg install unicorn:x86-windows-static
```
3. 你的 `vcpkg` 已经和你的 __Visual Studio__ 集成了,即你曾成功运行了:
```console
$ vcpkg integrate install
```
## 2. 编译
1. 在 __Visual Studio__ 打开这个项目。
2. 选择 `Release` 配置。
3. 选择 `Win32` 来生成供32位Navicat使用的keygen/patcher。
或者选择 `x64` 来生成供64位Navicat使用的keygen/patcher。
4. 选择 __生成 > 生成解决方案__
生成完成后,你会在 `bin/` 文件夹下看到编译后的keygen/patcher。

196
doc/how-to-use.md Normal file
View File

@ -0,0 +1,196 @@
# navicat-keygen for windows - How to use?
[中文版](how-to-use.windows.zh-CN.md)
1. Use `navicat-patcher.exe` to replace __Navicat Activation Public Key__ that is stored in `libcc.dll`.
```
navicat-patcher.exe [-dry-run] <Navicat Install Path> [RSA-2048 PEM File Path]
```
* `[-dry-run]` Run patcher without applying any patches.
__This parameter is optional.__
* `<Navicat Install Path>`: The full path to Navicat installation folder.
__This parameter must be specified.__
* `[RSA-2048 PEM File Path]`: The full path or relative path to a RSA-2048 private key file.
__This parameter is optional.__ If not specified, `navicat-patcher.exe` will generate a new RSA-2048 private key file `RegPrivateKey.pem` at current directory.
__Example: (in cmd.exe)__
```
navicat-patcher.exe "C:\Program Files\PremiumSoft\Navicat Premium 16"
```
It has been tested on __Navicat Premium 16.0.7 English version__. The following is an example of output.
```
***************************************************
* navicat-patcher by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[+] Try to open libcc.dll ... OK!
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_vtable = 0x00000001837759f0
[*] patch_solution_since<16, 0, 7, 0>: m_va_CSRegistrationInfoFetcher_WIN_GenerateRegistrationKey = 0x0000000181fa52d0
[*] patch_solution_since<16, 0, 7, 0>: m_va_iat_entry_malloc = 0x0000000183439bd0
[+] patch_solution_since<16, 0, 7, 0>: official encoded key is found.
[*] Generating new RSA private key, it may take a long time...
[*] Your RSA private key:
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAvxaFFjTE6hi80nhjgfFMM3yPer122OIWIbbumFIuAOcCF6D3
PnRHBdP9IqB99K6Nv6vKK3Jf0Y+dc5ETrg0l0AHYq+dTFTiWusHuRMx6xFjWzO96
7mFmJq6P28dUucKnr6yG1TQeZaq+mHh2DNEnNEYgV7cLVT1unUmMOL/PBh/eCcaJ
8hQNTQafQQknzCnAKC89v33y+rKInJNy9B+zSB0BGCz+eS8MKf6zc78JMSOnF2uj
NK+QEwaYw8lAbJve1F+rCQS0mbm0QvHhZYZrblVHI5l/8LkX5qBtKw7duUhXHxmO
fQieF23bBk9HDp5uQUGsdbKX6ZWitn/h926xyQIDAQABAoIBAQCHXxDRdni5zuSV
xivYdnUhVHDg5zA23ZQINmw5BJ8KjJzy2FnPqNhXzKJb0Y7ptG8/BhinRtOSxkcp
A/IJL89F2MkCn1JAimJd091UZ/fg+X7SmCVikyWm6auIa2IeZ0QcNAEhMVcHdzqn
EU+wLMu1QKjQ+x/QN0ERtHTeDyQ+lUNB+bvAjx3LHN9Zh8weVBHHtwDoyyZDdJPw
NWgpgcW+uYzlT66uh7LPPaRsEZgAkPIkhzZnwmugXdhlWxtYHKTEfe5gCqubQICc
I/x1yBP1EZFm6qBQD4/49775ZbXwxgaWvBXG+Aah9x8JYtVUS4MgrAiC4a8NQqFp
nwKVjUIBAoGBAOWsj9GGb2KYbfLzJNRrSxhs4TUBfpHteKSm2pL92NAbIOjssNhL
hLY3gBFX2RnYmoGD6YT84JNykuAictgAd5GwvLIbaVF9l7MQn8APRbe2CzQ+/494
9hpn33MZOBNd3I+a5+2qoFbXI04loyYDJkkeOqbwZzJjs7k9HmZMNwY5AoGBANT9
tRFWFDvA0pPgGoHhzlsAUAmrbSfCPkhrRXpE9fgl3VnV+NRtjCf9NhJt0uaIokZ5
oSf+jClcwU8N4EvGxMBaCHTqBzgc4dLPWpMAhPoMjjv1Oyug2iBcuTasHVP+Jdgq
CaNzpXOuq4upaaNrq+QMsI6O9wA/zWhWPmnYQYgRAoGAUk56471noU+65zvXUQB6
UvCB7Hrynt0ZRPg+kDrEPh/atV5NKdY2Yw6UqKJwvOBwzkU1pGDzIiQHGqd9vIa+
Usmhdbp5DakSeitU9IEEnQdyEHEbKJFSsLfUzeyVuesDJbt/rh5dg4Fpt5GpW+/5
Am8A2d6BPP+Z4qJSiJp7hZECgYEAy64TCZEXqEytE1yr/KjDfaK+54BX0j2e8gIj
XtmznqoXE2Hboslfzp4Gp3j+xhbDmEGYK3bw8l0RP1g1tkFOxeNTUvq6DJ8SFVbV
dt54S+bV3eCVxRL9hRUmyXGuWjQgXKdWsEhXYFkZE2Xe77h3mI3KCYoOCt74v146
MV3szQECgYEAozTO7Wuum+VMKIY35hmHMjUiYmLl3EXWwMBT2VSsk8Siu0XoH0yd
KoxsLDUBMS8sWKCZhFwU+Fx8UZjfo+xE3H4UTyVsw5EDpB9gSud928gNADwxTKor
3s4jnUzb4XRQ0qN2jXzdNuqXNV1ozeqajbM2oSZqbSnWSs5g6DpIs1Q=
-----END RSA PRIVATE KEY-----
[*] patch_solution_since<16, 0, 7, 0>: Patch has been done.
[*] New RSA-2048 private key has been saved to
C:\Users\DoubleSine\source\repos\navicat-keygen\bin\x64-Release\RegPrivateKey.pem
*******************************************************
* PATCH HAS BEEN DONE SUCCESSFULLY! *
* HAVE FUN AND ENJOY~ *
*******************************************************
```
2. Then use `navicat-keygen.exe` to generate __snKey__ and __Activation Code__
```
navicat-keygen.exe <-bin|-text> [-adv] <RSA-2048 Private Key File>
```
* `<-bin|-text>`: Must be `-bin` or `-text`.
If `-bin` is specified, `navicat-keygen.exe` will finally generate `license_file`. It is used for Navicat old activation method only.
If `-text` is specified, `navicat-keygen.exe` will finally generate a Base64-style string which is __Activation Code__. It is used for Navicat new activation method.
__This parameter must be specified.__
* `[-adv]`: Enable advanced mode.
__This parameter is optional.__ If specified, `navicat-keygen.exe` will ask you input Navicat product ID number, language signature numbers. It is for future use generally.
* `<RSA-2048 Private Key File>`: The full path or relative path to an RSA-2048 private key file. The private key must be in PEM format.
__This parameter must be specified.__
__Example: (in cmd.exe)__
```console
navicat-keygen.exe -text .\RegPrivateKey.pem
```
You will be asked to select Navicat product, language and input major version number. After that an randomly generated __snKey__ will be given.
```
***************************************************
* navicat-keygen by @DoubleLabyrinth *
* version: 16.0.7.0 *
***************************************************
[*] Select Navicat product:
0. DataModeler
1. Premium
2. MySQL
3. PostgreSQL
4. Oracle
5. SQLServer
6. SQLite
7. MariaDB
8. MongoDB
9. ReportViewer
(Input index)> 1
[*] Select product language:
0. English
1. Simplified Chinese
2. Traditional Chinese
3. Japanese
4. Polish
5. Spanish
6. French
7. German
8. Korean
9. Russian
10. Portuguese
(Input index)> 0
[*] Input major version number:
(range: 11 ~ 16, default: 16)> 16
[*] Serial number:
NAVL-GFKA-T5SR-ZFTK
[*] Your name:
```
You can use this __snKey__ to activate your Navicat preliminarily.
Then you will be asked to input `Your name` and `Your organization`. Just set them whatever you want, but not too long.
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
```
After that, you will be asked to input the request code. Now __DO NOT CLOSE KEYGEN__.
3. __Disconnect your network__ and open Navicat. Find and click `Registration`. Fill `Registration Key` by __snKey__ that the keygen gave and click `Activate`.
4. Generally online activation will failed and Navicat will ask you do `Manual Activation`, just choose it.
5. Copy your request code and paste it in the keygen. Input empty line to tell the keygen that your input ends.
```
[*] Your name: Double Sine
[*] Your organization: PremiumSoft CyberTech Ltd.
[*] Input request code (in Base64), input empty line to end:
CpgnfbIJGmAcxCuo/pAb8EeoS0audZn2NNemg6c3NPK/dWgb343IZQrFwoBZY6lpxE4Fq1BoNmCM75P03XpiXQ+hErcvFWk6iQPDCk/d4msf/AoprIqAMpXFoFLkeP0G93UIIEeBsUej8SrxdDgQDM585iPok5fUW+fTDCD1VICr7DBdL3c/69IxeIgiOQSuImdIQiM3/EOfDiFbAJL9vHW5LxFT8jj+8RPXehwPTBphpInmGdzxVZUZJwAGlXt7orrRbzafdeBjz6MnTajTcJP3SS2dBCiR33UScnyxYGEXdzv7+QLScTmCvI7gqg3Z8DMhroKMoHmy1AvC16FKVw==
[*] Request Info:
{"K":"NAVLGFKAT5SRZFTK", "DI":"7D48FCBD093C778879A1", "P":"WIN"}
[*] Response Info:
{"K":"NAVLGFKAT5SRZFTK","DI":"7D48FCBD093C778879A1","N":"Double Sine","O":"PremiumSoft CyberTech Ltd.","T":1644387294}
[*] Activation Code:
vwLGmQIWg/DtzHMcaKCDHAjTcBNbTo2VmNllphUSUMgGjgvL6v82ue+GqXB6M/qn48Rj4D4Joqqisr6UwMSclNmQxOQz4RftEpLtG6KBjDo4LM71qn9R/jWoZV5EoHPQkX5gzhO/D7GammrRGn2MV+zI6dJ4c4SBFNnNyjAeEqNzinrQwjB7lUVTlpHEe/SMrdCsGliPZQ/X+5ASbEsq3D8PZsjysJv98MIJrZvdTdznrRe8JzYP+8sbIPQMIX1UDmdyDpbpSl45N92OhO4htz1kFjUEfnrwY0GMOhdYHv/PfMI7RiQzkRyY7pLvX7muJ4dkA+CmMmwew3gy3MWjig==
```
6. Finally, you will get __Activation Code__ which looks like a Base64 string. Just copy it and paste it in Navicat `Manual Activation` window, then click `Activate`. If nothing wrong, activation should be done successfully.

194
doc/how-to-use.zh-CN.md Normal file
View File

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

BIN
doc/screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 KiB

90
navicat-keygen.sln Normal file
View File

@ -0,0 +1,90 @@

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
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "navicat-merge", "navicat-merge\navicat-merge.vcxproj", "{420139AA-CDEC-4C1B-8111-9A3931B453A9}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MFCCtrl3", "G:\Users\Administrator\source\repos\ConsoleApplication1\MFCCtrl3\MFCCtrl3.vcxproj", "{65953135-8395-4355-9364-0A6EF38B69E5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MFCApplication1", "MFCApplication1\MFCApplication1.vcxproj", "{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NavicatCracker", "Navicat-Cracker\NavicatCracker.vcxproj", "{759AFCD1-1227-4070-B12E-4658EC908FE3}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
common\common.vcxitems*{1b6920eb-e6ed-465f-9600-b5f816752375}*SharedItemsImports = 4
common\common.vcxitems*{420139aa-cdec-4c1b-8111-9a3931b453a9}*SharedItemsImports = 4
common\common.vcxitems*{6d262af4-5dac-4f0c-b3d6-23c9cbea9756}*SharedItemsImports = 4
common\common.vcxitems*{6d81a756-475a-4093-919e-3e9217f662ca}*SharedItemsImports = 9
common\common.vcxitems*{759afcd1-1227-4070-b12e-4658ec908fe3}*SharedItemsImports = 4
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{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
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Debug|x64.ActiveCfg = Debug|x64
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Debug|x64.Build.0 = Debug|x64
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Debug|x86.ActiveCfg = Debug|Win32
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Debug|x86.Build.0 = Debug|Win32
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Release|x64.ActiveCfg = Release|x64
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Release|x64.Build.0 = Release|x64
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Release|x86.ActiveCfg = Release|Win32
{420139AA-CDEC-4C1B-8111-9A3931B453A9}.Release|x86.Build.0 = Release|Win32
{65953135-8395-4355-9364-0A6EF38B69E5}.Debug|x64.ActiveCfg = Debug|x64
{65953135-8395-4355-9364-0A6EF38B69E5}.Debug|x64.Build.0 = Debug|x64
{65953135-8395-4355-9364-0A6EF38B69E5}.Debug|x86.ActiveCfg = Debug|Win32
{65953135-8395-4355-9364-0A6EF38B69E5}.Debug|x86.Build.0 = Debug|Win32
{65953135-8395-4355-9364-0A6EF38B69E5}.Release|x64.ActiveCfg = Release|x64
{65953135-8395-4355-9364-0A6EF38B69E5}.Release|x64.Build.0 = Release|x64
{65953135-8395-4355-9364-0A6EF38B69E5}.Release|x86.ActiveCfg = Release|Win32
{65953135-8395-4355-9364-0A6EF38B69E5}.Release|x86.Build.0 = Release|Win32
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Debug|x64.ActiveCfg = Debug|x64
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Debug|x64.Build.0 = Debug|x64
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Debug|x86.ActiveCfg = Debug|Win32
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Debug|x86.Build.0 = Debug|Win32
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Release|x64.ActiveCfg = Release|x64
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Release|x64.Build.0 = Release|x64
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Release|x86.ActiveCfg = Release|Win32
{4C203474-30A2-4C6E-AEC0-E421FD7B3BA3}.Release|x86.Build.0 = Release|Win32
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Debug|x64.ActiveCfg = Debug|x64
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Debug|x64.Build.0 = Debug|x64
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Debug|x86.ActiveCfg = Debug|Win32
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Debug|x86.Build.0 = Debug|Win32
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Release|x64.ActiveCfg = Release|x64
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Release|x64.Build.0 = Release|x64
{759AFCD1-1227-4070-B12E-4658EC908FE3}.Release|x86.ActiveCfg = Release|Win32
{759AFCD1-1227-4070-B12E-4658EC908FE3}.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

@ -0,0 +1,131 @@
#include "navicat_serial_generator.hpp"
#include <iostream>
#include "exceptions/operation_canceled_exception.hpp"
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\CollectInformation.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
[[nodiscard]]
static int read_int(int min_val, int max_val, std::wstring_view prompt, std::wstring_view error_msg) {
int val;
for (std::wstring s;;) {
std::wcout << prompt;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
}
if (s.empty())
continue;
try {
val = std::stoi(s, nullptr, 0);
if (min_val <= val && val <= max_val) {
return val;
} else {
throw std::invalid_argument(u8"");
}
} catch (std::invalid_argument&) {
std::wcout << error_msg << std::endl;
}
}
}
[[nodiscard]]
static int read_int(int min_val, int max_val, int default_val, std::wstring_view prompt, std::wstring_view error_msg) {
int val;
for (std::wstring s;;) {
std::wcout << prompt;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
}
if (s.empty()) {
return default_val;
}
try {
val = std::stoi(s, nullptr, 0);
if (min_val <= val && val <= max_val) {
return val;
} else {
throw std::invalid_argument(u8"");
}
} catch (std::invalid_argument&) {
std::wcout << error_msg << std::endl;
}
}
}
[[nodiscard]]
navicat_serial_generator CollectInformationNormal() {
navicat_serial_generator sn_generator;
std::wcout << L"[*] Select Navicat product:" << std::endl;
std::wcout << L" 0. DataModeler" << std::endl;
std::wcout << L" 1. Premium" << std::endl;
std::wcout << L" 2. MySQL" << std::endl;
std::wcout << L" 3. PostgreSQL" << std::endl;
std::wcout << L" 4. Oracle" << std::endl;
std::wcout << L" 5. SQLServer" << std::endl;
std::wcout << L" 6. SQLite" << std::endl;
std::wcout << L" 7. MariaDB" << std::endl;
std::wcout << L" 8. MongoDB" << std::endl;
std::wcout << L" 9. ReportViewer" << std::endl;
std::wcout << std::endl;
sn_generator.set_software_type(static_cast<navicat_software_type>(read_int(0, 9, L"(Input index)> ", L"Invalid index.")));
std::wcout << std::endl;
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::wcout << L"[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(11, 16, 16, L"(range: 11 ~ 16, default: 16)> ", L"Invalid number."));
std::wcout << std::endl;
return sn_generator;
}
[[nodiscard]]
navicat_serial_generator CollectInformationAdvanced() {
navicat_serial_generator sn_generator;
std::wcout << L"[*] Navicat Product Signature:" << std::endl;
sn_generator.set_software_type(static_cast<std::uint8_t>(read_int(0x00, 0xff, L"(range: 0x00 ~ 0xFF)> ", L"Invalid number.")));
std::wcout << std::endl;
std::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::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::wcout << L"[*] Input major version number:" << std::endl;
sn_generator.set_software_version(read_int(11, 16, 16, L"(range: 11 ~ 16, default: 16)> ", L"Invalid number."));
std::wcout << std::endl;
return sn_generator;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

@ -0,0 +1,237 @@
#include "exception.hpp"
#include "exceptions/operation_canceled_exception.hpp"
#include "exceptions/win32_exception.hpp"
#include "resource_wrapper.hpp"
#include "resource_traits/win32/file_handle.hpp"
#include "cp_converter.hpp"
#include "base64_rfc4648.hpp"
#include "navicat_serial_generator.hpp"
#include "rsa_cipher.hpp"
#include <iostream>
#include <ctime>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#define NKG_CURRENT_SOURCE_FILE() u8".\\navicat-keygen\\GenerateLicense.cpp"
#define NKG_CURRENT_SOURCE_LINE() __LINE__
namespace nkg {
void GenerateLicenseText(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
std::wstring b64_request_code;
std::vector<std::uint8_t> request_code;
std::string u8_request_info;
std::string u8_response_info;
std::vector<std::uint8_t> response_code;
std::wstring b64_response_code;
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
}
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
}
std::wcout << std::endl;
std::wcout << L"[*] Input request code in Base64: (Input empty line to end)" << std::endl;
while (true) {
std::wstring s;
if (!std::getline(std::wcin, s)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
}
if (s.empty()) {
break;
}
b64_request_code.append(s);
}
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::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;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
//
// begin to parse
//
json.Parse(u8_request_info.c_str());
//
// remove "Platform" info
//
json.RemoveMember(u8"P");
//
// set "Name" info
//
N_Key.SetString(u8"N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
//
// set "Organization" info
//
O_Key.SetString(u8"O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
//
// set "Time" info
//
T_Key.SetString(u8"T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
//
// add "Name", "Organization" and "Time"
//
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
b64_response_code = cp_converter<CP_UTF8, -1>::convert(base64_rfc4648::encode(response_code));
std::wcout << L"[*] Activation Code:" << std::endl;
std::wcout << b64_response_code << std::endl;
std::wcout << std::endl;
}
void GenerateLicenseBinary(const rsa_cipher& cipher, const navicat_serial_generator& sn_generator) {
std::string utf8SerialNumber = sn_generator.serial_number();
std::wstring username;
std::wstring organization;
std::string u8_username;
std::string u8_organization;
std::string u8_response_info;
std::vector<std::uint8_t> response_code;
std::wcout << L"[*] Your name: ";
if (!std::getline(std::wcin, username)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_username = cp_converter<-1, CP_UTF8>::convert(username);
}
std::wcout << L"[*] Your organization: ";
if (!std::getline(std::wcin, organization)) {
throw exceptions::operation_canceled_exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Operation is canceled by user.");
} else {
u8_organization = cp_converter<-1, CP_UTF8>::convert(organization);
}
rapidjson::Document json;
rapidjson::Value N_Key;
rapidjson::Value N_Value;
rapidjson::Value O_Key;
rapidjson::Value O_Value;
rapidjson::Value T_Key;
rapidjson::Value T_Value;
rapidjson::Value K_Key;
rapidjson::Value K_Value;
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Parse("{}");
K_Key.SetString("K", 1);
K_Value.SetString(utf8SerialNumber.c_str(), static_cast<rapidjson::SizeType>(utf8SerialNumber.length()));
N_Key.SetString("N", 1);
N_Value.SetString(u8_username.c_str(), static_cast<rapidjson::SizeType>(u8_username.length()));
O_Key.SetString("O", 1);
O_Value.SetString(u8_organization.c_str(), static_cast<rapidjson::SizeType>(u8_organization.length()));
T_Key.SetString("T", 1);
T_Value.SetUint(static_cast<unsigned int>(std::time(nullptr)));
json.AddMember(K_Key, K_Value, json.GetAllocator());
json.AddMember(N_Key, N_Value, json.GetAllocator());
json.AddMember(O_Key, O_Value, json.GetAllocator());
json.AddMember(T_Key, T_Value, json.GetAllocator());
//
// flush
//
json.Accept(writer);
if (buffer.GetSize() > 240) {
throw exception(NKG_CURRENT_SOURCE_FILE(), NKG_CURRENT_SOURCE_LINE(), u8"Response Info is too long.");
}
u8_response_info.assign(buffer.GetString(), buffer.GetSize());
std::wcout << L"[*] Response Info:" << std::endl;
std::wcout << cp_converter<CP_UTF8, -1>::convert(u8_response_info) << std::endl;
std::wcout << std::endl;
response_code.resize((cipher.bits() + 7) / 8);
response_code.resize(cipher.private_encrypt(u8_response_info.data(), u8_response_info.size(), response_code.data(), RSA_PKCS1_PADDING));
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 (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::wcout << L"[+] license_file has been generated." << std::endl;
}
}
#undef NKG_CURRENT_SOURCE_FILE
#undef NKG_CURRENT_SOURCE_LINE

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

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

View File

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

View File

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

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

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