feat: v2.1.0 核心重构与功能增强

## 架构重构
- 全局变量消除,迁移至 Config/State 对象
- SMB 插件融合(smb/smb2/smbghost/smbinfo)
- 服务探测重构,实现 Nmap 风格 fallback 机制
- 输出系统重构,TXT 实时刷盘 + 双写机制
- i18n 框架升级至 go-i18n

## 性能优化
- 正则表达式预编译
- 内存优化 map[string]struct{}
- 并发指纹匹配
- SOCKS5 连接复用
- 滑动窗口调度 + 自适应线程池

## 新功能
- Web 管理界面
- 多格式 POC 适配(xray/afrog)
- 增强指纹库(3139条)
- Favicon hash 指纹识别
- 插件选择性编译(Build Tags)
- fscan-lab 靶场环境
- 默认端口扩展(62→133)

## 构建系统
- 添加 no_local tag 支持排除本地插件
- 多版本构建:fscan/fscan-nolocal/fscan-web
- CI 添加 snapshot 模式支持仅测试构建

## Bug 修复
- 修复 120+ 个问题,包括 RDP panic、批量扫描漏报、
  JSON 输出格式、Redis 检测、Context 超时等

## 测试增强
- 单元测试覆盖率 74-100%
- 并发安全测试
- 集成测试(Web/端口/服务/SSH/ICMP)
This commit is contained in:
ZacharyZcR
2026-01-11 20:16:23 +08:00
parent 6b13b2e84f
commit 71b92d4408
948 changed files with 92335 additions and 24630 deletions
+3
View File
@@ -0,0 +1,3 @@
*.js linguist-language=Go
*.css linguist-language=Go
*.html linguist-language=Go
+1
View File
@@ -0,0 +1 @@
.idea/
+674
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) <year> <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:
<program> Copyright (C) <year> <name of author>
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>.
+30
View File
@@ -0,0 +1,30 @@
# Golang Remote Desktop Protocol
grdp is a pure Golang implementation of the Microsoft RDP (Remote Desktop Protocol) protocol (**client side authorization only**).
Forked from [icodeface/grdp](https://github.com/icodeface/grdp)
## Status
**The project is under development and not finished yet.**
* [x] Standard RDP Authentication
* [x] SSL Authentication
* [x] NTLMv2 Authentication
* [x] Windows Clipboard
* [ ] RDP Client(ugly)
* [ ] VNC Client(unfinished)
## Example
1. build in example dir on linux or windows
2. start example on port 8088
3. http://localhost:8088
## Take ideas from
* [rdpy](https://github.com/citronneur/rdpy)
* [node-rdpjs](https://github.com/citronneur/node-rdpjs)
* [gordp](https://github.com/Madnikulin50/gordp)
* [ncrack_rdp](https://github.com/nmap/ncrack/blob/master/modules/ncrack_rdp.cc)
* [webRDP](https://github.com/Chorder/webRDP)
+174
View File
@@ -0,0 +1,174 @@
// client.go
package client
import (
"log"
"os"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/pdu"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/rfb"
)
const (
CLIP_OFF = 0
CLIP_IN = 0x1
CLIP_OUT = 0x2
)
const (
TC_RDP = 0
TC_VNC = 1
)
type Control interface {
Login(host, user, passwd string, width, height int) error
KeyUp(sc int, name string)
KeyDown(sc int, name string)
MouseMove(x, y int)
MouseWheel(scroll, x, y int)
MouseUp(button int, x, y int)
MouseDown(button int, x, y int)
On(event string, msg interface{})
Close()
}
func init() {
glog.SetLevel(glog.INFO)
logger := log.New(os.Stdout, "", 0)
glog.SetLogger(logger)
}
type Client struct {
host string
user string
passwd string
ctl Control
tc int
setting *Setting
}
func NewClient(host, user, passwd string, t int, s *Setting) *Client {
if s == nil {
s = NewSetting()
}
c := &Client{
host: host,
user: user,
passwd: passwd,
tc: t,
setting: s,
}
switch t {
case TC_VNC:
c.ctl = newVncClient(s)
default:
c.ctl = newRdpClient(s)
}
s.SetLogLevel()
return c
}
func (c *Client) Login() error {
return c.ctl.Login(c.host, c.user, c.passwd, c.setting.Width, c.setting.Height)
}
func (c *Client) KeyUp(sc int, name string) {
c.ctl.KeyUp(sc, name)
}
func (c *Client) KeyDown(sc int, name string) {
c.ctl.KeyDown(sc, name)
}
func (c *Client) MouseMove(x, y int) {
c.ctl.MouseMove(x, y)
}
func (c *Client) MouseWheel(scroll, x, y int) {
c.ctl.MouseWheel(scroll, x, y)
}
func (c *Client) MouseUp(button, x, y int) {
c.ctl.MouseUp(button, x, y)
}
func (c *Client) MouseDown(button, x, y int) {
c.ctl.MouseDown(button, x, y)
}
func (c *Client) OnError(f func(e error)) {
c.ctl.On("error", f)
}
func (c *Client) OnClose(f func()) {
c.ctl.On("close", f)
}
func (c *Client) OnSuccess(f func()) {
c.ctl.On("success", f)
}
func (c *Client) OnReady(f func()) {
c.ctl.On("ready", f)
}
func (c *Client) OnBitmap(f func([]Bitmap)) {
f1 := func(data interface{}) {
bs := make([]Bitmap, 0, 50)
if c.tc == TC_VNC {
br := data.(*rfb.BitRect)
for _, v := range br.Rects {
b := Bitmap{int(v.Rect.X), int(v.Rect.Y), int(v.Rect.X + v.Rect.Width), int(v.Rect.Y + v.Rect.Height),
int(v.Rect.Width), int(v.Rect.Height),
Bpp(uint16(br.Pf.BitsPerPixel)), false, v.Data}
bs = append(bs, b)
}
} else {
for _, v := range data.([]pdu.BitmapData) {
IsCompress := v.IsCompress()
stream := v.BitmapDataStream
if IsCompress {
stream = bitmapDecompress(&v)
IsCompress = false
}
b := Bitmap{int(v.DestLeft), int(v.DestTop), int(v.DestRight), int(v.DestBottom),
int(v.Width), int(v.Height), Bpp(v.BitsPerPixel), IsCompress, stream}
bs = append(bs, b)
}
}
f(bs)
}
c.ctl.On("bitmap", f1)
}
type Bitmap struct {
DestLeft int `json:"destLeft"`
DestTop int `json:"destTop"`
DestRight int `json:"destRight"`
DestBottom int `json:"destBottom"`
Width int `json:"width"`
Height int `json:"height"`
BitsPerPixel int `json:"bitsPerPixel"`
IsCompress bool `json:"isCompress"`
Data []byte `json:"data"`
}
func Bpp(bp uint16) int {
return int(bp / 8)
}
type Setting struct {
Width int
Height int
Protocol string
LogLevel glog.LEVEL
}
func NewSetting() *Setting {
return &Setting{
Width: 1024,
Height: 768,
LogLevel: glog.INFO,
}
}
func (s *Setting) SetLogLevel() {
glog.SetLevel(s.LogLevel)
}
func (s *Setting) SetRequestedProtocol(p uint32) {}
func (s *Setting) SetClipboard(c int) {}
+156
View File
@@ -0,0 +1,156 @@
package client
import (
"fmt"
"net"
"strings"
"time"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/plugin"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/nla"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/pdu"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/sec"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/tpkt"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/x224"
)
type RdpClient struct {
tpkt *tpkt.TPKT
x224 *x224.X224
mcs *t125.MCSClient
sec *sec.Client
pdu *pdu.Client
channels *plugin.Channels
}
func newRdpClient(s *Setting) *RdpClient {
return &RdpClient{}
}
func bitmapDecompress(bitmap *pdu.BitmapData) []byte {
return core.Decompress(bitmap.BitmapDataStream, int(bitmap.Width), int(bitmap.Height), Bpp(bitmap.BitsPerPixel))
}
func split(user string) (domain string, uname string) {
if strings.Index(user, "\\") != -1 {
t := strings.Split(user, "\\")
domain = t[0]
uname = t[len(t)-1]
} else if strings.Index(user, "/") != -1 {
t := strings.Split(user, "/")
domain = t[0]
uname = t[len(t)-1]
} else {
uname = user
}
return
}
func (c *RdpClient) Login(host, user, pwd string, width, height int) error {
conn, err := net.DialTimeout("tcp", host, 3*time.Second)
if err != nil {
return fmt.Errorf("[dial err] %v", err)
}
domain, user := split(user)
c.tpkt = tpkt.New(core.NewSocketLayer(conn), nla.NewNTLMv2(domain, user, pwd))
c.x224 = x224.New(c.tpkt)
c.mcs = t125.NewMCSClient(c.x224)
c.sec = sec.NewClient(c.mcs)
c.pdu = pdu.NewClient(c.sec)
c.channels = plugin.NewChannels(c.sec)
//c.mcs.SetClientDesktop(uint16(width), uint16(height))
c.sec.SetUser(user)
c.sec.SetPwd(pwd)
c.sec.SetDomain(domain)
c.tpkt.SetFastPathListener(c.sec)
c.sec.SetFastPathListener(c.pdu)
c.sec.SetChannelSender(c.mcs)
c.channels.SetChannelSender(c.sec)
//c.x224.SetRequestedProtocol(x224.PROTOCOL_RDP)
//c.x224.SetRequestedProtocol(x224.PROTOCOL_SSL)
err = c.x224.Connect()
if err != nil {
return fmt.Errorf("[x224 connect err] %v", err)
}
return nil
}
func (c *RdpClient) On(event string, f interface{}) {
c.pdu.On(event, f)
}
func (c *RdpClient) KeyUp(sc int, name string) {
p := &pdu.ScancodeKeyEvent{}
p.KeyCode = uint16(sc)
p.KeyboardFlags |= pdu.KBDFLAGS_RELEASE
c.pdu.SendInputEvents(pdu.INPUT_EVENT_SCANCODE, []pdu.InputEventsInterface{p})
}
func (c *RdpClient) KeyDown(sc int, name string) {
p := &pdu.ScancodeKeyEvent{}
p.KeyCode = uint16(sc)
c.pdu.SendInputEvents(pdu.INPUT_EVENT_SCANCODE, []pdu.InputEventsInterface{p})
}
func (c *RdpClient) MouseMove(x, y int) {
p := &pdu.PointerEvent{}
p.PointerFlags |= pdu.PTRFLAGS_MOVE
p.XPos = uint16(x)
p.YPos = uint16(y)
c.pdu.SendInputEvents(pdu.INPUT_EVENT_MOUSE, []pdu.InputEventsInterface{p})
}
func (c *RdpClient) MouseWheel(scroll, x, y int) {
p := &pdu.PointerEvent{}
p.PointerFlags |= pdu.PTRFLAGS_WHEEL
p.XPos = uint16(x)
p.YPos = uint16(y)
c.pdu.SendInputEvents(pdu.INPUT_EVENT_SCANCODE, []pdu.InputEventsInterface{p})
}
func (c *RdpClient) MouseUp(button int, x, y int) {
p := &pdu.PointerEvent{}
switch button {
case 0:
p.PointerFlags |= pdu.PTRFLAGS_BUTTON1
case 2:
p.PointerFlags |= pdu.PTRFLAGS_BUTTON2
case 1:
p.PointerFlags |= pdu.PTRFLAGS_BUTTON3
default:
p.PointerFlags |= pdu.PTRFLAGS_MOVE
}
p.XPos = uint16(x)
p.YPos = uint16(y)
c.pdu.SendInputEvents(pdu.INPUT_EVENT_MOUSE, []pdu.InputEventsInterface{p})
}
func (c *RdpClient) MouseDown(button int, x, y int) {
p := &pdu.PointerEvent{}
p.PointerFlags |= pdu.PTRFLAGS_DOWN
switch button {
case 0:
p.PointerFlags |= pdu.PTRFLAGS_BUTTON1
case 2:
p.PointerFlags |= pdu.PTRFLAGS_BUTTON2
case 1:
p.PointerFlags |= pdu.PTRFLAGS_BUTTON3
default:
p.PointerFlags |= pdu.PTRFLAGS_MOVE
}
p.XPos = uint16(x)
p.YPos = uint16(y)
c.pdu.SendInputEvents(pdu.INPUT_EVENT_MOUSE, []pdu.InputEventsInterface{p})
}
func (c *RdpClient) Close() {
if c != nil && c.tpkt != nil {
c.tpkt.Close()
}
}
+103
View File
@@ -0,0 +1,103 @@
// rfb.go
package client
import (
"fmt"
"net"
"time"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/rfb"
)
type VncClient struct {
vnc *rfb.RFB
}
func newVncClient(s *Setting) *VncClient {
return &VncClient{}
}
func (c *VncClient) Login(host, user, pwd string, width, height int) error {
conn, err := net.DialTimeout("tcp", host, 3*time.Second)
if err != nil {
return fmt.Errorf("[dial err] %v", err)
}
c.vnc = rfb.NewRFB(rfb.NewRFBConn(conn, pwd))
err = c.vnc.Connect()
if err != nil {
return fmt.Errorf("[vnc connect err] %v", err)
}
return nil
}
func (c *VncClient) On(event string, f interface{}) {
c.vnc.On(event, f)
}
func (c *VncClient) KeyUp(sc int, name string) {
k := &rfb.KeyEvent{}
k.Key = uint32(sc)
c.vnc.SendKeyEvent(k)
}
func (c *VncClient) KeyDown(sc int, name string) {
k := &rfb.KeyEvent{}
k.DownFlag = 1
k.Key = uint32(sc)
c.vnc.SendKeyEvent(k)
}
func (c *VncClient) MouseMove(x, y int) {
p := &rfb.PointerEvent{}
time.Sleep(8 * time.Millisecond)
p.XPos = uint16(x)
p.YPos = uint16(y)
c.vnc.SendPointEvent(p)
}
func (c *VncClient) MouseWheel(scroll, x, y int) {
}
func (c *VncClient) MouseUp(button int, x, y int) {
p := &rfb.PointerEvent{}
switch button {
case 0:
p.Mask = 1
case 2:
p.Mask = 1<<3 - 1
case 1:
p.Mask = 1<<2 - 1
default:
p.Mask = 0
}
p.XPos = uint16(x)
p.YPos = uint16(y)
c.vnc.SendPointEvent(p)
}
func (c *VncClient) MouseDown(button int, x, y int) {
p := &rfb.PointerEvent{}
switch button {
case 0:
p.Mask = 1
case 2:
p.Mask = 1<<3 - 1
case 1:
p.Mask = 1<<2 - 1
default:
p.Mask = 0
}
p.XPos = uint16(x)
p.YPos = uint16(y)
c.MouseMove(x, y)
c.vnc.SendPointEvent(p)
}
func (c *VncClient) Close() {
if c.vnc != nil {
c.vnc.Close()
}
}
+151
View File
@@ -0,0 +1,151 @@
package core
import (
"encoding/binary"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"io"
)
type ReadBytesComplete func(result []byte, err error)
func StartReadBytes(len int, r io.Reader, cb ReadBytesComplete) {
glog.Debug("create len:", len)
b := make([]byte, len)
go func() {
_, err := io.ReadFull(r, b)
//glog.Debug("StartReadBytes Get", n, "Bytes:", hex.EncodeToString(b))
cb(b, err)
}()
}
func ReadBytes(len int, r io.Reader) ([]byte, error) {
b := make([]byte, len)
length, err := io.ReadFull(r, b)
return b[:length], err
}
func ReadByte(r io.Reader) (byte, error) {
b, err := ReadBytes(1, r)
return b[0], err
}
func ReadUInt8(r io.Reader) (uint8, error) {
b, err := ReadBytes(1, r)
if err != nil {
return uint8(0), err
} else {
return uint8(b[0]), err
}
}
func ReadUint16LE(r io.Reader) (uint16, error) {
b := make([]byte, 2)
_, err := io.ReadFull(r, b)
if err != nil {
return 0, nil
}
return binary.LittleEndian.Uint16(b), nil
}
func ReadUint16BE(r io.Reader) (uint16, error) {
b := make([]byte, 2)
_, err := io.ReadFull(r, b)
if err != nil {
return 0, nil
}
return binary.BigEndian.Uint16(b), nil
}
func ReadUInt32LE(r io.Reader) (uint32, error) {
b := make([]byte, 4)
_, err := io.ReadFull(r, b)
if err != nil {
return 0, nil
}
return binary.LittleEndian.Uint32(b), nil
}
func ReadUInt32BE(r io.Reader) (uint32, error) {
b := make([]byte, 4)
_, err := io.ReadFull(r, b)
if err != nil {
return 0, nil
}
return binary.BigEndian.Uint32(b), nil
}
func WriteByte(data byte, w io.Writer) (int, error) {
b := make([]byte, 1)
b[0] = byte(data)
return w.Write(b)
}
func WriteBytes(data []byte, w io.Writer) (int, error) {
return w.Write(data)
}
func WriteUInt8(data uint8, w io.Writer) (int, error) {
b := make([]byte, 1)
b[0] = byte(data)
return w.Write(b)
}
func WriteUInt16BE(data uint16, w io.Writer) (int, error) {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, data)
return w.Write(b)
}
func WriteUInt16LE(data uint16, w io.Writer) (int, error) {
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, data)
return w.Write(b)
}
func WriteUInt32LE(data uint32, w io.Writer) (int, error) {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, data)
return w.Write(b)
}
func WriteUInt32BE(data uint32, w io.Writer) (int, error) {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, data)
return w.Write(b)
}
func PutUint16BE(data uint16) (uint8, uint8) {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, data)
return uint8(b[0]), uint8(b[1])
}
func Uint16BE(d0, d1 uint8) uint16 {
b := make([]byte, 2)
b[0] = d0
b[1] = d1
return binary.BigEndian.Uint16(b)
}
func RGB565ToRGB(data uint16) (r, g, b uint8) {
r = uint8((data & 0xF800) >> 8)
r |= r >> 5
g = uint8((data & 0x07E0) >> 3)
g |= g >> 6
b = uint8((data & 0x001F) << 3)
b |= b >> 5
return
}
func RGB555ToRGB(data uint16) (r, g, b uint8) {
r = uint8((data & 0x7C00) >> 7)
r |= r >> 5
g = uint8((data & 0x03E0) >> 2)
g |= g >> 5
b = uint8((data & 0x001F) << 3)
b |= b >> 5
return
}
File diff suppressed because it is too large Load Diff
+74
View File
@@ -0,0 +1,74 @@
package core
import (
"crypto/rsa"
"math/big"
"github.com/huin/asn1ber"
//"crypto/tls"
"errors"
"github.com/icodeface/tls"
"net"
)
type SocketLayer struct {
conn net.Conn
tlsConn *tls.Conn
}
func NewSocketLayer(conn net.Conn) *SocketLayer {
l := &SocketLayer{
conn: conn,
tlsConn: nil,
}
return l
}
func (s *SocketLayer) Read(b []byte) (n int, err error) {
if s.tlsConn != nil {
return s.tlsConn.Read(b)
}
return s.conn.Read(b)
}
func (s *SocketLayer) Write(b []byte) (n int, err error) {
if s.tlsConn != nil {
return s.tlsConn.Write(b)
}
return s.conn.Write(b)
}
func (s *SocketLayer) Close() error {
if s.tlsConn != nil {
err := s.tlsConn.Close()
if err != nil {
return err
}
}
return s.conn.Close()
}
func (s *SocketLayer) StartTLS() error {
config := &tls.Config{
InsecureSkipVerify: true,
MinVersion: tls.VersionTLS10,
MaxVersion: tls.VersionTLS13,
PreferServerCipherSuites: true,
}
s.tlsConn = tls.Client(s.conn, config)
return s.tlsConn.Handshake()
}
type PublicKey struct {
N *big.Int `asn1:"explicit,tag:0"` // modulus
E int `asn1:"explicit,tag:1"` // public exponent
}
func (s *SocketLayer) TlsPubKey() ([]byte, error) {
if s.tlsConn == nil {
return nil, errors.New("TLS conn does not exist")
}
pub := s.tlsConn.ConnectionState().PeerCertificates[0].PublicKey.(*rsa.PublicKey)
return asn1ber.Marshal(*pub)
}
+25
View File
@@ -0,0 +1,25 @@
package core
import "github.com/shadow1ng/fscan/mylib/grdp/emission"
type Transport interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
On(event, listener interface{}) *emission.Emitter
Once(event, listener interface{}) *emission.Emitter
Emit(event interface{}, arguments ...interface{}) *emission.Emitter
}
type FastPathListener interface {
RecvFastPath(secFlag byte, s []byte)
}
type FastPathSender interface {
SendFastPath(secFlag byte, s []byte) (int, error)
}
type ChannelSender interface {
SendToChannel(channel string, s []byte) (int, error)
}
+67
View File
@@ -0,0 +1,67 @@
package core
import (
"bytes"
"crypto/rand"
"encoding/binary"
"unicode/utf16"
)
func Reverse(s []byte) []byte {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
func Random(n int) []byte {
const alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = alpha[b%byte(len(alpha))]
}
return bytes
}
func UTF16ToLittleEndianBytes(u []uint16) []byte {
b := make([]byte, 2*len(u))
for index, value := range u {
binary.LittleEndian.PutUint16(b[index*2:], value)
}
return b
}
func LittleEndianBytesToUTF16(u []byte) []uint16 {
b := make([]uint16, 0, len(u)/2)
n := make([]byte, 2)
for i, v := range u {
if i%2 == 0 {
n[0] = v
} else {
n[1] = v
b = append(b, binary.LittleEndian.Uint16(n))
}
}
return b
}
// s.encode('utf-16le')
func UnicodeEncode(p string) []byte {
return UTF16ToLittleEndianBytes(utf16.Encode([]rune(p)))
}
func UnicodeDecode(p []byte) string {
r := bytes.NewReader(p)
n := make([]uint16, 0, 100)
for r.Len() > 0 {
a, _ := ReadUint16LE(r)
n = append(n, a)
}
//n := LittleEndianBytesToUTF16(p)
return string(utf16.Decode(n))
}
func BytesToUint64(b []byte) uint64 {
return binary.LittleEndian.Uint64(b)
}
+290
View File
@@ -0,0 +1,290 @@
// Package emission provides an event emitter.
// copy form https://raw.githubusercontent.com/chuckpreslar/emission/master/emitter.go
// fix issue with nest once
package emission
import (
"errors"
"fmt"
"os"
"reflect"
"sync"
)
// Default number of maximum listeners for an event.
const DefaultMaxListeners = 10
// Error presented when an invalid argument is provided as a listener function
var ErrNoneFunction = errors.New("Kind of Value for listener is not Func.")
// RecoveryListener ...
type RecoveryListener func(interface{}, interface{}, error)
// Emitter ...
type Emitter struct {
// Mutex to prevent race conditions within the Emitter.
*sync.Mutex
// Map of event to a slice of listener function's reflect Values.
events map[interface{}][]reflect.Value
// Optional RecoveryListener to call when a panic occurs.
recoverer RecoveryListener
// Maximum listeners for debugging potential memory leaks.
maxListeners int
// Map of event to a slice of listener function's reflect Values.
onces map[interface{}][]reflect.Value
}
// AddListener appends the listener argument to the event arguments slice
// in the Emitter's events map. If the number of listeners for an event
// is greater than the Emitter's maximum listeners then a warning is printed.
// If the relect Value of the listener does not have a Kind of Func then
// AddListener panics. If a RecoveryListener has been set then it is called
// recovering from the panic.
func (emitter *Emitter) AddListener(event, listener interface{}) *Emitter {
emitter.Lock()
defer emitter.Unlock()
fn := reflect.ValueOf(listener)
if reflect.Func != fn.Kind() {
if nil == emitter.recoverer {
panic(ErrNoneFunction)
} else {
emitter.recoverer(event, listener, ErrNoneFunction)
}
}
if emitter.maxListeners != -1 && emitter.maxListeners < len(emitter.events[event])+1 {
fmt.Fprintf(os.Stdout, "Warning: event `%v` has exceeded the maximum "+
"number of listeners of %d.\n", event, emitter.maxListeners)
}
emitter.events[event] = append(emitter.events[event], fn)
return emitter
}
// On is an alias for AddListener.
func (emitter *Emitter) On(event, listener interface{}) *Emitter {
return emitter.AddListener(event, listener)
}
// RemoveListener removes the listener argument from the event arguments slice
// in the Emitter's events map. If the reflect Value of the listener does not
// have a Kind of Func then RemoveListener panics. If a RecoveryListener has
// been set then it is called after recovering from the panic.
func (emitter *Emitter) RemoveListener(event, listener interface{}) *Emitter {
emitter.Lock()
defer emitter.Unlock()
fn := reflect.ValueOf(listener)
if reflect.Func != fn.Kind() {
if nil == emitter.recoverer {
panic(ErrNoneFunction)
} else {
emitter.recoverer(event, listener, ErrNoneFunction)
}
}
if events, ok := emitter.events[event]; ok {
newEvents := []reflect.Value{}
for _, listener := range events {
if fn.Pointer() != listener.Pointer() {
newEvents = append(newEvents, listener)
}
}
emitter.events[event] = newEvents
}
if events, ok := emitter.onces[event]; ok {
newEvents := []reflect.Value{}
for _, listener := range events {
if fn.Pointer() != listener.Pointer() {
newEvents = append(newEvents, listener)
}
}
emitter.onces[event] = newEvents
}
return emitter
}
// Off is an alias for RemoveListener.
func (emitter *Emitter) Off(event, listener interface{}) *Emitter {
return emitter.RemoveListener(event, listener)
}
// Once generates a new function which invokes the supplied listener
// only once before removing itself from the event's listener slice
// in the Emitter's events map. If the reflect Value of the listener
// does not have a Kind of Func then Once panics. If a RecoveryListener
// has been set then it is called after recovering from the panic.
func (emitter *Emitter) Once(event, listener interface{}) *Emitter {
emitter.Lock()
defer emitter.Unlock()
fn := reflect.ValueOf(listener)
if reflect.Func != fn.Kind() {
if nil == emitter.recoverer {
panic(ErrNoneFunction)
} else {
emitter.recoverer(event, listener, ErrNoneFunction)
}
}
if emitter.maxListeners != -1 && emitter.maxListeners < len(emitter.onces[event])+1 {
fmt.Fprintf(os.Stdout, "Warning: event `%v` has exceeded the maximum "+
"number of listeners of %d.\n", event, emitter.maxListeners)
}
emitter.onces[event] = append(emitter.onces[event], fn)
return emitter
}
// Emit attempts to use the reflect package to Call each listener stored
// in the Emitter's events map with the supplied arguments. Each listener
// is called within its own go routine. The reflect package will panic if
// the agruments supplied do not align the parameters of a listener function.
// If a RecoveryListener has been set then it is called after recovering from
// the panic.
func (emitter *Emitter) Emit(event interface{}, arguments ...interface{}) *Emitter {
var (
listeners []reflect.Value
ok bool
)
// Lock the mutex when reading from the Emitter's
// events map.
emitter.Lock()
if listeners, ok = emitter.events[event]; !ok {
// If the Emitter does not include the event in its
// event map, it has no listeners to Call yet.
emitter.Unlock()
goto ONCES
}
// Unlock the mutex immediately following the read
// instead of deferring so that listeners registered
// with Once can aquire the mutex for removal.
emitter.Unlock()
emitter.callListeners(listeners, event, arguments...)
ONCES:
// execute onces
emitter.Lock()
if listeners, ok = emitter.onces[event]; !ok {
emitter.Unlock()
return emitter
}
emitter.Unlock()
emitter.callListeners(listeners, event, arguments...)
// clear executed listeners
emitter.onces[event] = emitter.onces[event][len(listeners):]
return emitter
}
func (emitter *Emitter) callListeners(listeners []reflect.Value, event interface{}, arguments ...interface{}) {
var wg sync.WaitGroup
wg.Add(len(listeners))
for _, fn := range listeners {
go func(fn reflect.Value) {
defer wg.Done()
// Recover from potential panics, supplying them to a
// RecoveryListener if one has been set, else allowing
// the panic to occur.
if nil != emitter.recoverer {
defer func() {
if r := recover(); nil != r {
err := fmt.Errorf("%v", r)
emitter.recoverer(event, fn.Interface(), err)
}
}()
}
var values []reflect.Value
for i := 0; i < len(arguments); i++ {
if arguments[i] == nil {
values = append(values, reflect.New(fn.Type().In(i)).Elem())
} else {
argValue := reflect.ValueOf(arguments[i])
expectedType := fn.Type().In(i)
// 检查是否需要转换类型
if argValue.Type().ConvertibleTo(expectedType) {
// 如果可以转换,则转换类型
//fmt.Printf("将参数 %v(类型 %v)转换为所需类型 %v\n", arguments[i], argValue.Type(), expectedType)
argValue = argValue.Convert(expectedType)
} else {
// 打印错误信息,类型不匹配
fmt.Printf("无法将参数 %v(类型 %v)转换为所需类型 %v\n", arguments[i], argValue.Type(), expectedType)
continue
}
//values = append(values, reflect.ValueOf(arguments[i]))
values = append(values, argValue)
}
}
fn.Call(values)
}(fn)
}
wg.Wait()
}
// RecoverWith sets the listener to call when a panic occurs, recovering from
// panics and attempting to keep the application from crashing.
func (emitter *Emitter) RecoverWith(listener RecoveryListener) *Emitter {
emitter.recoverer = listener
return emitter
}
// SetMaxListeners sets the maximum number of listeners per
// event for the Emitter. If -1 is passed as the maximum,
// all events may have unlimited listeners. By default, each
// event can have a maximum number of 10 listeners which is
// useful for finding memory leaks.
func (emitter *Emitter) SetMaxListeners(max int) *Emitter {
emitter.Lock()
defer emitter.Unlock()
emitter.maxListeners = max
return emitter
}
// GetListenerCount gets count of listeners for a given event.
func (emitter *Emitter) GetListenerCount(event interface{}) (count int) {
emitter.Lock()
if listeners, ok := emitter.events[event]; ok {
count = len(listeners)
}
emitter.Unlock()
return
}
// NewEmitter returns a new Emitter object, defaulting the
// number of maximum listeners per event to the DefaultMaxListeners
// constant and initializing its events map.
func NewEmitter() (emitter *Emitter) {
emitter = new(Emitter)
emitter.Mutex = new(sync.Mutex)
emitter.events = make(map[interface{}][]reflect.Value)
emitter.maxListeners = DefaultMaxListeners
emitter.onces = make(map[interface{}][]reflect.Value)
return
}
+129
View File
@@ -0,0 +1,129 @@
package glog
import (
"fmt"
"log"
"sync"
)
var (
logger *log.Logger
level LEVEL
mu sync.Mutex
)
type LEVEL int
const (
TRACE LEVEL = iota
DEBUG
INFO
WARN
ERROR
NONE
)
func SetLogger(l *log.Logger) {
l.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
logger = l
}
func SetLevel(l LEVEL) {
level = l
}
func checkLogger() {
if logger == nil && level != NONE {
panic("logger not inited")
}
}
func Trace(v ...interface{}) {
checkLogger()
if level <= TRACE {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[TRACE]")
logger.Output(2, fmt.Sprintln(v...))
}
}
func Tracef(f string, v ...interface{}) {
checkLogger()
if level <= TRACE {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[TRACE]")
logger.Output(2, fmt.Sprintln(fmt.Sprintf(f, v...)))
}
}
func Debug(v ...interface{}) {
checkLogger()
if level <= DEBUG {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[DEBUG]")
logger.Output(2, fmt.Sprintln(v...))
}
}
func Debugf(f string, v ...interface{}) {
checkLogger()
if level <= DEBUG {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[DEBUG]")
logger.Output(2, fmt.Sprintln(fmt.Sprintf(f, v...)))
}
}
func Info(v ...interface{}) {
checkLogger()
if level <= INFO {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[INFO]")
logger.Output(2, fmt.Sprintln(v...))
}
}
func Infof(f string, v ...interface{}) {
checkLogger()
if level <= INFO {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[INFO]")
logger.Output(2, fmt.Sprintln(fmt.Sprintf(f, v...)))
}
}
func Warn(v ...interface{}) {
checkLogger()
if level <= WARN {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[WARN]")
logger.Output(2, fmt.Sprintln(v...))
}
}
func Warnf(f string, v ...interface{}) {
checkLogger()
if level <= WARN {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[WARN]")
logger.Output(2, fmt.Sprintln(fmt.Sprintf(f, v...)))
}
}
func Error(v ...interface{}) {
checkLogger()
if level <= ERROR {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[ERROR]")
logger.Output(2, fmt.Sprintln(v...))
}
}
func Errorf(f string, v ...interface{}) {
checkLogger()
if level <= ERROR {
mu.Lock()
defer mu.Unlock()
logger.SetPrefix("[ERROR]")
logger.Output(2, fmt.Sprintln(fmt.Sprintf(f, v...)))
}
}
+662
View File
@@ -0,0 +1,662 @@
package login
import (
"bufio"
"bytes"
"errors"
"fmt"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/nla"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/pdu"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/sec"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/tpkt"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/x224"
"golang.org/x/net/context"
"golang.org/x/net/proxy"
"image"
"image/color"
"image/draw"
"image/jpeg"
"log"
"math/rand"
"net"
"net/url"
"os"
"strings"
"time"
)
var (
Socks5Proxy string = ""
LogLever glog.LEVEL = glog.NONE
OutputDir string
)
func init() {
}
func RdpConn(host, domain, user, password string, timeout int64, rdpProtocol uint32) (bool, error) {
g := NewClient(host, LogLever)
status, err, reconnectProtocol := g.ScreenShot(domain, user, password, timeout, rdpProtocol)
if status == true {
return true, err
} else {
if reconnectProtocol != rdpProtocol {
glog.Info("reconnect with protocol:", reconnectProtocol)
return RdpConn(host, domain, user, password, timeout, reconnectProtocol)
} else {
return status, err
}
}
}
func RdpCrack(host, domain, user, password string, timeout int64, rdpProtocol uint32) (bool, error) {
g := NewClient(host, LogLever)
status, err, reconnectProtocol := g.Crack(domain, user, password, timeout, rdpProtocol)
if status == true {
return true, err
} else {
if reconnectProtocol != rdpProtocol {
glog.Info("reconnect with protocol:", reconnectProtocol)
return RdpCrack(host, domain, user, password, timeout, reconnectProtocol)
} else {
return status, err
}
}
}
type Client struct {
Host string // ip:port
tpkt *tpkt.TPKT
x224 *x224.X224
mcs *t125.MCSClient
sec *sec.Client
pdu *pdu.Client
}
func NewClient(host string, logLevel glog.LEVEL) *Client {
glog.SetLevel(logLevel)
logger := log.New(os.Stdout, "", 0)
glog.SetLogger(logger)
return &Client{
Host: host,
}
}
func WrapperTcpWithTimeout(network, address string, timeout time.Duration) (net.Conn, error) {
local_ip := "0.0.0.0"
net_ip := net.ParseIP(local_ip)
if net_ip == nil {
net_ip = net.ParseIP("0.0.0.0")
}
local_addr := &net.TCPAddr{
IP: net_ip, // 替换为你想要使用的本地IP地址
}
d := &net.Dialer{Timeout: timeout, LocalAddr: local_addr}
return WrapperTCP(network, address, d)
}
func WrapperTCP(network, address string, forward *net.Dialer) (net.Conn, error) {
//get conn
var conn net.Conn
if Socks5Proxy == "" {
var err error
conn, err = forward.Dial(network, address)
if err != nil {
return nil, err
}
} else {
dailer, err := Socks5Dailer(forward)
if err != nil {
return nil, err
}
conn, err = dailer.Dial(network, address)
if err != nil {
// fmt.Println(err)
return nil, err
}
}
timeout := forward.Timeout
if err := conn.SetWriteDeadline(time.Now().Add(timeout * 6)); err != nil {
return nil, err
}
if err := conn.SetReadDeadline(time.Now().Add(timeout * 6)); err != nil {
return nil, err
}
return conn, nil
}
func Socks5Dailer(forward *net.Dialer) (proxy.Dialer, error) {
u, err := url.Parse(Socks5Proxy)
if err != nil {
return nil, err
}
if strings.ToLower(u.Scheme) != "socks5" {
return nil, errors.New("Only support socks5")
}
address := u.Host
var auth proxy.Auth
var dailer proxy.Dialer
if u.User.String() != "" {
auth = proxy.Auth{}
auth.User = u.User.Username()
password, _ := u.User.Password()
auth.Password = password
dailer, err = proxy.SOCKS5("tcp", address, &auth, forward)
} else {
dailer, err = proxy.SOCKS5("tcp", address, nil, forward)
}
if err != nil {
return nil, err
}
return dailer, nil
}
type Bitmap struct {
DestLeft int `json:"destLeft"`
DestTop int `json:"destTop"`
DestRight int `json:"destRight"`
DestBottom int `json:"destBottom"`
Width int `json:"width"`
Height int `json:"height"`
BitsPerPixel int `json:"bitsPerPixel"`
IsCompress bool `json:"isCompress"`
Data []byte `json:"data"`
}
func Bpp(BitsPerPixel uint16) (pixel int) {
switch BitsPerPixel {
case 15:
pixel = 1
case 16:
pixel = 2
case 24:
pixel = 3
case 32:
pixel = 4
default:
glog.Error("-------------------------------------Bpp func. invalid bitmap data format")
}
return
}
func BitmapDecompress(bitmap *pdu.BitmapData) []byte {
return core.Decompress(bitmap.BitmapDataStream, int(bitmap.Width), int(bitmap.Height), Bpp(bitmap.BitsPerPixel))
}
func ToRGBA(pixel int, i int, data []byte) (r, g, b, a uint8) {
a = 255
switch pixel {
case 1:
rgb555 := core.Uint16BE(data[i], data[i+1])
r, g, b = core.RGB555ToRGB(rgb555)
case 2:
rgb565 := core.Uint16BE(data[i], data[i+1])
r, g, b = core.RGB565ToRGB(rgb565)
case 3, 4:
fallthrough
default:
r, g, b = data[i+2], data[i+1], data[i]
}
return
}
func (g *Client) ProbeOSInfo(host, domain, user, pwd string, timeout int64, rdpProtocol uint32) (info map[string]any) {
start := time.Now()
exitFlag := make(chan bool)
info = make(map[string]any)
targetSlice := strings.Split(g.Host, ":")
ip := targetSlice[0]
conn, err := WrapperTcpWithTimeout("tcp", g.Host, time.Duration(timeout)*time.Second)
if err != nil {
return
}
defer conn.Close()
glog.Info(conn.LocalAddr().String())
g.tpkt = tpkt.New(core.NewSocketLayer(conn), nla.NewNTLMv2(domain, user, pwd))
g.x224 = x224.New(g.tpkt)
g.mcs = t125.NewMCSClient(g.x224)
g.sec = sec.NewClient(g.mcs)
g.pdu = pdu.NewClient(g.sec)
g.sec.SetUser(user)
g.sec.SetPwd(pwd)
g.sec.SetDomain(domain)
g.tpkt.SetFastPathListener(g.sec)
g.sec.SetFastPathListener(g.pdu)
g.pdu.SetFastPathSender(g.tpkt)
g.sec.SetChannelSender(g.mcs)
g.tpkt.On("os_info", func(infoMap map[string]any) {
glog.Debug("[+] callback, get os info ........................")
for k, v := range infoMap {
glog.Debugf("%s: %s\n", k, v)
}
info = infoMap
g.pdu.Emit("done")
})
g.x224.SetRequestedProtocol(rdpProtocol) //x224.PROTOCOL_SSL , x224.PROTOCOL_RDP , x224.PROTOCOL_HYBRID , x224.PROTOCOL_HYBRID_EX
g.x224.On("reconnect", func(protocol uint32) {
info["reconn"] = protocol
g.pdu.Emit("close")
exitFlag <- true
})
err = g.x224.Connect()
if err != nil {
info["err"] = err.Error()
return
}
glog.Info("wait connect ok")
g.pdu.On("error", func(e error) {
err = e
glog.Error("error", e)
g.pdu.Emit("done")
})
g.pdu.On("close", func() {
err = errors.New("close")
glog.Info("on close")
g.pdu.Emit("done")
})
g.pdu.On("success", func() {
glog.Debugf("===============login success %s===============", ip)
err = nil
g.pdu.Emit("done")
})
g.pdu.On("ready", func() {
err = nil
glog.Debug("on ready")
})
g.pdu.On("bitmap", func(rectangles []pdu.BitmapData) {
})
g.pdu.On("done", func() {
glog.Debug("done信号触发")
exitFlag <- true
})
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout*3)*time.Second)
defer cancel()
loop:
for {
select {
case <-time.After(time.Second * time.Duration(timeout)): //
break loop
case <-exitFlag:
break loop
case <-ctx.Done():
glog.Debug("总超时已达到,退出")
break loop
}
}
glog.Debug("循环结束,总时间过去了:", time.Since(start))
return info
}
func (g *Client) ScreenShot(domain, user, pwd string, timeout int64, rdpProtocol uint32) (status bool, err error, reconnProtocol uint32) {
//glog.SetLevel(glog.ERROR)
reconnProtocol = rdpProtocol
pic_length := 1280 //1280
pic_width := 800 //800
needReconnect := false
isScreenOK := false
refresh := make(chan bool)
exitFlag := make(chan bool)
start := time.Now()
now := start
screenImage := image.NewRGBA(image.Rect(0, 0, pic_length, pic_width))
index := 1
targetSlice := strings.Split(g.Host, ":")
ip := targetSlice[0]
port := targetSlice[1]
status = false
conn, err := WrapperTcpWithTimeout("tcp", g.Host, time.Duration(timeout)*time.Second)
if err != nil {
return status, fmt.Errorf("[dial err] %v", err), reconnProtocol
}
defer conn.Close()
glog.Info(conn.LocalAddr().String())
g.tpkt = tpkt.New(core.NewSocketLayer(conn), nla.NewNTLMv2(domain, user, pwd))
g.x224 = x224.New(g.tpkt)
g.mcs = t125.NewMCSClient(g.x224)
g.sec = sec.NewClient(g.mcs)
g.pdu = pdu.NewClient(g.sec)
g.sec.SetUser(user)
g.sec.SetPwd(pwd)
g.sec.SetDomain(domain)
//g.sec.SetClientAutoReconnect()
g.tpkt.SetFastPathListener(g.sec)
g.sec.SetFastPathListener(g.pdu)
g.pdu.SetFastPathSender(g.tpkt)
g.sec.SetChannelSender(g.mcs)
g.tpkt.On("os_info", func(info map[string]any) {
glog.Debug("[+] callback, get os info ........................")
for k, v := range info {
glog.Debugf("%s: %s\n", k, v)
}
})
g.x224.SetRequestedProtocol(rdpProtocol) //x224.PROTOCOL_SSL , x224.PROTOCOL_RDP , x224.PROTOCOL_HYBRID , x224.PROTOCOL_HYBRID_EX
g.x224.On("reconnect", func(protocol uint32) {
needReconnect = true
reconnProtocol = protocol
glog.Info("need reconnect with protocol:", protocol)
g.pdu.Emit("close")
exitFlag <- true
})
g.x224.On("more_timeout", func() {
timeout += 18 //如果是PROTOCOL_RDP协议,可以适当延长超时时间
})
err = g.x224.Connect()
if err != nil {
return status, fmt.Errorf("[x224 connect err] %v", err), reconnProtocol
}
glog.Info("wait connect ok")
g.pdu.On("error", func(e error) {
err = e
glog.Error("error", e)
g.pdu.Emit("done")
})
g.pdu.On("close", func() {
err = errors.New("close")
glog.Info("on close")
g.pdu.Emit("done")
})
g.pdu.On("success", func() {
glog.Debugf("===============login success %s===============", ip)
status = true
err = nil
g.pdu.Emit("done")
})
g.pdu.On("ready", func() {
err = nil
glog.Debug("on ready")
//g.pdu.Emit("done")
})
g.pdu.On("bitmap", func(rectangles []pdu.BitmapData) {
now = time.Now()
// 发送一个鼠标事件,作用是与服务器保持联系不要断开
rand.New(rand.NewSource(time.Now().UnixNano()))
randomNumber := rand.Intn(1000) + 10 // 10到1000之间的随机数
mouseX := 60 + randomNumber
mouseY := 10 + randomNumber
pevent := &pdu.PointerEvent{}
pevent.PointerFlags |= pdu.PTRFLAGS_MOVE
pevent.XPos = uint16(mouseX)
pevent.YPos = uint16(mouseY)
g.pdu.SendInputEvents(pdu.INPUT_EVENT_MOUSE, []pdu.InputEventsInterface{pevent})
glog.Debug("on update bitmap:", len(rectangles))
bs := make([]Bitmap, 0)
for _, v := range rectangles {
IsCompress := v.IsCompress()
data := v.BitmapDataStream
if IsCompress {
data = BitmapDecompress(&v)
IsCompress = false
}
b := Bitmap{int(v.DestLeft), int(v.DestTop), int(v.DestRight), int(v.DestBottom),
int(v.Width), int(v.Height), Bpp(v.BitsPerPixel), IsCompress, data}
bs = append(bs, b)
}
var (
pixel int
i int
r, g, b, a uint8
)
for _, bm := range bs {
i = 0
pixel = bm.BitsPerPixel
m := image.NewRGBA(image.Rect(0, 0, bm.Width, bm.Height))
for y := 0; y < bm.Height; y++ {
for x := 0; x < bm.Width; x++ {
r, g, b, a = ToRGBA(pixel, i, bm.Data)
c := color.RGBA{R: r, G: g, B: b, A: a}
i += pixel
m.Set(x, y, c)
}
}
draw.Draw(screenImage, screenImage.Bounds().Add(image.Pt(bm.DestLeft, bm.DestTop)), m, m.Bounds().Min, draw.Src)
}
// Encode to jpeg.
//var imageBuf bytes.Buffer
//err = jpeg.Encode(&imageBuf, screenImage, nil)
//
//if err != nil {
// glog.Info("trans bitmap to jpeg err:", err)
//}
// Write to file.
//fo, err := os.Create(fmt.Sprintf("img/%s-%d.jpg", ip, index))
//if err != nil {
// panic(err)
//}
//index += 1
//fw := bufio.NewWriter(fo)
//fw.Write(imageBuf.Bytes())
isScreenOK = true
refresh <- true
})
g.pdu.On("done", func() {
glog.Debug("done信号触发")
exitFlag <- true
})
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout*6)*time.Second)
defer cancel()
loop:
for {
select {
case <-time.After(time.Second * time.Duration(timeout*3)): //
glog.Debug("本次获取bitmap超时了, 距离上次获取到图像过去了:", time.Since(now))
break loop
case <-refresh:
continue loop
case <-exitFlag:
break loop
case <-ctx.Done():
glog.Debug("总超时已达到,退出")
break loop
}
}
glog.Debug("循环结束,总时间过去了:", time.Since(start))
if g.x224.ServerChooseProtocol() == x224.PROTOCOL_HYBRID && g.x224.ServerChooseProtocol() == x224.PROTOCOL_HYBRID {
if err == nil {
status = true
}
}
if needReconnect {
return status, err, reconnProtocol
} else if isScreenOK {
glog.Info("get screen ok")
// Encode to jpeg.
var imageBuf bytes.Buffer
err = jpeg.Encode(&imageBuf, screenImage, nil)
if err != nil {
log.Panic(err)
}
// Write to file.
saveDate := time.Now().Format("2006_01_02_15_04_05")
fo, writeErr := os.Create(fmt.Sprintf("%s/%s_%s_%s.jpg", OutputDir, ip, port, saveDate))
index += 1
if writeErr != nil {
glog.Error("Can not create rdp screenshot file:", writeErr)
} else {
fw := bufio.NewWriter(fo)
_, writeErr := fw.Write(imageBuf.Bytes())
if writeErr != nil {
glog.Error("Can not write rdp screenshot file:", writeErr)
}
}
}
return status, err, reconnProtocol
}
func (g *Client) Crack(domain, user, pwd string, timeout int64, rdpProtocol uint32) (status bool, err error, reconnProtocol uint32) {
//glog.SetLevel(glog.ERROR)
reconnProtocol = rdpProtocol
needReconnect := false
refresh := make(chan bool)
exitFlag := make(chan bool)
start := time.Now()
now := start
targetSlice := strings.Split(g.Host, ":")
ip := targetSlice[0]
status = false
conn, err := WrapperTcpWithTimeout("tcp", g.Host, time.Duration(timeout)*time.Second)
if err != nil {
return status, fmt.Errorf("[dial err] %v", err), reconnProtocol
}
defer conn.Close()
glog.Info(conn.LocalAddr().String())
g.tpkt = tpkt.New(core.NewSocketLayer(conn), nla.NewNTLMv2(domain, user, pwd))
g.x224 = x224.New(g.tpkt)
g.mcs = t125.NewMCSClient(g.x224)
g.sec = sec.NewClient(g.mcs)
g.pdu = pdu.NewClient(g.sec)
g.sec.SetUser(user)
g.sec.SetPwd(pwd)
g.sec.SetDomain(domain)
//g.sec.SetClientAutoReconnect()
g.tpkt.SetFastPathListener(g.sec)
g.sec.SetFastPathListener(g.pdu)
g.pdu.SetFastPathSender(g.tpkt)
g.sec.SetChannelSender(g.mcs)
g.tpkt.On("os_info", func(info map[string]any) {
glog.Debug("[+] callback, get os info ........................")
for k, v := range info {
glog.Debugf("%s: %s\n", k, v)
}
})
g.x224.SetRequestedProtocol(rdpProtocol) //x224.PROTOCOL_SSL , x224.PROTOCOL_RDP , x224.PROTOCOL_HYBRID , x224.PROTOCOL_HYBRID_EX
g.x224.On("reconnect", func(protocol uint32) {
needReconnect = true
reconnProtocol = protocol
glog.Info("need reconnect with protocol:", protocol)
g.pdu.Emit("close")
exitFlag <- true
})
g.x224.On("more_timeout", func() {
timeout += 18 //如果是PROTOCOL_RDP协议,可以适当延长超时时间
})
err = g.x224.Connect()
if err != nil {
return status, fmt.Errorf("[x224 connect err] %v", err), reconnProtocol
}
glog.Info("wait connect ok")
g.pdu.On("error", func(e error) {
err = e
glog.Error("error", e)
g.pdu.Emit("done")
})
g.pdu.On("close", func() {
err = errors.New("close")
glog.Info("on close")
g.pdu.Emit("done")
})
g.pdu.On("success", func() {
glog.Debugf("===============login success %s===============", ip)
status = true
err = nil
g.pdu.Emit("done")
})
g.pdu.On("ready", func() {
err = nil
glog.Debug("on ready")
//g.pdu.Emit("done")
})
g.pdu.On("bitmap", func(rectangles []pdu.BitmapData) {
now = time.Now()
// 发送一个鼠标事件,作用是与服务器保持联系不要断开
rand.New(rand.NewSource(time.Now().UnixNano()))
randomNumber := rand.Intn(1000) + 10 // 10到1000之间的随机数
mouseX := 60 + randomNumber
mouseY := 10 + randomNumber
pevent := &pdu.PointerEvent{}
pevent.PointerFlags |= pdu.PTRFLAGS_MOVE
pevent.XPos = uint16(mouseX)
pevent.YPos = uint16(mouseY)
g.pdu.SendInputEvents(pdu.INPUT_EVENT_MOUSE, []pdu.InputEventsInterface{pevent})
glog.Debug("on update bitmap:", len(rectangles))
refresh <- true
})
g.pdu.On("done", func() {
glog.Debug("done信号触发")
exitFlag <- true
})
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout*6)*time.Second)
defer cancel()
loop:
for {
select {
case <-time.After(time.Second * time.Duration(timeout*3)): //
glog.Debug("本次获取bitmap超时了, 距离上次获取到图像过去了:", time.Since(now))
break loop
case <-refresh:
continue loop
case <-exitFlag:
break loop
case <-ctx.Done():
glog.Debug("总超时已达到,退出")
break loop
}
}
glog.Debug("循环结束,总时间过去了:", time.Since(start))
if g.x224.ServerChooseProtocol() == x224.PROTOCOL_HYBRID && g.x224.ServerChooseProtocol() == x224.PROTOCOL_HYBRID {
if err == nil {
status = true
}
}
if needReconnect {
return status, err, reconnProtocol
}
return status, err, reconnProtocol
}
+328
View File
@@ -0,0 +1,328 @@
// +build ignore
// addins.go
package plugin
import (
"strings"
"sync/atomic"
"syscall"
"unsafe"
)
var (
openHandleSeq uint32
freerdpClient2 = syscall.NewLazyDLL("freerdp-client2.dll")
winpr2 = syscall.NewLazyDLL("winpr2.dll")
freerdp2 = syscall.NewLazyDLL("freerdp2.dll")
)
var (
virtualChannelEntry = freerdpClient2.NewProc("VirtualChannelEntry")
virtualChannelEntryEx = freerdpClient2.NewProc("VirtualChannelEntryEx")
)
func VirtualChannelEntryEx(ex *ChannelEntryPointsEx, pInitHandle interface{}) (err error) {
r0, _, ec := virtualChannelEntryEx.Call(uintptr(unsafe.Pointer(ex)),
uintptr(unsafe.Pointer(&pInitHandle)))
if r0 == 0 {
err = error(ec)
}
return
}
func ChannelsClientLoadEx(cs *rdpChannels) {
var client ChannelClientData
client.entryEx = VIRTUALCHANNELENTRYEX(VirtualChannelEntryEx)
cs.clientDataList = append(cs.clientDataList, client)
cs.clientDataCount++
var init ChannelInitData
init.channels = cs
init.openDataMap = make(map[uint32]*ChannelOpenData)
cs.initDataList = append(cs.initDataList, init)
cs.initDataCount++
ex := NewChannelEntryPointsEx()
ex.PVirtualChannelInitEx = VIRTUALCHANNELINITEX(RdpVirtualChannelInitEx)
ex.PVirtualChannelOpenEx = VIRTUALCHANNELOPENEX(RdpVirtualChannelOpenEx)
ex.PVirtualChannelCloseEx = VIRTUALCHANNELCLOSEEX(RdpVirtualChannelCloseEx)
ex.PVirtualChannelWriteEx = VIRTUALCHANNELWRITEEX(RdpVirtualChannelWriteEx)
client.entryEx(ex, uintptr(unsafe.Pointer(&init)))
}
type ChannelClientData struct {
//PVIRTUALCHANNELENTRY entry;
entryEx VIRTUALCHANNELENTRYEX
// pChannelInitEventProc *CHANNEL_INIT_EVENT_FN
pChannelInitEventProcEx CHANNEL_INIT_EVENT_EX_FN
pInitHandle interface{}
lpUserParam interface{}
}
type ChannelOpenData struct {
name string
OpenHandle uint32
options uint32
flags int
pInterface interface{}
channels *rdpChannels
lpUserParam interface{}
//pChannelOpenEventProc *CHANNEL_OPEN_EVENT_FN
pChannelOpenEventProcEx *CHANNEL_OPEN_EVENT_EX_FN
}
type ChannelInitData struct {
channels *rdpChannels
pInterface interface{}
openDataMap map[uint32]*ChannelOpenData
}
type rdpChannels struct {
clientDataCount int
clientDataList []ChannelClientData
openDataCount int
openDataList []ChannelOpenData
initDataCount int
initDataList []ChannelInitData
/* control for entry into MyVirtualChannelInit */
can_call_init bool
/* true once freerdp_channels_post_connect is called */
connected bool
/* used for locating the channels for a given instance */
//freerdp* instance;
//wMessageQueue* queue;
//DrdynvcClientContext* drdynvc;
//CRITICAL_SECTION channelsLock;
}
type ChannelOpenEvent struct {
Data interface{}
DataLength uint32
UserData interface{}
pChannelOpenData *ChannelOpenData
}
func RdpVirtualChannelInitEx(lpUserParam interface{}, clientContext interface{},
pInitHandle interface{}, pChannel []ChannelDef,
channelCount int, versionRequested uint32,
pChannelInitEventProcEx CHANNEL_INIT_EVENT_EX_FN) uint {
var (
//rdpSettings* settings;
pChannelInitData *ChannelInitData
pChannelClientData *ChannelClientData
channels *rdpChannels
)
if pInitHandle == nil {
return CHANNEL_RC_BAD_INIT_HANDLE
}
if pChannel == nil {
return CHANNEL_RC_BAD_CHANNEL
}
if (channelCount <= 0) || pChannelInitEventProcEx == nil {
return CHANNEL_RC_INITIALIZATION_ERROR
}
pChannelInitData = pInitHandle.(*ChannelInitData)
//WINPR_ASSERT(pChannelInitData);
channels = pChannelInitData.channels
//WINPR_ASSERT(channels);
if !channels.can_call_init {
return CHANNEL_RC_NOT_IN_VIRTUALCHANNELENTRY
}
if (channels.openDataCount + channelCount) > 30 {
return CHANNEL_RC_TOO_MANY_CHANNELS
}
if channels.connected {
return CHANNEL_RC_ALREADY_CONNECTED
}
if versionRequested != VIRTUAL_CHANNEL_VERSION_WIN2000 {
}
for i := range pChannel {
pChannelDef := &pChannel[i]
if getChannelOpenDataByName(channels, pChannelDef.Name) == nil {
return CHANNEL_RC_BAD_CHANNEL
}
}
pChannelClientData = &channels.clientDataList[channels.clientDataCount]
pChannelClientData.pChannelInitEventProcEx = pChannelInitEventProcEx
pChannelClientData.pInitHandle = pInitHandle
pChannelClientData.lpUserParam = lpUserParam
channels.clientDataCount++
//WINPR_ASSERT(channels->instance);
//WINPR_ASSERT(channels->instance->context);
//settings = channels.instance.context.settings
//WINPR_ASSERT(settings);
for i := range pChannel {
pChannelDef := &pChannel[i]
var pChannelOpenData ChannelOpenData
//WINPR_ASSERT(pChannelOpenData)
pChannelOpenData.OpenHandle = atomic.AddUint32(&openHandleSeq, 1)
pChannelOpenData.channels = channels
pChannelOpenData.lpUserParam = lpUserParam
if _, ok := pChannelInitData.openDataMap[pChannelOpenData.OpenHandle]; ok {
return CHANNEL_RC_INITIALIZATION_ERROR
}
pChannelInitData.pInterface = clientContext
pChannelOpenData.flags = 1
pChannelOpenData.name = pChannelDef.Name
pChannelOpenData.options = pChannelDef.Options
pChannelInitData.openDataMap[pChannelOpenData.OpenHandle] = &pChannelOpenData
channels.openDataList = append(channels.openDataList, pChannelOpenData)
channels.openDataCount++
/*
if settings.ChannelCount < 30 {
channel := freerdp_settings_get_pointer_array_writable(
settings, FreeRDP_ChannelDefArray, settings.ChannelCount)
channel.name = pChannelDef.Name
channel.options = pChannelDef.Options
settings.ChannelCount++
}*/
channels.openDataCount++
}
return CHANNEL_RC_OK
}
func getChannelOpenDataByName(channel *rdpChannels, name string) *ChannelOpenData {
for _, v := range channel.openDataList {
if strings.EqualFold(name, v.name) {
return &v
}
}
return nil
}
func RdpVirtualChannelOpenEx(pInitHandle interface{}, pOpenHandle *uint32, pChannelName string,
pChannelOpenEventProcEx *CHANNEL_OPEN_EVENT_EX_FN) uint {
pChannelInitData := pInitHandle.(*ChannelInitData)
channels := pChannelInitData.channels
pInterface := pChannelInitData.pInterface
if pOpenHandle == nil {
return CHANNEL_RC_BAD_CHANNEL_HANDLE
}
if pChannelOpenEventProcEx == nil {
return CHANNEL_RC_BAD_PROC
}
if !channels.connected {
return CHANNEL_RC_NOT_CONNECTED
}
pChannelOpenData := getChannelOpenDataByName(channels, pChannelName)
if pChannelOpenData == nil {
return CHANNEL_RC_UNKNOWN_CHANNEL_NAME
}
if pChannelOpenData.flags == 2 {
return CHANNEL_RC_ALREADY_OPEN
}
pChannelOpenData.flags = 2 /* open */
pChannelOpenData.pInterface = pInterface
pChannelOpenData.pChannelOpenEventProcEx = pChannelOpenEventProcEx
*pOpenHandle = pChannelOpenData.OpenHandle
return CHANNEL_RC_OK
}
func RdpVirtualChannelCloseEx(pInitHandle interface{}, openHandle uint32) uint {
if pInitHandle == nil {
return CHANNEL_RC_BAD_INIT_HANDLE
}
pChannelInitData := pInitHandle.(*ChannelInitData)
pChannelOpenData := pChannelInitData.openDataMap[openHandle]
if pChannelOpenData == nil {
return CHANNEL_RC_BAD_CHANNEL_HANDLE
}
if pChannelOpenData.flags != 2 {
return CHANNEL_RC_NOT_OPEN
}
pChannelOpenData.flags = 0
return CHANNEL_RC_OK
}
func RdpVirtualChannelWriteEx(pInitHandle interface{}, openHandle uint32,
pData interface{}, dataLength uint32,
pUserData interface{}) uint {
//wMessage message;
if pInitHandle == nil {
return CHANNEL_RC_BAD_INIT_HANDLE
}
pChannelInitData := pInitHandle.(*ChannelInitData)
channels := pChannelInitData.channels
if channels == nil {
return CHANNEL_RC_BAD_CHANNEL_HANDLE
}
pChannelOpenData := pChannelInitData.openDataMap[openHandle]
if pChannelOpenData == nil {
return CHANNEL_RC_BAD_CHANNEL_HANDLE
}
if !channels.connected {
return CHANNEL_RC_NOT_CONNECTED
}
if pData == nil {
return CHANNEL_RC_NULL_DATA
}
if dataLength == 0 {
return CHANNEL_RC_ZERO_LENGTH
}
if pChannelOpenData.flags != 2 {
return CHANNEL_RC_NOT_OPEN
}
pChannelOpenEvent := new(ChannelOpenEvent)
if pChannelOpenEvent == nil {
return CHANNEL_RC_NO_MEMORY
}
pChannelOpenEvent.Data = pData
pChannelOpenEvent.DataLength = dataLength
pChannelOpenEvent.UserData = pUserData
pChannelOpenEvent.pChannelOpenData = pChannelOpenData
/*message.context = channels;
message.id = 0;
message.wParam = pChannelOpenEvent;
message.lParam = NULL;
message.Free = channel_queue_message_free;
if (!MessageQueue_Dispatch(channels->queue, &message))
{
free(pChannelOpenEvent);
return CHANNEL_RC_NO_MEMORY;
}*/
return CHANNEL_RC_OK
}
+304
View File
@@ -0,0 +1,304 @@
package plugin
import "C"
import (
"bytes"
"fmt"
"unsafe"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
)
const (
CHANNEL_RC_OK = 0
CHANNEL_RC_ALREADY_INITIALIZED = 1
CHANNEL_RC_NOT_INITIALIZED = 2
CHANNEL_RC_ALREADY_CONNECTED = 3
CHANNEL_RC_NOT_CONNECTED = 4
CHANNEL_RC_TOO_MANY_CHANNELS = 5
CHANNEL_RC_BAD_CHANNEL = 6
CHANNEL_RC_BAD_CHANNEL_HANDLE = 7
CHANNEL_RC_NO_BUFFER = 8
CHANNEL_RC_BAD_INIT_HANDLE = 9
CHANNEL_RC_NOT_OPEN = 10
CHANNEL_RC_BAD_PROC = 11
CHANNEL_RC_NO_MEMORY = 12
CHANNEL_RC_UNKNOWN_CHANNEL_NAME = 13
CHANNEL_RC_ALREADY_OPEN = 14
CHANNEL_RC_NOT_IN_VIRTUALCHANNELENTRY = 15
CHANNEL_RC_NULL_DATA = 16
CHANNEL_RC_ZERO_LENGTH = 17
CHANNEL_RC_INVALID_INSTANCE = 18
CHANNEL_RC_UNSUPPORTED_VERSION = 19
CHANNEL_RC_INITIALIZATION_ERROR = 20
)
const (
VIRTUAL_CHANNEL_VERSION_WIN2000 = 1
)
const (
CHANNEL_EVENT_INITIALIZED = 0
CHANNEL_EVENT_CONNECTED = 1
CHANNEL_EVENT_V1_CONNECTED = 2
CHANNEL_EVENT_DISCONNECTED = 3
CHANNEL_EVENT_TERMINATED = 4
CHANNEL_EVENT_REMOTE_CONTROL_START = 5
CHANNEL_EVENT_REMOTE_CONTROL_STOP = 6
CHANNEL_EVENT_ATTACHED = 7
CHANNEL_EVENT_DETACHED = 8
CHANNEL_EVENT_DATA_RECEIVED = 10
CHANNEL_EVENT_WRITE_COMPLETE = 11
CHANNEL_EVENT_WRITE_CANCELLED = 12
)
const (
CHANNEL_OPTION_INITIALIZED = 0x80000000
CHANNEL_OPTION_ENCRYPT_RDP = 0x40000000
CHANNEL_OPTION_ENCRYPT_SC = 0x20000000
CHANNEL_OPTION_ENCRYPT_CS = 0x10000000
CHANNEL_OPTION_PRI_HIGH = 0x08000000
CHANNEL_OPTION_PRI_MED = 0x04000000
CHANNEL_OPTION_PRI_LOW = 0x02000000
CHANNEL_OPTION_COMPRESS_RDP = 0x00800000
CHANNEL_OPTION_COMPRESS = 0x00400000
CHANNEL_OPTION_SHOW_PROTOCOL = 0x00200000
CHANNEL_OPTION_REMOTE_CONTROL_PERSISTENT = 0x00100000
)
type ChannelDef struct {
Name string
Options uint32
}
type CHANNEL_INIT_EVENT_EX_FN func(lpUserParam interface{},
pInitHandle interface{}, event uint, pData uintptr, dataLength uint)
type VIRTUALCHANNELINITEX func(lpUserParam interface{}, clientContext interface{},
pInitHandle interface{}, pChannel []ChannelDef,
channelCount int, versionRequested uint32,
pChannelInitEventProcEx CHANNEL_INIT_EVENT_EX_FN) uint
type CHANNEL_OPEN_EVENT_EX_FN func(lpUserParam uintptr,
openHandle uint32, event uint,
pData uintptr, dataLength uint32, totalLength uint32, dataFlags uint32)
type VIRTUALCHANNELOPENEX func(pInitHandle interface{}, pOpenHandle *uint32,
pChannelName string,
pChannelOpenEventProcEx *CHANNEL_OPEN_EVENT_EX_FN) uint
type VIRTUALCHANNELCLOSEEX func(pInitHandle interface{}, openHandle uint32) uint
type VIRTUALCHANNELWRITEEX func(pInitHandle interface{}, openHandle uint32, pData interface{},
dataLength uint32, pUserData interface{}) uint
type ChannelEntryPointsEx struct {
CbSize uint32
ProtocolVersion uint32
PVirtualChannelInitEx VIRTUALCHANNELINITEX
PVirtualChannelOpenEx VIRTUALCHANNELOPENEX
PVirtualChannelCloseEx VIRTUALCHANNELCLOSEEX
PVirtualChannelWriteEx VIRTUALCHANNELWRITEEX
}
func NewChannelEntryPointsEx() *ChannelEntryPointsEx {
e := &ChannelEntryPointsEx{}
e.CbSize = uint32(unsafe.Sizeof(e))
e.ProtocolVersion = VIRTUAL_CHANNEL_VERSION_WIN2000
return e
}
type VIRTUALCHANNELENTRYEX func(pEntryPointsEx *ChannelEntryPointsEx,
pInitHandle interface{}) error
/*
type ChannelEntryPoints struct {
CbSize uint32
ProtocolVersion uint32
PVirtualChannelInit PVIRTUALCHANNELINIT
PVirtualChannelOpen PVIRTUALCHANNELOPEN
PVirtualChannelClose PVIRTUALCHANNELCLOSE
PVirtualChannelWrite PVIRTUALCHANNELWRITE
}
typedef VOID VCAPITYPE CHANNEL_INIT_EVENT_FN(LPVOID pInitHandle,
UINT event, LPVOID pData, UINT dataLength);
typedef CHANNEL_INIT_EVENT_FN* PCHANNEL_INIT_EVENT_FN;
typedef VOID VCAPITYPE CHANNEL_OPEN_EVENT_FN(DWORD openHandle, UINT event,
LPVOID pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags);
typedef CHANNEL_OPEN_EVENT_FN* PCHANNEL_OPEN_EVENT_FN;
typedef UINT VCAPITYPE VIRTUALCHANNELINIT(LPVOID* ppInitHandle, PCHANNEL_DEF pChannel,
INT channelCount, ULONG versionRequested,
PCHANNEL_INIT_EVENT_FN pChannelInitEventProc);
typedef VIRTUALCHANNELINIT* PVIRTUALCHANNELINIT;
typedef UINT VCAPITYPE VIRTUALCHANNELOPEN(LPVOID pInitHandle, LPDWORD pOpenHandle,
PCHAR pChannelName,
PCHANNEL_OPEN_EVENT_FN pChannelOpenEventProc);
typedef VIRTUALCHANNELOPEN* PVIRTUALCHANNELOPEN;
typedef UINT VCAPITYPE VIRTUALCHANNELCLOSE(DWORD openHandle);
typedef VIRTUALCHANNELCLOSE* PVIRTUALCHANNELCLOSE;
typedef UINT VCAPITYPE VIRTUALCHANNELWRITE(DWORD openHandle, LPVOID pData, ULONG dataLength,
LPVOID pUserData);
typedef VIRTUALCHANNELWRITE* PVIRTUALCHANNELWRITE;
typedef UINT VCAPITYPE VIRTUALCHANNELINITEX(LPVOID lpUserParam, LPVOID clientContext,
LPVOID pInitHandle, PCHANNEL_DEF pChannel,
INT channelCount, ULONG versionRequested,
PCHANNEL_INIT_EVENT_EX_FN pChannelInitEventProcEx);
typedef VIRTUALCHANNELINITEX* PVIRTUALCHANNELINITEX;
typedef UINT VCAPITYPE VIRTUALCHANNELOPENEX(LPVOID pInitHandle, LPDWORD pOpenHandle,
PCHAR pChannelName,
PCHANNEL_OPEN_EVENT_EX_FN pChannelOpenEventProcEx);
typedef VIRTUALCHANNELOPENEX* PVIRTUALCHANNELOPENEX;
typedef UINT VCAPITYPE VIRTUALCHANNELCLOSEEX(LPVOID pInitHandle, DWORD openHandle);
typedef VIRTUALCHANNELCLOSEEX* PVIRTUALCHANNELCLOSEEX;
typedef UINT VCAPITYPE VIRTUALCHANNELWRITEEX(LPVOID pInitHandle, DWORD openHandle, LPVOID pData,
ULONG dataLength, LPVOID pUserData);
typedef VIRTUALCHANNELWRITEEX* PVIRTUALCHANNELWRITEEX;
*/
// static channel name
const (
CLIPRDR_SVC_CHANNEL_NAME = "cliprdr" //剪切板
RDPDR_SVC_CHANNEL_NAME = "rdpdr" //设备重定向(打印机,磁盘,端口,智能卡等)
RDPSND_SVC_CHANNEL_NAME = "rdpsnd" //音频输出
RAIL_SVC_CHANNEL_NAME = "rail" //远程应用
DRDYNVC_SVC_CHANNEL_NAME = "drdynvc" //动态虚拟通道
REMDESK_SVC_CHANNEL_NAME = "remdesk" //远程协助
)
const (
RDPGFX_DVC_CHANNEL_NAME = "Microsoft::Windows::RDS::Graphics" //图形扩展
)
var StaticVirtualChannels = map[string]int{
CLIPRDR_SVC_CHANNEL_NAME: CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP |
CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL,
RDPDR_SVC_CHANNEL_NAME: CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP | CHANNEL_OPTION_COMPRESS_RDP,
RDPSND_SVC_CHANNEL_NAME: CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP |
CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL,
RAIL_SVC_CHANNEL_NAME: CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP |
CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL,
}
const (
CHANNEL_CHUNK_LENGTH = 1600
CHANNEL_FLAG_FIRST = 0x01
CHANNEL_FLAG_LAST = 0x02
CHANNEL_FLAG_SHOW_PROTOCOL = 0x10
)
type ChannelTransport interface {
GetType() (string, uint32)
Sender(core.ChannelSender)
Process(s []byte)
}
type ChannelClient struct {
ChannelDef
t ChannelTransport
}
type Channels struct {
emission.Emitter
channels map[string]ChannelClient
transport core.Transport
buff *bytes.Buffer
channelSender core.ChannelSender
}
func NewChannels(t core.Transport) *Channels {
c := &Channels{
Emitter: *emission.NewEmitter(),
channels: make(map[string]ChannelClient, 20),
transport: t,
buff: &bytes.Buffer{},
}
t.On("channel", c.process)
return c
}
func (c *Channels) SetChannelSender(f core.ChannelSender) {
c.channelSender = f
}
func (c *Channels) Register(t ChannelTransport) {
name, option := t.GetType()
_, ok := c.channels[name]
if ok {
glog.Warn("Already register channel:", name)
return
}
t.Sender(c)
c.channels[name] = ChannelClient{ChannelDef{name, option}, t}
}
func (c *Channels) SendToChannel(channel string, s []byte) (int, error) {
cli, ok := c.channels[channel]
if !ok {
glog.Warn("No register channel:", channel)
return 0, fmt.Errorf("No register channel: %s", channel)
}
idx := 0
ln := len(s)
b := &bytes.Buffer{}
for ln > 0 {
var flag uint32 = 0
if cli.Options&CHANNEL_OPTION_SHOW_PROTOCOL != 0 {
flag |= CHANNEL_FLAG_SHOW_PROTOCOL
}
if idx == 0 {
flag |= CHANNEL_FLAG_FIRST
}
var ss []byte
if ln > CHANNEL_CHUNK_LENGTH {
ss = s[idx : idx+CHANNEL_CHUNK_LENGTH]
idx += CHANNEL_CHUNK_LENGTH
} else {
flag |= CHANNEL_FLAG_LAST
ss = s[idx : idx+ln]
}
glog.Debug("len:", len(ss), "flag:", flag)
ln -= len(ss)
b.Reset()
core.WriteUInt32LE(uint32(len(s)), b)
core.WriteUInt32LE(flag, b)
b.Write(ss)
c.channelSender.SendToChannel(channel, b.Bytes())
}
return ln, nil
}
func (c *Channels) process(channel string, s []byte) {
cli, ok := c.channels[channel]
if !ok {
glog.Warn("No found channel:", channel)
return
}
r := bytes.NewReader(s)
ln, _ := core.ReadUInt32LE(r)
flags, _ := core.ReadUInt32LE(r)
glog.Debugf("channel:%s length: %d, flags: %d", channel, ln, flags)
if flags&CHANNEL_FLAG_FIRST == 0 || flags&CHANNEL_FLAG_LAST == 0 {
if flags&CHANNEL_FLAG_FIRST != 0 {
c.buff.Reset()
}
b, _ := core.ReadBytes(r.Len(), r)
c.buff.Write(b)
if flags&CHANNEL_FLAG_LAST == 0 {
return
}
s = c.buff.Bytes()
} else {
s, _ = core.ReadBytes(r.Len(), r)
}
cli.t.Process(s)
}
+159
View File
@@ -0,0 +1,159 @@
package drdynvc
import (
"bytes"
"encoding/hex"
"io"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/plugin"
)
const (
ChannelName = plugin.DRDYNVC_SVC_CHANNEL_NAME
ChannelOption = plugin.CHANNEL_OPTION_INITIALIZED |
plugin.CHANNEL_OPTION_ENCRYPT_RDP
)
const (
MAX_DVC_CHANNELS = 20
)
const (
DYNVC_CREATE_REQ = 0x01
DYNVC_DATA_FIRST = 0x02
DYNVC_DATA = 0x03
DYNVC_CLOSE = 0x04
DYNVC_CAPABILITIES = 0x05
DYNVC_DATA_FIRST_COMPRESSED = 0x06
DYNVC_DATA_COMPRESSED = 0x07
DYNVC_SOFT_SYNC_REQUEST = 0x08
DYNVC_SOFT_SYNC_RESPONSE = 0x09
)
type ChannelClient struct {
}
type DvcClient struct {
w core.ChannelSender
channels map[string]ChannelClient
}
func NewDvcClient() *DvcClient {
return &DvcClient{
channels: make(map[string]ChannelClient, 100),
}
}
func (c *DvcClient) LoadAddin(f core.ChannelSender) {
}
type DvcHeader struct {
cmd uint8
sp uint8
cbChId uint8
}
func readHeader(r io.Reader) *DvcHeader {
value, _ := core.ReadUInt8(r)
cmd := (value & 0xf0) >> 4
sp := (value & 0x0c) >> 2
cbChId := (value & 0x03) >> 0
return &DvcHeader{cmd, sp, cbChId}
}
func (h *DvcHeader) serialize(channelId uint32) []byte {
b := &bytes.Buffer{}
core.WriteUInt8((h.cmd<<4)|(h.sp<<2)|h.cbChId, b)
if h.cbChId == 0 {
core.WriteUInt8(uint8(channelId), b)
} else if h.cbChId == 1 {
core.WriteUInt16LE(uint16(channelId), b)
} else {
core.WriteUInt32LE(channelId, b)
}
return b.Bytes()
}
func (c *DvcClient) Send(s []byte) (int, error) {
glog.Debug("len:", len(s), "data:", hex.EncodeToString(s))
name, _ := c.GetType()
return c.w.SendToChannel(name, s)
}
func (c *DvcClient) Sender(f core.ChannelSender) {
c.w = f
}
func (c *DvcClient) GetType() (string, uint32) {
return ChannelName, ChannelOption
}
func (c *DvcClient) Process(s []byte) {
glog.Debug("recv:", hex.EncodeToString(s))
r := bytes.NewReader(s)
hdr := readHeader(r)
glog.Infof("dvc: Cmd=0x%x, Sp=%d CbChId=%d all=%d", hdr.cmd, hdr.sp, hdr.cbChId, r.Len())
b, _ := core.ReadBytes(r.Len(), r)
switch hdr.cmd {
case DYNVC_CAPABILITIES:
glog.Info("DYNVC_CAPABILITIES")
c.processCapsPdu(hdr, b)
case DYNVC_CREATE_REQ:
glog.Info("DYNVC_CREATE_REQ")
c.processCreateReq(hdr, b)
case DYNVC_DATA_FIRST:
glog.Info("DYNVC_DATA_FIRST")
case DYNVC_DATA:
glog.Info("DYNVC_DATA")
case DYNVC_CLOSE:
glog.Info("DYNVC_CLOSE")
default:
glog.Errorf("type 0x%x not supported", hdr.cmd)
}
}
func (c *DvcClient) processCreateReq(hdr *DvcHeader, s []byte) {
r := bytes.NewReader(s)
channelId := readDvcId(r, hdr.cbChId)
name, _ := core.ReadBytes(r.Len(), r)
channelName := string(name)
glog.Infof("Server requests channelId=%d, name=%s", channelId, channelName)
//response
b := &bytes.Buffer{}
b.Write(hdr.serialize(channelId))
core.WriteUInt32LE(0, b)
c.Send(b.Bytes())
}
func readDvcId(r io.Reader, cbLen uint8) (id uint32) {
switch cbLen {
case 0:
i, _ := core.ReadUInt8(r)
id = uint32(i)
case 1:
i, _ := core.ReadUint16LE(r)
id = uint32(i)
default:
id, _ = core.ReadUInt32LE(r)
}
return
}
func (c *DvcClient) processCapsPdu(hdr *DvcHeader, s []byte) {
r := bytes.NewReader(s)
core.ReadUInt8(r)
ver, _ := core.ReadUint16LE(r)
glog.Infof("Server supports dvc=%d", ver)
hdr.cmd = DYNVC_CAPABILITIES
hdr.cbChId = 0
hdr.sp = 0
b := &bytes.Buffer{}
core.WriteUInt16LE(0x0050, b)
core.WriteUInt16LE(ver, b)
c.Send(b.Bytes())
}
+451
View File
@@ -0,0 +1,451 @@
// rail.go
package rail
import (
"bytes"
"encoding/hex"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/plugin"
)
const (
ChannelName = plugin.RAIL_SVC_CHANNEL_NAME
ChannelOption = plugin.CHANNEL_OPTION_INITIALIZED | plugin.CHANNEL_OPTION_ENCRYPT_RDP |
plugin.CHANNEL_OPTION_COMPRESS_RDP | plugin.CHANNEL_OPTION_SHOW_PROTOCOL
)
const (
TS_RAIL_ORDER_EXEC = 0x0001
TS_RAIL_ORDER_ACTIVATE = 0x0002
TS_RAIL_ORDER_SYSPARAM = 0x0003
TS_RAIL_ORDER_SYSCOMMAND = 0x0004
TS_RAIL_ORDER_HANDSHAKE = 0x0005
TS_RAIL_ORDER_NOTIFY_EVENT = 0x0006
TS_RAIL_ORDER_WINDOWMOVE = 0x0008
TS_RAIL_ORDER_LOCALMOVESIZE = 0x0009
TS_RAIL_ORDER_MINMAXINFO = 0x000A
TS_RAIL_ORDER_CLIENTSTATUS = 0x000B
TS_RAIL_ORDER_SYSMENU = 0x000C
TS_RAIL_ORDER_LANGBARINFO = 0x000D
TS_RAIL_ORDER_GET_APPID_REQ = 0x000E
TS_RAIL_ORDER_GET_APPID_RESP = 0x000F
TS_RAIL_ORDER_TASKBARINFO = 0x0010
TS_RAIL_ORDER_LANGUAGEIMEINFO = 0x0011
TS_RAIL_ORDER_COMPARTMENTINFO = 0x0012
TS_RAIL_ORDER_HANDSHAKE_EX = 0x0013
TS_RAIL_ORDER_ZORDER_SYNC = 0x0014
TS_RAIL_ORDER_CLOAK = 0x0015
TS_RAIL_ORDER_POWER_DISPLAY_REQUEST = 0x0016
TS_RAIL_ORDER_SNAP_ARRANGE = 0x0017
TS_RAIL_ORDER_GET_APPID_RESP_EX = 0x0018
TS_RAIL_ORDER_EXEC_RESULT = 0x0080
)
type RailClient struct {
w core.ChannelSender
DesktopWidth uint16
DesktopHeight uint16
RemoteApplicationProgram string
ShellWorkingDirectory string
RemoteApplicationCmdLine string
}
func NewClient() *RailClient {
return &RailClient{
DesktopWidth: 800,
DesktopHeight: 600,
RemoteApplicationProgram: "calc",
ShellWorkingDirectory: "/tmp",
}
}
type RailPDUHeader struct {
OrderType uint16 `struc:"little"`
OrderLength uint16 `struc:"little"`
}
func NewRailPDUHeader(mType, ln uint16) *RailPDUHeader {
return &RailPDUHeader{
OrderType: mType,
OrderLength: ln,
}
}
func (h *RailPDUHeader) serialize() []byte {
b := &bytes.Buffer{}
core.WriteUInt16LE(h.OrderType, b)
core.WriteUInt16LE(h.OrderLength, b)
return b.Bytes()
}
func (c *RailClient) sendData(mType uint16, ln int, s []byte) {
glog.Debug(ln, ":ln:", len(s), "data:", hex.EncodeToString(s))
header := NewRailPDUHeader(mType, uint16(ln))
b := &bytes.Buffer{}
core.WriteBytes(header.serialize(), b)
core.WriteBytes(s, b)
c.Send(b.Bytes())
}
func (c *RailClient) Send(s []byte) (int, error) {
glog.Debug("len:", len(s), "data:", hex.EncodeToString(s))
name, _ := c.GetType()
return c.w.SendToChannel(name, s)
}
func (c *RailClient) Sender(f core.ChannelSender) {
c.w = f
}
func (c *RailClient) GetType() (string, uint32) {
return ChannelName, ChannelOption
}
func (c *RailClient) Process(s []byte) {
glog.Debug("recv:", hex.EncodeToString(s))
r := bytes.NewReader(s)
msgType, _ := core.ReadUint16LE(r)
length, _ := core.ReadUint16LE(r)
glog.Infof("rail: type=0x%x length=%d, all=%d", msgType, length, r.Len())
b, _ := core.ReadBytes(int(length), r)
glog.Info("b:", hex.EncodeToString(b))
switch msgType {
case TS_RAIL_ORDER_HANDSHAKE:
glog.Info("TS_RAIL_ORDER_HANDSHAKE")
c.processOrderHandshake(b)
case TS_RAIL_ORDER_SYSPARAM:
glog.Info("TS_RAIL_ORDER_SYSPARAM")
c.processOrderSysparam(b)
case TS_RAIL_ORDER_EXEC_RESULT:
glog.Info("TS_RAIL_ORDER_EXEC_RESULT")
c.processExecResult(b)
default:
glog.Errorf("type 0x%x not supported", msgType)
}
}
func (c *RailClient) processOrderHandshake(b []byte) {
r := bytes.NewReader(b)
buildNumber, _ := core.ReadUInt32LE(r)
glog.Info("buildNumber:", buildNumber)
//send client info
c.sendClientStatus()
//send client systemparam
c.sendClientSystemparam()
//send client execute
c.sendClientExecute()
}
const (
TS_RAIL_CLIENTSTATUS_ALLOWLOCALMOVESIZE = 0x00000001
TS_RAIL_CLIENTSTATUS_AUTORECONNECT = 0x00000002
TS_RAIL_CLIENTSTATUS_ZORDER_SYNC = 0x00000004
TS_RAIL_CLIENTSTATUS_WINDOW_RESIZE_MARGIN_SUPPORTED = 0x00000010
TS_RAIL_CLIENTSTATUS_HIGH_DPI_ICONS_SUPPORTED = 0x00000020
TS_RAIL_CLIENTSTATUS_APPBAR_REMOTING_SUPPORTED = 0x00000040
TS_RAIL_CLIENTSTATUS_POWER_DISPLAY_REQUEST_SUPPORTED = 0x00000080
TS_RAIL_CLIENTSTATUS_GET_APPID_RESPONSE_EX_SUPPORTED = 0x00000100
TS_RAIL_CLIENTSTATUS_BIDIRECTIONAL_CLOAK_SUPPORTED = 0x00000200
)
func (c *RailClient) sendClientStatus() {
glog.Info("Send client Status")
var flags uint32 = TS_RAIL_CLIENTSTATUS_ALLOWLOCALMOVESIZE
//if (settings->AutoReconnectionEnabled)
//clientStatus.flags |= TS_RAIL_CLIENTSTATUS_AUTORECONNECT;
flags |= TS_RAIL_CLIENTSTATUS_ZORDER_SYNC
flags |= TS_RAIL_CLIENTSTATUS_WINDOW_RESIZE_MARGIN_SUPPORTED
flags |= TS_RAIL_CLIENTSTATUS_APPBAR_REMOTING_SUPPORTED
flags |= TS_RAIL_CLIENTSTATUS_POWER_DISPLAY_REQUEST_SUPPORTED
flags |= TS_RAIL_CLIENTSTATUS_BIDIRECTIONAL_CLOAK_SUPPORTED
b := &bytes.Buffer{}
core.WriteUInt32LE(flags, b)
c.sendData(TS_RAIL_ORDER_CLIENTSTATUS, 4, b.Bytes())
}
const (
SPI_SET_SCREEN_SAVE_ACTIVE = 0x00000011
SPI_SET_SCREEN_SAVE_SECURE = 0x00000077
)
const (
/*Bit mask values for SPI_ parameters*/
SPI_MASK_SET_DRAG_FULL_WINDOWS = 0x00000001
SPI_MASK_SET_KEYBOARD_CUES = 0x00000002
SPI_MASK_SET_KEYBOARD_PREF = 0x00000004
SPI_MASK_SET_MOUSE_BUTTON_SWAP = 0x00000008
SPI_MASK_SET_WORK_AREA = 0x00000010
SPI_MASK_DISPLAY_CHANGE = 0x00000020
SPI_MASK_TASKBAR_POS = 0x00000040
SPI_MASK_SET_HIGH_CONTRAST = 0x00000080
SPI_MASK_SET_SCREEN_SAVE_ACTIVE = 0x00000100
SPI_MASK_SET_SET_SCREEN_SAVE_SECURE = 0x00000200
SPI_MASK_SET_CARET_WIDTH = 0x00000400
SPI_MASK_SET_STICKY_KEYS = 0x00000800
SPI_MASK_SET_TOGGLE_KEYS = 0x00001000
SPI_MASK_SET_FILTER_KEYS = 0x00002000
)
const (
SPI_SET_DRAG_FULL_WINDOWS = 0x00000025
SPI_SET_KEYBOARD_CUES = 0x0000100B
SPI_SET_KEYBOARD_PREF = 0x00000045
SPI_SET_MOUSE_BUTTON_SWAP = 0x00000021
SPI_SET_WORK_AREA = 0x0000002F
SPI_DISPLAY_CHANGE = 0x0000F001
SPI_TASKBAR_POS = 0x0000F000
SPI_SET_HIGH_CONTRAST = 0x00000043
SPI_SETCARETWIDTH = 0x00002007
SPI_SETSTICKYKEYS = 0x0000003B
SPI_SETTOGGLEKEYS = 0x00000035
SPI_SETFILTERKEYS = 0x00000033
)
type TsFilterKeys struct {
Flags uint32
WaitTime uint32
DelayTime uint32
RepeatTime uint32
BounceTime uint32
}
type RailHighContrast struct {
flags uint32
colorSchemeLength uint32
colorScheme string
}
type Rectangle16 struct {
left uint16
top uint16
right uint16
bottom uint16
}
type RailSysparamOrder struct {
param uint32
params uint32
dragFullWindows uint8
keyboardCues uint8
keyboardPref uint8
mouseButtonSwap uint8
workArea Rectangle16
displayChange Rectangle16
taskbarPos Rectangle16
highContrast RailHighContrast
caretWidth uint32
stickyKeys uint32
toggleKeys uint32
filterKeys TsFilterKeys
setScreenSaveActive uint8
setScreenSaveSecure uint8
}
func (c *RailClient) sendClientSystemparam() {
glog.Info("Send client Systemparam")
var sp RailSysparamOrder
sp.params = 0
sp.params |= SPI_MASK_SET_HIGH_CONTRAST
sp.highContrast.colorScheme = ""
sp.highContrast.colorSchemeLength = 0
sp.highContrast.flags = 0x7E
sp.params |= SPI_MASK_SET_MOUSE_BUTTON_SWAP
sp.mouseButtonSwap = 0
sp.params |= SPI_MASK_SET_KEYBOARD_PREF
sp.keyboardPref = 0
sp.params |= SPI_MASK_SET_DRAG_FULL_WINDOWS
sp.dragFullWindows = 0
sp.params |= SPI_MASK_SET_KEYBOARD_CUES
sp.keyboardCues = 0
sp.params |= SPI_MASK_SET_WORK_AREA
sp.workArea.left = 0
sp.workArea.top = 0
sp.workArea.right = c.DesktopWidth
sp.workArea.bottom = c.DesktopHeight
if sp.params&SPI_MASK_SET_HIGH_CONTRAST != 0 {
sp.param = SPI_SET_HIGH_CONTRAST
c.sendOneClientSysparam(&sp)
}
if sp.params&SPI_MASK_TASKBAR_POS != 0 {
sp.param = SPI_TASKBAR_POS
c.sendOneClientSysparam(&sp)
}
if sp.params&SPI_MASK_SET_MOUSE_BUTTON_SWAP != 0 {
sp.param = SPI_SET_MOUSE_BUTTON_SWAP
c.sendOneClientSysparam(&sp)
}
if sp.params&SPI_MASK_SET_KEYBOARD_PREF != 0 {
sp.param = SPI_SET_KEYBOARD_PREF
c.sendOneClientSysparam(&sp)
}
if sp.params&SPI_MASK_SET_DRAG_FULL_WINDOWS != 0 {
sp.param = SPI_SET_DRAG_FULL_WINDOWS
c.sendOneClientSysparam(&sp)
}
if sp.params&SPI_MASK_SET_KEYBOARD_CUES != 0 {
sp.param = SPI_SET_KEYBOARD_CUES
c.sendOneClientSysparam(&sp)
}
if sp.params&SPI_MASK_SET_WORK_AREA != 0 {
sp.param = SPI_SET_WORK_AREA
glog.Debug("SPI_SET_WORK_AREA")
c.sendOneClientSysparam(&sp)
}
}
func (c *RailClient) sendOneClientSysparam(sp *RailSysparamOrder) {
length := 0
b := &bytes.Buffer{}
core.WriteUInt32LE(sp.param, b)
switch sp.param {
case SPI_SET_DRAG_FULL_WINDOWS:
core.WriteUInt8(sp.dragFullWindows, b)
case SPI_SET_KEYBOARD_CUES:
core.WriteUInt8(sp.keyboardCues, b)
case SPI_SET_KEYBOARD_PREF:
core.WriteUInt8(sp.keyboardPref, b)
case SPI_SET_MOUSE_BUTTON_SWAP:
core.WriteUInt8(sp.mouseButtonSwap, b)
case SPI_SET_WORK_AREA:
core.WriteUInt16LE(sp.workArea.left, b)
core.WriteUInt16LE(sp.workArea.top, b)
core.WriteUInt16LE(sp.workArea.right, b)
core.WriteUInt16LE(sp.workArea.bottom, b)
case SPI_DISPLAY_CHANGE:
core.WriteUInt16LE(sp.displayChange.left, b)
core.WriteUInt16LE(sp.displayChange.top, b)
core.WriteUInt16LE(sp.displayChange.right, b)
core.WriteUInt16LE(sp.displayChange.bottom, b)
case SPI_TASKBAR_POS:
core.WriteUInt16LE(sp.taskbarPos.left, b)
core.WriteUInt16LE(sp.taskbarPos.top, b)
core.WriteUInt16LE(sp.taskbarPos.right, b)
core.WriteUInt16LE(sp.taskbarPos.bottom, b)
case SPI_SET_HIGH_CONTRAST:
core.WriteUInt32LE(sp.highContrast.flags, b)
core.WriteUInt32LE(sp.highContrast.colorSchemeLength, b)
data := core.UnicodeEncode(sp.highContrast.colorScheme)
core.WriteBytes(data, b)
case SPI_SETFILTERKEYS:
core.WriteUInt32LE(sp.filterKeys.Flags, b)
core.WriteUInt32LE(sp.filterKeys.WaitTime, b)
core.WriteUInt32LE(sp.filterKeys.DelayTime, b)
core.WriteUInt32LE(sp.filterKeys.RepeatTime, b)
core.WriteUInt32LE(sp.filterKeys.BounceTime, b)
case SPI_SETSTICKYKEYS:
core.WriteUInt32LE(sp.stickyKeys, b)
case SPI_SETCARETWIDTH:
core.WriteUInt32LE(sp.caretWidth, b)
case SPI_SETTOGGLEKEYS:
core.WriteUInt32LE(sp.toggleKeys, b)
case SPI_MASK_SET_SET_SCREEN_SAVE_SECURE:
core.WriteUInt8(sp.setScreenSaveSecure, b)
case SPI_MASK_SET_SCREEN_SAVE_ACTIVE:
core.WriteUInt8(sp.setScreenSaveActive, b)
default:
glog.Error("ERROR_BAD_ARGUMENTS")
return
}
c.sendData(TS_RAIL_ORDER_SYSPARAM, length+b.Len(), b.Bytes())
}
type RailExecOrder struct {
flags uint16
RemoteApplicationProgram string
RemoteApplicationWorkingDir string
RemoteApplicationArguments string
}
func (c *RailClient) sendClientExecute() {
glog.Info("Send Client Execute")
var exec RailExecOrder
//exec.flags = TS_RAIL_EXEC_FLAG_EXPAND_ARGUMENTS
exec.RemoteApplicationProgram = c.RemoteApplicationProgram
exec.RemoteApplicationWorkingDir = c.ShellWorkingDirectory
exec.RemoteApplicationArguments = c.RemoteApplicationCmdLine
program := core.UnicodeEncode(exec.RemoteApplicationProgram)
workdir := core.UnicodeEncode(exec.RemoteApplicationWorkingDir)
arguments := core.UnicodeEncode(exec.RemoteApplicationArguments)
length := 4
b := &bytes.Buffer{}
core.WriteUInt16LE(exec.flags, b)
core.WriteUInt16LE(uint16(len(program)), b)
core.WriteUInt16LE(uint16(len(workdir)), b)
core.WriteUInt16LE(uint16(len(arguments)), b)
core.WriteBytes(program, b)
core.WriteBytes(workdir, b)
core.WriteBytes(arguments, b)
length += b.Len()
c.sendData(TS_RAIL_ORDER_EXEC, length, b.Bytes())
}
func (c *RailClient) processOrderSysparam(b []byte) {
r := bytes.NewReader(b)
systemParam, _ := core.ReadUInt32LE(r)
body, _ := core.ReadUInt8(r)
glog.Infof("systemParam:0x%x, body:%d", systemParam, body)
}
const (
//The Client Execute request was successful and the requested application or file has been launched.
RAIL_EXEC_S_OK = 0x0000
//The Client Execute request could not be satisfied because the server is not monitoring the current input desktop.
RAIL_EXEC_E_HOOK_NOT_LOADED = 0x0001
//The Execute request could not be satisfied because the request PDU was malformed.
RAIL_EXEC_E_DECODE_FAILED = 0x0002
//The Client Execute request could not be satisfied because the requested application was blocked by policy from being launched on the server.
RAIL_EXEC_E_NOT_IN_ALLOWLIST = 0x0003
//The Client Execute request could not be satisfied because the application or file path could not be found.
RAIL_EXEC_E_FILE_NOT_FOUND = 0x0005
//The Client Execute request could not be satisfied because an unspecified error occurred on the server.
RAIL_EXEC_E_FAIL = 0x0006
//The Client Execute request could not be satisfied because the remote session is locked.
RAIL_EXEC_E_SESSION_LOCKED = 0x0007
)
func (c *RailClient) processExecResult(b []byte) {
r := bytes.NewReader(b)
flags, _ := core.ReadUint16LE(r)
execResult, _ := core.ReadUint16LE(r)
rawResult, _ := core.ReadUInt32LE(r)
core.ReadUint16LE(r)
exeOrFileLength, _ := core.ReadUint16LE(r)
exeOrFile, _ := core.ReadBytes(r.Len(), r)
glog.Info("flags:", flags, "execResult:", execResult, "rawResult:", rawResult)
glog.Info("length:", exeOrFileLength, "file:", core.UnicodeDecode(exeOrFile))
}
+9
View File
@@ -0,0 +1,9 @@
package rdpgfx
import (
"github.com/shadow1ng/fscan/mylib/grdp/plugin"
)
const (
ChannelName = plugin.RDPGFX_DVC_CHANNEL_NAME
)
+183
View File
@@ -0,0 +1,183 @@
package lic
import (
"io"
"github.com/shadow1ng/fscan/mylib/grdp/core"
)
const (
LICENSE_REQUEST = 0x01
PLATFORM_CHALLENGE = 0x02
NEW_LICENSE = 0x03
UPGRADE_LICENSE = 0x04
LICENSE_INFO = 0x12
NEW_LICENSE_REQUEST = 0x13
PLATFORM_CHALLENGE_RESPONSE = 0x15
ERROR_ALERT = 0xFF
)
// error code
const (
ERR_INVALID_SERVER_CERTIFICATE = 0x00000001
ERR_NO_LICENSE = 0x00000002
ERR_INVALID_SCOPE = 0x00000004
ERR_NO_LICENSE_SERVER = 0x00000006
STATUS_VALID_CLIENT = 0x00000007
ERR_INVALID_CLIENT = 0x00000008
ERR_INVALID_PRODUCTID = 0x0000000B
ERR_INVALID_MESSAGE_LEN = 0x0000000C
ERR_INVALID_MAC = 0x00000003
)
// state transition
const (
ST_TOTAL_ABORT = 0x00000001
ST_NO_TRANSITION = 0x00000002
ST_RESET_PHASE_TO_START = 0x00000003
ST_RESEND_LAST_MESSAGE = 0x00000004
)
/*
"""
@summary: Binary blob data type
@see: http://msdn.microsoft.com/en-us/library/cc240481.aspx
"""
*/
type BinaryBlobType uint16
const (
BB_ANY_BLOB = 0x0000
BB_DATA_BLOB = 0x0001
BB_RANDOM_BLOB = 0x0002
BB_CERTIFICATE_BLOB = 0x0003
BB_ERROR_BLOB = 0x0004
BB_ENCRYPTED_DATA_BLOB = 0x0009
BB_KEY_EXCHG_ALG_BLOB = 0x000D
BB_SCOPE_BLOB = 0x000E
BB_CLIENT_USER_NAME_BLOB = 0x000F
BB_CLIENT_MACHINE_NAME_BLOB = 0x0010
)
type ErrorMessage struct {
DwErrorCode uint32
DwStateTransaction uint32
Blob []byte
}
func readErrorMessage(r io.Reader) *ErrorMessage {
m := &ErrorMessage{}
m.DwErrorCode, _ = core.ReadUInt32LE(r)
m.DwStateTransaction, _ = core.ReadUInt32LE(r)
return m
}
type LicensePacket struct {
BMsgtype uint8
Flag uint8
WMsgSize uint16
LicensingMessage interface{}
}
func ReadLicensePacket(r io.Reader) *LicensePacket {
l := &LicensePacket{}
l.BMsgtype, _ = core.ReadUInt8(r)
l.Flag, _ = core.ReadUInt8(r)
l.WMsgSize, _ = core.ReadUint16LE(r)
switch l.BMsgtype {
case ERROR_ALERT:
l.LicensingMessage = readErrorMessage(r)
default:
l.LicensingMessage, _ = core.ReadBytes(int(l.WMsgSize-4), r)
}
return l
}
/*
"""
@summary: Blob use by license manager to exchange security data
@see: http://msdn.microsoft.com/en-us/library/cc240481.aspx
"""
*/
type LicenseBinaryBlob struct {
WBlobType uint16 `struc:"little"`
WBlobLen uint16 `struc:"little"`
BlobData []byte `struc:"sizefrom=WBlobLen"`
}
func NewLicenseBinaryBlob(WBlobType uint16) *LicenseBinaryBlob {
return &LicenseBinaryBlob{}
}
/*
"""
@summary: License server product information
@see: http://msdn.microsoft.com/en-us/library/cc241915.aspx
"""
*/
type ProductInformation struct {
DwVersion uint32 `struc:"little"`
CbCompanyName uint32 `struc:"little"`
//may contain "Microsoft Corporation" from server microsoft
PbCompanyName []byte `struc:"sizefrom=CbCompanyName"`
CbProductId uint32 `struc:"little"`
//may contain "A02" from microsoft license server
PbProductId []byte `struc:"sizefrom=CbProductId"`
}
/*
@summary: Send by server to signal license request
server -> client
@see: http://msdn.microsoft.com/en-us/library/cc241914.aspx
*/
type ServerLicenseRequest struct {
ServerRandom []byte `struc:"[32]byte"`
ProductInfo ProductInformation `struc:"little"`
KeyExchangeList LicenseBinaryBlob `struc:"little"`
ServerCertificate LicenseBinaryBlob `struc:"little"`
//ScopeList ScopeList
}
/*
@summary: Send by client to ask new license for client.
RDPY doesn'support license reuse, need it in futur version
@see: http://msdn.microsoft.com/en-us/library/cc241918.aspx
#RSA and must be only RSA
#pure microsoft client ;-)
#http://msdn.microsoft.com/en-us/library/1040af38-c733-4fb3-acd1-8db8cc979eda#id10
*/
type ClientNewLicenseRequest struct {
PreferredKeyExchangeAlg uint32 `struc:"little"`
PlatformId uint32 `struc:"little"`
ClientRandom []byte `struc:"[32]byte"`
EncryptedPreMasterSecret LicenseBinaryBlob `struc:"little"`
ClientUserName LicenseBinaryBlob `struc:"little"`
ClientMachineName LicenseBinaryBlob `struc:"little"`
}
/*
@summary: challenge send from server to client
@see: http://msdn.microsoft.com/en-us/library/cc241921.aspx
*/
type ServerPlatformChallenge struct {
ConnectFlags uint32
EncryptedPlatformChallenge LicenseBinaryBlob
MACData [16]byte
}
/*
"""
@summary: client challenge response
@see: http://msdn.microsoft.com/en-us/library/cc241922.aspx
"""
*/
type ClientPLatformChallengeResponse struct {
EncryptedPlatformChallengeResponse LicenseBinaryBlob
EncryptedHWID LicenseBinaryBlob
MACData []byte //[16]byte
}
+99
View File
@@ -0,0 +1,99 @@
package nla
import (
"encoding/asn1"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
)
type NegoToken struct {
Data []byte `asn1:"explicit,tag:0"`
}
type TSRequest struct {
Version int `asn1:"explicit,tag:0"`
NegoTokens []NegoToken `asn1:"optional,explicit,tag:1"`
AuthInfo []byte `asn1:"optional,explicit,tag:2"`
PubKeyAuth []byte `asn1:"optional,explicit,tag:3"`
//ErrorCode int `asn1:"optional,explicit,tag:4"`
}
type TSCredentials struct {
CredType int `asn1:"explicit,tag:0"`
Credentials []byte `asn1:"explicit,tag:1"`
}
type TSPasswordCreds struct {
DomainName []byte `asn1:"explicit,tag:0"`
UserName []byte `asn1:"explicit,tag:1"`
Password []byte `asn1:"explicit,tag:2"`
}
type TSCspDataDetail struct {
KeySpec int `asn1:"explicit,tag:0"`
CardName string `asn1:"explicit,tag:1"`
ReaderName string `asn1:"explicit,tag:2"`
ContainerName string `asn1:"explicit,tag:3"`
CspName string `asn1:"explicit,tag:4"`
}
type TSSmartCardCreds struct {
Pin string `asn1:"explicit,tag:0"`
CspData []TSCspDataDetail `asn1:"explicit,tag:1"`
UserHint string `asn1:"explicit,tag:2"`
DomainHint string `asn1:"explicit,tag:3"`
}
func EncodeDERTRequest(msgs []Message, authInfo []byte, pubKeyAuth []byte) []byte {
req := TSRequest{
Version: 2,
}
if len(msgs) > 0 {
req.NegoTokens = make([]NegoToken, 0, len(msgs))
}
for _, msg := range msgs {
token := NegoToken{msg.Serialize()}
req.NegoTokens = append(req.NegoTokens, token)
}
if len(authInfo) > 0 {
req.AuthInfo = authInfo
}
if len(pubKeyAuth) > 0 {
req.PubKeyAuth = pubKeyAuth
}
result, err := asn1.Marshal(req)
if err != nil {
glog.Error(err)
}
return result
}
func DecodeDERTRequest(s []byte) (*TSRequest, error) {
treq := &TSRequest{}
_, err := asn1.Unmarshal(s, treq)
return treq, err
}
func EncodeDERTCredentials(domain, username, password []byte) []byte {
tpas := TSPasswordCreds{domain, username, password}
result, err := asn1.Marshal(tpas)
if err != nil {
glog.Error(err)
}
tcre := TSCredentials{1, result}
result, err = asn1.Marshal(tcre)
if err != nil {
glog.Error(err)
}
return result
}
func DecodeDERTCredentials(s []byte) (*TSCredentials, error) {
tcre := &TSCredentials{}
_, err := asn1.Unmarshal(s, tcre)
return tcre, err
}
+46
View File
@@ -0,0 +1,46 @@
package nla
import (
"crypto/hmac"
"crypto/md5"
"crypto/rc4"
"strings"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"golang.org/x/crypto/md4"
)
func MD4(data []byte) []byte {
h := md4.New()
h.Write(data)
return h.Sum(nil)
}
func MD5(data []byte) []byte {
h := md5.New()
h.Write(data)
return h.Sum(nil)
}
func HMAC_MD5(key, data []byte) []byte {
h := hmac.New(md5.New, key)
h.Write(data)
return h.Sum(nil)
}
// Version 2 of NTLM hash function
func NTOWFv2(password, user, domain string) []byte {
return HMAC_MD5(MD4(core.UnicodeEncode(password)), core.UnicodeEncode(strings.ToUpper(user)+domain))
}
// Same as NTOWFv2
func LMOWFv2(password, user, domain string) []byte {
return NTOWFv2(password, user, domain)
}
func RC4K(key, src []byte) []byte {
result := make([]byte, len(src))
rc4obj, _ := rc4.NewCipher(key)
rc4obj.XORKeyStream(result, src)
return result
}
+515
View File
@@ -0,0 +1,515 @@
package nla
import (
"bytes"
"crypto/md5"
"crypto/rc4"
"encoding/binary"
"encoding/hex"
"time"
"github.com/lunixbochs/struc"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
)
const (
WINDOWS_MINOR_VERSION_0 = 0x00
WINDOWS_MINOR_VERSION_1 = 0x01
WINDOWS_MINOR_VERSION_2 = 0x02
WINDOWS_MINOR_VERSION_3 = 0x03
WINDOWS_MAJOR_VERSION_5 = 0x05
WINDOWS_MAJOR_VERSION_6 = 0x06
NTLMSSP_REVISION_W2K3 = 0x0F
)
const (
MsvAvEOL = 0x0000
MsvAvNbComputerName = 0x0001
MsvAvNbDomainName = 0x0002
MsvAvDnsComputerName = 0x0003
MsvAvDnsDomainName = 0x0004
MsvAvDnsTreeName = 0x0005
MsvAvFlags = 0x0006
MsvAvTimestamp = 0x0007
MsvAvSingleHost = 0x0008
MsvAvTargetName = 0x0009
MsvChannelBindings = 0x000A
)
type AVPair struct {
Id uint16 `struc:"little"`
Len uint16 `struc:"little,sizeof=Value"`
Value []byte `struc:"little"`
}
const (
NTLMSSP_NEGOTIATE_56 = 0x80000000
NTLMSSP_NEGOTIATE_KEY_EXCH = 0x40000000
NTLMSSP_NEGOTIATE_128 = 0x20000000
NTLMSSP_NEGOTIATE_VERSION = 0x02000000
NTLMSSP_NEGOTIATE_TARGET_INFO = 0x00800000
NTLMSSP_REQUEST_NON_NT_SESSION_KEY = 0x00400000
NTLMSSP_NEGOTIATE_IDENTIFY = 0x00100000
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY = 0x00080000
NTLMSSP_TARGET_TYPE_SERVER = 0x00020000
NTLMSSP_TARGET_TYPE_DOMAIN = 0x00010000
NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000
NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED = 0x00002000
NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED = 0x00001000
NTLMSSP_NEGOTIATE_NTLM = 0x00000200
NTLMSSP_NEGOTIATE_LM_KEY = 0x00000080
NTLMSSP_NEGOTIATE_DATAGRAM = 0x00000040
NTLMSSP_NEGOTIATE_SEAL = 0x00000020
NTLMSSP_NEGOTIATE_SIGN = 0x00000010
NTLMSSP_REQUEST_TARGET = 0x00000004
NTLM_NEGOTIATE_OEM = 0x00000002
NTLMSSP_NEGOTIATE_UNICODE = 0x00000001
)
type NVersion struct {
ProductMajorVersion uint8 `struc:"little"`
ProductMinorVersion uint8 `struc:"little"`
ProductBuild uint16 `struc:"little"`
Reserved [3]byte `struc:"little"`
NTLMRevisionCurrent uint8 `struc:"little"`
}
func NewNVersion() NVersion {
return NVersion{
ProductMajorVersion: WINDOWS_MAJOR_VERSION_6,
ProductMinorVersion: WINDOWS_MINOR_VERSION_0,
ProductBuild: 6002,
NTLMRevisionCurrent: NTLMSSP_REVISION_W2K3,
}
}
type Message interface {
Serialize() []byte
}
type NegotiateMessage struct {
Signature [8]byte `struc:"little"`
MessageType uint32 `struc:"little"`
NegotiateFlags uint32 `struc:"little"`
DomainNameLen uint16 `struc:"little"`
DomainNameMaxLen uint16 `struc:"little"`
DomainNameBufferOffset uint32 `struc:"little"`
WorkstationLen uint16 `struc:"little"`
WorkstationMaxLen uint16 `struc:"little"`
WorkstationBufferOffset uint32 `struc:"little"`
Version NVersion `struc:"little"`
Payload [32]byte `struc:"skip"`
}
func NewNegotiateMessage() *NegotiateMessage {
return &NegotiateMessage{
Signature: [8]byte{'N', 'T', 'L', 'M', 'S', 'S', 'P', 0x00},
MessageType: 0x00000001,
}
}
func (m *NegotiateMessage) Serialize() []byte {
if (m.NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) != 0 {
m.Version = NewNVersion()
}
buff := &bytes.Buffer{}
struc.Pack(buff, m)
return buff.Bytes()
}
type ChallengeMessage struct {
Signature []byte `struc:"[8]byte"`
MessageType uint32 `struc:"little"`
TargetNameLen uint16 `struc:"little"`
TargetNameMaxLen uint16 `struc:"little"`
TargetNameBufferOffset uint32 `struc:"little"`
NegotiateFlags uint32 `struc:"little"`
ServerChallenge [8]byte `struc:"little"`
Reserved [8]byte `struc:"little"`
TargetInfoLen uint16 `struc:"little"`
TargetInfoMaxLen uint16 `struc:"little"`
TargetInfoBufferOffset uint32 `struc:"little"`
Version NVersion `struc:"skip"`
Payload []byte `struc:"skip"`
}
func (m *ChallengeMessage) Serialize() []byte {
buff := &bytes.Buffer{}
struc.Pack(buff, m)
if (m.NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) != 0 {
struc.Pack(buff, m.Version)
}
buff.Write(m.Payload)
return buff.Bytes()
}
func NewChallengeMessage() *ChallengeMessage {
return &ChallengeMessage{
Signature: []byte{'N', 'T', 'L', 'M', 'S', 'S', 'P', 0x00},
MessageType: 0x00000002,
}
}
// total len - payload len
func (m *ChallengeMessage) BaseLen() uint32 {
return 56
}
func (m *ChallengeMessage) getTargetInfo() []byte {
if m.TargetInfoLen == 0 {
return make([]byte, 0)
}
offset := m.BaseLen()
start := m.TargetInfoBufferOffset - offset
return m.Payload[start : start+uint32(m.TargetInfoLen)]
}
func (m *ChallengeMessage) getTargetName() []byte {
if m.TargetNameLen == 0 {
return make([]byte, 0)
}
offset := m.BaseLen()
start := m.TargetNameBufferOffset - offset
return m.Payload[start : start+uint32(m.TargetNameLen)]
}
func (m *ChallengeMessage) getTargetInfoTimestamp(data []byte) []byte {
r := bytes.NewReader(data)
for r.Len() > 0 {
avPair := &AVPair{}
struc.Unpack(r, avPair)
if avPair.Id == MsvAvTimestamp {
return avPair.Value
}
if avPair.Id == MsvAvEOL {
break
}
}
return nil
}
type AuthenticateMessage struct {
Signature [8]byte
MessageType uint32 `struc:"little"`
LmChallengeResponseLen uint16 `struc:"little"`
LmChallengeResponseMaxLen uint16 `struc:"little"`
LmChallengeResponseBufferOffset uint32 `struc:"little"`
NtChallengeResponseLen uint16 `struc:"little"`
NtChallengeResponseMaxLen uint16 `struc:"little"`
NtChallengeResponseBufferOffset uint32 `struc:"little"`
DomainNameLen uint16 `struc:"little"`
DomainNameMaxLen uint16 `struc:"little"`
DomainNameBufferOffset uint32 `struc:"little"`
UserNameLen uint16 `struc:"little"`
UserNameMaxLen uint16 `struc:"little"`
UserNameBufferOffset uint32 `struc:"little"`
WorkstationLen uint16 `struc:"little"`
WorkstationMaxLen uint16 `struc:"little"`
WorkstationBufferOffset uint32 `struc:"little"`
EncryptedRandomSessionLen uint16 `struc:"little"`
EncryptedRandomSessionMaxLen uint16 `struc:"little"`
EncryptedRandomSessionBufferOffset uint32 `struc:"little"`
NegotiateFlags uint32 `struc:"little"`
Version NVersion `struc:"little"`
MIC [16]byte `struc:"little"`
Payload []byte `struc:"skip"`
}
func (m *AuthenticateMessage) BaseLen() uint32 {
return 88
}
func NewAuthenticateMessage(negFlag uint32, domain, user, workstation []byte,
lmchallResp, ntchallResp, enRandomSessKey []byte) *AuthenticateMessage {
msg := &AuthenticateMessage{
Signature: [8]byte{'N', 'T', 'L', 'M', 'S', 'S', 'P', 0x00},
MessageType: 0x00000003,
NegotiateFlags: negFlag,
}
payloadBuff := &bytes.Buffer{}
msg.LmChallengeResponseLen = uint16(len(lmchallResp))
msg.LmChallengeResponseMaxLen = msg.LmChallengeResponseLen
msg.LmChallengeResponseBufferOffset = msg.BaseLen()
payloadBuff.Write(lmchallResp)
msg.NtChallengeResponseLen = uint16(len(ntchallResp))
msg.NtChallengeResponseMaxLen = msg.NtChallengeResponseLen
msg.NtChallengeResponseBufferOffset = msg.LmChallengeResponseBufferOffset + uint32(msg.LmChallengeResponseLen)
payloadBuff.Write(ntchallResp)
msg.DomainNameLen = uint16(len(domain))
msg.DomainNameMaxLen = msg.DomainNameLen
msg.DomainNameBufferOffset = msg.NtChallengeResponseBufferOffset + uint32(msg.NtChallengeResponseLen)
payloadBuff.Write(domain)
msg.UserNameLen = uint16(len(user))
msg.UserNameMaxLen = msg.UserNameLen
msg.UserNameBufferOffset = msg.DomainNameBufferOffset + uint32(msg.DomainNameLen)
payloadBuff.Write(user)
msg.WorkstationLen = uint16(len(workstation))
msg.WorkstationMaxLen = msg.WorkstationLen
msg.WorkstationBufferOffset = msg.UserNameBufferOffset + uint32(msg.UserNameLen)
payloadBuff.Write(workstation)
msg.EncryptedRandomSessionLen = uint16(len(enRandomSessKey))
msg.EncryptedRandomSessionMaxLen = msg.EncryptedRandomSessionLen
msg.EncryptedRandomSessionBufferOffset = msg.WorkstationBufferOffset + uint32(msg.WorkstationLen)
payloadBuff.Write(enRandomSessKey)
if (msg.NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) != 0 {
msg.Version = NewNVersion()
}
msg.Payload = payloadBuff.Bytes()
return msg
}
func (m *AuthenticateMessage) Serialize() []byte {
buff := &bytes.Buffer{}
struc.Pack(buff, m)
buff.Write(m.Payload)
return buff.Bytes()
}
type NTLMv2 struct {
domain string
user string
password string
respKeyNT []byte
respKeyLM []byte
negotiateMessage *NegotiateMessage
challengeMessage *ChallengeMessage
authenticateMessage *AuthenticateMessage
enableUnicode bool
}
func NewNTLMv2(domain, user, password string) *NTLMv2 {
return &NTLMv2{
domain: domain,
user: user,
password: password,
respKeyNT: NTOWFv2(password, user, domain),
respKeyLM: LMOWFv2(password, user, domain),
}
}
// generate first handshake messgae
func (n *NTLMv2) GetNegotiateMessage() *NegotiateMessage {
negoMsg := NewNegotiateMessage()
negoMsg.NegotiateFlags = NTLMSSP_NEGOTIATE_KEY_EXCH |
NTLMSSP_NEGOTIATE_128 |
NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY |
NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
NTLMSSP_NEGOTIATE_NTLM |
NTLMSSP_NEGOTIATE_SEAL |
NTLMSSP_NEGOTIATE_SIGN |
NTLMSSP_REQUEST_TARGET |
NTLMSSP_NEGOTIATE_UNICODE
n.negotiateMessage = negoMsg
return n.negotiateMessage
}
// process NTLMv2 Authenticate hash
func (n *NTLMv2) ComputeResponseV2(respKeyNT, respKeyLM, serverChallenge, clientChallenge,
timestamp, serverInfo []byte) (ntChallResp, lmChallResp, SessBaseKey []byte) {
tempBuff := &bytes.Buffer{}
tempBuff.Write([]byte{0x01, 0x01}) // Responser version, HiResponser version
tempBuff.Write([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
tempBuff.Write(timestamp)
tempBuff.Write(clientChallenge)
tempBuff.Write([]byte{0x00, 0x00, 0x00, 0x00})
tempBuff.Write(serverInfo)
tempBuff.Write([]byte{0x00, 0x00, 0x00, 0x00})
ntBuf := bytes.NewBuffer(serverChallenge)
ntBuf.Write(tempBuff.Bytes())
ntProof := HMAC_MD5(respKeyNT, ntBuf.Bytes())
ntChallResp = make([]byte, 0, len(ntProof)+tempBuff.Len())
ntChallResp = append(ntChallResp, ntProof...)
ntChallResp = append(ntChallResp, tempBuff.Bytes()...)
lmBuf := bytes.NewBuffer(serverChallenge)
lmBuf.Write(clientChallenge)
lmChallResp = HMAC_MD5(respKeyLM, lmBuf.Bytes())
lmChallResp = append(lmChallResp, clientChallenge...)
SessBaseKey = HMAC_MD5(respKeyNT, ntProof)
return
}
func MIC(exportedSessionKey []byte, negotiateMessage, challengeMessage, authenticateMessage Message) []byte {
buff := bytes.Buffer{}
buff.Write(negotiateMessage.Serialize())
buff.Write(challengeMessage.Serialize())
buff.Write(authenticateMessage.Serialize())
return HMAC_MD5(exportedSessionKey, buff.Bytes())
}
func concat(bs ...[]byte) []byte {
return bytes.Join(bs, nil)
}
var (
clientSigning = concat([]byte("session key to client-to-server signing key magic constant"), []byte{0x00})
serverSigning = concat([]byte("session key to server-to-client signing key magic constant"), []byte{0x00})
clientSealing = concat([]byte("session key to client-to-server sealing key magic constant"), []byte{0x00})
serverSealing = concat([]byte("session key to server-to-client sealing key magic constant"), []byte{0x00})
)
func (n *NTLMv2) GetAuthenticateMessage(s []byte) (*AuthenticateMessage, *NTLMv2Security) {
challengeMsg := &ChallengeMessage{}
r := bytes.NewReader(s)
err := struc.Unpack(r, challengeMsg)
if err != nil {
glog.Error("read challengeMsg", err)
return nil, nil
}
if challengeMsg.NegotiateFlags&NTLMSSP_NEGOTIATE_VERSION != 0 {
version := NVersion{}
err := struc.Unpack(r, &version)
if err != nil {
glog.Error("read version", err)
return nil, nil
}
challengeMsg.Version = version
}
challengeMsg.Payload, _ = core.ReadBytes(r.Len(), r)
n.challengeMessage = challengeMsg
glog.Debugf("challengeMsg:%+v", challengeMsg)
serverName := challengeMsg.getTargetName()
serverInfo := challengeMsg.getTargetInfo()
timestamp := challengeMsg.getTargetInfoTimestamp(serverInfo)
computeMIC := false
if timestamp == nil {
ft := uint64(time.Now().UnixNano()) / 100
ft += 116444736000000000 // add time between unix & windows offset
timestamp = make([]byte, 8)
binary.LittleEndian.PutUint64(timestamp, ft)
} else {
computeMIC = true
}
glog.Infof("serverName=%+v", core.UnicodeDecode(serverName))
serverChallenge := challengeMsg.ServerChallenge[:]
clientChallenge := core.Random(8)
ntChallengeResponse, lmChallengeResponse, SessionBaseKey := n.ComputeResponseV2(
n.respKeyNT, n.respKeyLM, serverChallenge, clientChallenge, timestamp, serverInfo)
exchangeKey := SessionBaseKey
exportedSessionKey := core.Random(16)
EncryptedRandomSessionKey := make([]byte, len(exportedSessionKey))
rc, _ := rc4.NewCipher(exchangeKey)
rc.XORKeyStream(EncryptedRandomSessionKey, exportedSessionKey)
if challengeMsg.NegotiateFlags&NTLMSSP_NEGOTIATE_UNICODE != 0 {
n.enableUnicode = true
}
glog.Infof("user: %s, passwd:%s", n.user, n.password)
domain, user, _ := n.GetEncodedCredentials()
n.authenticateMessage = NewAuthenticateMessage(challengeMsg.NegotiateFlags,
domain, user, []byte(""), lmChallengeResponse, ntChallengeResponse, EncryptedRandomSessionKey)
if computeMIC {
copy(n.authenticateMessage.MIC[:], MIC(exportedSessionKey, n.negotiateMessage, n.challengeMessage, n.authenticateMessage)[:16])
}
md := md5.New()
//ClientSigningKey
a := concat(exportedSessionKey, clientSigning)
md.Write(a)
ClientSigningKey := md.Sum(nil)
//ServerSigningKey
md.Reset()
a = concat(exportedSessionKey, serverSigning)
md.Write(a)
ServerSigningKey := md.Sum(nil)
//ClientSealingKey
md.Reset()
a = concat(exportedSessionKey, clientSealing)
md.Write(a)
ClientSealingKey := md.Sum(nil)
//ServerSealingKey
md.Reset()
a = concat(exportedSessionKey, serverSealing)
md.Write(a)
ServerSealingKey := md.Sum(nil)
glog.Debugf("ClientSigningKey:%s", hex.EncodeToString(ClientSigningKey))
glog.Debugf("ServerSigningKey:%s", hex.EncodeToString(ServerSigningKey))
glog.Debugf("ClientSealingKey:%s", hex.EncodeToString(ClientSealingKey))
glog.Debugf("ServerSealingKey:%s", hex.EncodeToString(ServerSealingKey))
encryptRC4, _ := rc4.NewCipher(ClientSealingKey)
decryptRC4, _ := rc4.NewCipher(ServerSealingKey)
ntlmSec := &NTLMv2Security{encryptRC4, decryptRC4, ClientSigningKey, ServerSigningKey, 0}
return n.authenticateMessage, ntlmSec
}
func (n *NTLMv2) GetEncodedCredentials() ([]byte, []byte, []byte) {
if n.enableUnicode {
return core.UnicodeEncode(n.domain), core.UnicodeEncode(n.user), core.UnicodeEncode(n.password)
}
return []byte(n.domain), []byte(n.user), []byte(n.password)
}
type NTLMv2Security struct {
EncryptRC4 *rc4.Cipher
DecryptRC4 *rc4.Cipher
SigningKey []byte
VerifyKey []byte
SeqNum uint32
}
func (n *NTLMv2Security) GssEncrypt(s []byte) []byte {
p := make([]byte, len(s))
n.EncryptRC4.XORKeyStream(p, s)
b := &bytes.Buffer{}
//signature
core.WriteUInt32LE(n.SeqNum, b)
core.WriteBytes(s, b)
s1 := HMAC_MD5(n.SigningKey, b.Bytes())[:8]
checksum := make([]byte, 8)
n.EncryptRC4.XORKeyStream(checksum, s1)
b.Reset()
core.WriteUInt32LE(0x00000001, b)
core.WriteBytes(checksum, b)
core.WriteUInt32LE(n.SeqNum, b)
core.WriteBytes(p, b)
n.SeqNum++
return b.Bytes()
}
func (n *NTLMv2Security) GssDecrypt(s []byte) []byte {
r := bytes.NewReader(s)
core.ReadUInt32LE(r) //version
checksum, _ := core.ReadBytes(8, r)
seqNum, _ := core.ReadUInt32LE(r)
data, _ := core.ReadBytes(r.Len(), r)
p := make([]byte, len(data))
n.DecryptRC4.XORKeyStream(p, data)
check := make([]byte, len(checksum))
n.DecryptRC4.XORKeyStream(check, checksum)
b := &bytes.Buffer{}
core.WriteUInt32LE(seqNum, b)
core.WriteBytes(p, b)
verify := HMAC_MD5(n.VerifyKey, b.Bytes())
if string(verify) != string(check) {
return nil
}
return p
}
+760
View File
@@ -0,0 +1,760 @@
package pdu
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/lunixbochs/struc"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/gcc"
)
type CapsType uint16
const (
CAPSTYPE_GENERAL CapsType = 0x0001
CAPSTYPE_BITMAP = 0x0002
CAPSTYPE_ORDER = 0x0003
CAPSTYPE_BITMAPCACHE = 0x0004
CAPSTYPE_CONTROL = 0x0005
CAPSTYPE_ACTIVATION = 0x0007
CAPSTYPE_POINTER = 0x0008
CAPSTYPE_SHARE = 0x0009
CAPSTYPE_COLORCACHE = 0x000A
CAPSTYPE_SOUND = 0x000C
CAPSTYPE_INPUT = 0x000D
CAPSTYPE_FONT = 0x000E
CAPSTYPE_BRUSH = 0x000F
CAPSTYPE_GLYPHCACHE = 0x0010
CAPSTYPE_OFFSCREENCACHE = 0x0011
CAPSTYPE_BITMAPCACHE_HOSTSUPPORT = 0x0012
CAPSTYPE_BITMAPCACHE_REV2 = 0x0013
CAPSTYPE_VIRTUALCHANNEL = 0x0014
CAPSTYPE_DRAWNINEGRIDCACHE = 0x0015
CAPSTYPE_DRAWGDIPLUS = 0x0016
CAPSTYPE_RAIL = 0x0017
CAPSTYPE_WINDOW = 0x0018
CAPSETTYPE_COMPDESK = 0x0019
CAPSETTYPE_MULTIFRAGMENTUPDATE = 0x001A
CAPSETTYPE_LARGE_POINTER = 0x001B
CAPSETTYPE_SURFACE_COMMANDS = 0x001C
CAPSETTYPE_BITMAP_CODECS = 0x001D
CAPSSETTYPE_FRAME_ACKNOWLEDGE = 0x001E
)
func (c CapsType) String() string {
switch c {
case CAPSTYPE_GENERAL:
return "CAPSTYPE_GENERAL"
case CAPSTYPE_BITMAP:
return "CAPSTYPE_BITMAP"
case CAPSTYPE_ORDER:
return "CAPSTYPE_ORDER"
case CAPSTYPE_BITMAPCACHE:
return "CAPSTYPE_BITMAPCACHE"
case CAPSTYPE_CONTROL:
return "CAPSTYPE_CONTROL"
case CAPSTYPE_ACTIVATION:
return "CAPSTYPE_ACTIVATION"
case CAPSTYPE_POINTER:
return "CAPSTYPE_POINTER"
case CAPSTYPE_SHARE:
return "CAPSTYPE_SHARE"
case CAPSTYPE_COLORCACHE:
return "CAPSTYPE_COLORCACHE"
case CAPSTYPE_SOUND:
return "CAPSTYPE_SOUND"
case CAPSTYPE_INPUT:
return "CAPSTYPE_INPUT"
case CAPSTYPE_FONT:
return "CAPSTYPE_FONT"
case CAPSTYPE_BRUSH:
return "CAPSTYPE_BRUSH"
case CAPSTYPE_GLYPHCACHE:
return "CAPSTYPE_GLYPHCACHE"
case CAPSTYPE_OFFSCREENCACHE:
return "CAPSTYPE_OFFSCREENCACHE"
case CAPSTYPE_BITMAPCACHE_HOSTSUPPORT:
return "CAPSTYPE_BITMAPCACHE_HOSTSUPPORT"
case CAPSTYPE_BITMAPCACHE_REV2:
return "CAPSTYPE_BITMAPCACHE_REV2"
case CAPSTYPE_VIRTUALCHANNEL:
return "CAPSTYPE_VIRTUALCHANNEL"
case CAPSTYPE_DRAWNINEGRIDCACHE:
return "CAPSTYPE_DRAWNINEGRIDCACHE"
case CAPSTYPE_DRAWGDIPLUS:
return "CAPSTYPE_DRAWGDIPLUS"
case CAPSTYPE_RAIL:
return "CAPSTYPE_RAIL"
case CAPSTYPE_WINDOW:
return "CAPSTYPE_WINDOW"
case CAPSETTYPE_COMPDESK:
return "CAPSETTYPE_COMPDESK"
case CAPSETTYPE_MULTIFRAGMENTUPDATE:
return "CAPSETTYPE_MULTIFRAGMENTUPDATE"
case CAPSETTYPE_LARGE_POINTER:
return "CAPSETTYPE_LARGE_POINTER"
case CAPSETTYPE_SURFACE_COMMANDS:
return "CAPSETTYPE_SURFACE_COMMANDS"
case CAPSETTYPE_BITMAP_CODECS:
return "CAPSETTYPE_BITMAP_CODECS"
case CAPSSETTYPE_FRAME_ACKNOWLEDGE:
return "CAPSSETTYPE_FRAME_ACKNOWLEDGE"
}
return "Unknown"
}
type MajorType uint16
const (
OSMAJORTYPE_UNSPECIFIED MajorType = 0x0000
OSMAJORTYPE_WINDOWS = 0x0001
OSMAJORTYPE_OS2 = 0x0002
OSMAJORTYPE_MACINTOSH = 0x0003
OSMAJORTYPE_UNIX = 0x0004
OSMAJORTYPE_IOS = 0x0005
OSMAJORTYPE_OSX = 0x0006
OSMAJORTYPE_ANDROID = 0x0007
)
type MinorType uint16
const (
OSMINORTYPE_UNSPECIFIED MinorType = 0x0000
OSMINORTYPE_WINDOWS_31X = 0x0001
OSMINORTYPE_WINDOWS_95 = 0x0002
OSMINORTYPE_WINDOWS_NT = 0x0003
OSMINORTYPE_OS2_V21 = 0x0004
OSMINORTYPE_POWER_PC = 0x0005
OSMINORTYPE_MACINTOSH = 0x0006
OSMINORTYPE_NATIVE_XSERVER = 0x0007
OSMINORTYPE_PSEUDO_XSERVER = 0x0008
OSMINORTYPE_WINDOWS_RT = 0x0009
)
const (
FASTPATH_OUTPUT_SUPPORTED uint16 = 0x0001
NO_BITMAP_COMPRESSION_HDR = 0x0400
LONG_CREDENTIALS_SUPPORTED = 0x0004
AUTORECONNECT_SUPPORTED = 0x0008
ENC_SALTED_CHECKSUM = 0x0010
)
type OrderFlag uint16
const (
NEGOTIATEORDERSUPPORT OrderFlag = 0x0002
ZEROBOUNDSDELTASSUPPORT = 0x0008
COLORINDEXSUPPORT = 0x0020
SOLIDPATTERNBRUSHONLY = 0x0040
ORDERFLAGS_EXTRA_FLAGS = 0x0080
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240556.aspx
*/
type Order uint8
const (
TS_NEG_DSTBLT_INDEX Order = 0x00
TS_NEG_PATBLT_INDEX = 0x01
TS_NEG_SCRBLT_INDEX = 0x02
TS_NEG_MEMBLT_INDEX = 0x03
TS_NEG_MEM3BLT_INDEX = 0x04
TS_NEG_DRAWNINEGRID_INDEX = 0x07
TS_NEG_LINETO_INDEX = 0x08
TS_NEG_MULTI_DRAWNINEGRID_INDEX = 0x09
TS_NEG_SAVEBITMAP_INDEX = 0x0B
TS_NEG_MULTIDSTBLT_INDEX = 0x0F
TS_NEG_MULTIPATBLT_INDEX = 0x10
TS_NEG_MULTISCRBLT_INDEX = 0x11
TS_NEG_MULTIOPAQUERECT_INDEX = 0x12
TS_NEG_FAST_INDEX_INDEX = 0x13
TS_NEG_POLYGON_SC_INDEX = 0x14
TS_NEG_POLYGON_CB_INDEX = 0x15
TS_NEG_POLYLINE_INDEX = 0x16
TS_NEG_FAST_GLYPH_INDEX = 0x18
TS_NEG_ELLIPSE_SC_INDEX = 0x19
TS_NEG_ELLIPSE_CB_INDEX = 0x1A
TS_NEG_GLYPH_INDEX_INDEX = 0x1B
)
type OrderEx uint16
const (
ORDERFLAGS_EX_CACHE_BITMAP_REV3_SUPPORT OrderEx = 0x0002
ORDERFLAGS_EX_ALTSEC_FRAME_MARKER_SUPPORT = 0x0004
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240563.aspx
*/
const (
INPUT_FLAG_SCANCODES uint16 = 0x0001
INPUT_FLAG_MOUSEX = 0x0004
INPUT_FLAG_FASTPATH_INPUT = 0x0008
INPUT_FLAG_UNICODE = 0x0010
INPUT_FLAG_FASTPATH_INPUT2 = 0x0020
INPUT_FLAG_UNUSED1 = 0x0040
INPUT_FLAG_UNUSED2 = 0x0080
INPUT_FLAG_MOUSE_HWHEEL = 0x0100
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240564.aspx
*/
type BrushSupport uint32
const (
BRUSH_DEFAULT BrushSupport = 0x00000000
BRUSH_COLOR_8x8 = 0x00000001
BRUSH_COLOR_FULL = 0x00000002
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240565.aspx
*/
type GlyphSupport uint16
const (
GLYPH_SUPPORT_NONE GlyphSupport = 0x0000
GLYPH_SUPPORT_PARTIAL = 0x0001
GLYPH_SUPPORT_FULL = 0x0002
GLYPH_SUPPORT_ENCODE = 0x0003
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240550.aspx
*/
type OffscreenSupportLevel uint32
const (
OSL_FALSE OffscreenSupportLevel = 0x00000000
OSL_TRUE = 0x00000001
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240551.aspx
*/
type VirtualChannelCompressionFlag uint32
const (
VCCAPS_NO_COMPR VirtualChannelCompressionFlag = 0x00000000
VCCAPS_COMPR_SC = 0x00000001
VCCAPS_COMPR_CS_8K = 0x00000002
)
type SoundFlag uint16
const (
SOUND_NONE SoundFlag = 0x0000
SOUND_BEEPS_FLAG = 0x0001
)
type RailsupportLevel uint32
const (
RAIL_LEVEL_SUPPORTED = 0x00000001
RAIL_LEVEL_DOCKED_LANGBAR_SUPPORTED = 0x00000002
RAIL_LEVEL_SHELL_INTEGRATION_SUPPORTED = 0x00000004
RAIL_LEVEL_LANGUAGE_IME_SYNC_SUPPORTED = 0x00000008
RAIL_LEVEL_SERVER_TO_CLIENT_IME_SYNC_SUPPORTED = 0x00000010
RAIL_LEVEL_HIDE_MINIMIZED_APPS_SUPPORTED = 0x00000020
RAIL_LEVEL_WINDOW_CLOAKING_SUPPORTED = 0x00000040
RAIL_LEVEL_HANDSHAKE_EX_SUPPORTED = 0x00000080
)
const (
INPUT_EVENT_SYNC = 0x0000
INPUT_EVENT_UNUSED = 0x0002
INPUT_EVENT_SCANCODE = 0x0004
INPUT_EVENT_UNICODE = 0x0005
INPUT_EVENT_MOUSE = 0x8001
INPUT_EVENT_MOUSEX = 0x8002
)
const (
PTRFLAGS_HWHEEL = 0x0400
PTRFLAGS_WHEEL = 0x0200
PTRFLAGS_WHEEL_NEGATIVE = 0x0100
WheelRotationMask = 0x01FF
PTRFLAGS_MOVE = 0x0800
PTRFLAGS_DOWN = 0x8000
PTRFLAGS_BUTTON1 = 0x1000
PTRFLAGS_BUTTON2 = 0x2000
PTRFLAGS_BUTTON3 = 0x4000
)
const (
KBDFLAGS_EXTENDED = 0x0100
KBDFLAGS_DOWN = 0x4000
KBDFLAGS_RELEASE = 0x8000
)
type SurfaceCmdFlags uint32
const (
SURFCMDS_SET_SURFACE_BITS = 0x00000002
SURFCMDS_FRAME_MARKER = 0x00000010
SURFCMDS_STREAM_SURFACE_BITS = 0x00000040
)
type Capability interface {
Type() CapsType
}
type GeneralCapability struct {
// 010018000100030000020000000015040000000000000000
OSMajorType MajorType `struc:"little"`
OSMinorType MinorType `struc:"little"`
ProtocolVersion uint16 `struc:"little"`
Pad2octetsA uint16 `struc:"little"`
GeneralCompressionTypes uint16 `struc:"little"`
ExtraFlags uint16 `struc:"little"`
UpdateCapabilityFlag uint16 `struc:"little"`
RemoteUnshareFlag uint16 `struc:"little"`
GeneralCompressionLevel uint16 `struc:"little"`
RefreshRectSupport uint8 `struc:"little"`
SuppressOutputSupport uint8 `struc:"little"`
}
func (*GeneralCapability) Type() CapsType {
return CAPSTYPE_GENERAL
}
type BitmapCapability struct {
// 02001c00180001000100010000052003000000000100000001000000
PreferredBitsPerPixel gcc.HighColor `struc:"little"`
Receive1BitPerPixel uint16 `struc:"little"`
Receive4BitsPerPixel uint16 `struc:"little"`
Receive8BitsPerPixel uint16 `struc:"little"`
DesktopWidth uint16 `struc:"little"`
DesktopHeight uint16 `struc:"little"`
Pad2octets uint16 `struc:"little"`
DesktopResizeFlag uint16 `struc:"little"`
BitmapCompressionFlag uint16 `struc:"little"`
HighColorFlags uint8 `struc:"little"`
DrawingFlags uint8 `struc:"little"`
MultipleRectangleSupport uint16 `struc:"little"`
Pad2octetsB uint16 `struc:"little"`
}
func (*BitmapCapability) Type() CapsType {
return CAPSTYPE_BITMAP
}
type BitmapCacheCapability struct {
// 04002800000000000000000000000000000000000000000000000000000000000000000000000000
Pad1 uint32 `struc:"little"`
Pad2 uint32 `struc:"little"`
Pad3 uint32 `struc:"little"`
Pad4 uint32 `struc:"little"`
Pad5 uint32 `struc:"little"`
Pad6 uint32 `struc:"little"`
Cache0Entries uint16 `struc:"little"`
Cache0MaximumCellSize uint16 `struc:"little"`
Cache1Entries uint16 `struc:"little"`
Cache1MaximumCellSize uint16 `struc:"little"`
Cache2Entries uint16 `struc:"little"`
Cache2MaximumCellSize uint16 `struc:"little"`
}
func (*BitmapCacheCapability) Type() CapsType {
return CAPSTYPE_BITMAPCACHE
}
type OrderCapability struct {
// 030058000000000000000000000000000000000000000000010014000000010000000a0000000000000000000000000000000000000000000000000000000000000000000000000000000000008403000000000000000000
TerminalDescriptor [16]byte
Pad4octetsA uint32 `struc:"little"`
DesktopSaveXGranularity uint16 `struc:"little"`
DesktopSaveYGranularity uint16 `struc:"little"`
Pad2octetsA uint16 `struc:"little"`
MaximumOrderLevel uint16 `struc:"little"`
NumberFonts uint16 `struc:"little"`
OrderFlags OrderFlag `struc:"little"`
OrderSupport [32]byte
TextFlags uint16 `struc:"little"`
OrderSupportExFlags uint16 `struc:"little"`
Pad4octetsB uint32 `struc:"little"`
DesktopSaveSize uint32 `struc:"little"`
Pad2octetsC uint16 `struc:"little"`
Pad2octetsD uint16 `struc:"little"`
TextANSICodePage uint16 `struc:"little"`
Pad2octetsE uint16 `struc:"little"`
}
func (*OrderCapability) Type() CapsType {
return CAPSTYPE_ORDER
}
type PointerCapability struct {
ColorPointerFlag uint16 `struc:"little"`
ColorPointerCacheSize uint16 `struc:"little"`
// old version of rdp doesn't support ...
PointerCacheSize uint16 `struc:"little"` // only server need
}
func (*PointerCapability) Type() CapsType {
return CAPSTYPE_POINTER
}
type InputCapability struct {
// 0d005c001500000009040000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c000000
Flags uint16 `struc:"little"`
Pad2octetsA uint16 `struc:"little"`
// same value as gcc.ClientCoreSettings.kbdLayout
KeyboardLayout gcc.KeyboardLayout `struc:"little"`
// same value as gcc.ClientCoreSettings.keyboardType
KeyboardType uint32 `struc:"little"`
// same value as gcc.ClientCoreSettings.keyboardSubType
KeyboardSubType uint32 `struc:"little"`
// same value as gcc.ClientCoreSettings.keyboardFnKeys
KeyboardFunctionKey uint32 `struc:"little"`
// same value as gcc.ClientCoreSettingrrs.imeFileName
ImeFileName [64]byte
//need add 0c000000 in the end
}
func (*InputCapability) Type() CapsType {
return CAPSTYPE_INPUT
}
type BrushCapability struct {
// 0f00080000000000
SupportLevel BrushSupport `struc:"little"`
}
func (*BrushCapability) Type() CapsType {
return CAPSTYPE_BRUSH
}
type cacheEntry struct {
Entries uint16 `struc:"little"`
MaximumCellSize uint16 `struc:"little"`
}
type GlyphCapability struct {
// 10003400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
GlyphCache [10]cacheEntry `struc:"little"`
FragCache uint32 `struc:"little"`
SupportLevel GlyphSupport `struc:"little"`
Pad2octets uint16 `struc:"little"`
}
func (*GlyphCapability) Type() CapsType {
return CAPSTYPE_GLYPHCACHE
}
type OffscreenBitmapCacheCapability struct {
// 11000c000000000000000000
SupportLevel OffscreenSupportLevel `struc:"little"`
CacheSize uint16 `struc:"little"`
CacheEntries uint16 `struc:"little"`
}
func (*OffscreenBitmapCacheCapability) Type() CapsType {
return CAPSTYPE_OFFSCREENCACHE
}
type BitmapCache2Capability struct {
BitmapCachePersist uint16 `struc:"little"`
Pad2octets uint8 `struc:"little"`
CachesNum uint8 `struc:"little"`
BmpC0Cells uint32 `struc:"little"`
BmpC1Cells uint32 `struc:"little"`
BmpC2Cells uint32 `struc:"little"`
BmpC3Cells uint32 `struc:"little"`
BmpC4Cells uint32 `struc:"little"`
Pad2octets1 [12]byte `struc:"little"`
}
func (*BitmapCache2Capability) Type() CapsType {
return CAPSTYPE_BITMAPCACHE_REV2
}
type VirtualChannelCapability struct {
// 14000c000000000000000000
Flags VirtualChannelCompressionFlag `struc:"little"`
VCChunkSize uint32 `struc:"little"` // optional
}
func (*VirtualChannelCapability) Type() CapsType {
return CAPSTYPE_VIRTUALCHANNEL
}
type SoundCapability struct {
// 0c00080000000000
Flags SoundFlag `struc:"little"`
Pad2octets uint16 `struc:"little"`
}
func (*SoundCapability) Type() CapsType {
return CAPSTYPE_SOUND
}
type ControlCapability struct {
ControlFlags uint16 `struc:"little"`
RemoteDetachFlag uint16 `struc:"little"`
ControlInterest uint16 `struc:"little"`
DetachInterest uint16 `struc:"little"`
}
func (*ControlCapability) Type() CapsType {
return CAPSTYPE_CONTROL
}
type WindowActivationCapability struct {
HelpKeyFlag uint16 `struc:"little"`
HelpKeyIndexFlag uint16 `struc:"little"`
HelpExtendedKeyFlag uint16 `struc:"little"`
WindowManagerKeyFlag uint16 `struc:"little"`
}
func (*WindowActivationCapability) Type() CapsType {
return CAPSTYPE_ACTIVATION
}
type FontCapability struct {
SupportFlags uint16 `struc:"little"`
Pad2octets uint16 `struc:"little"`
}
func (*FontCapability) Type() CapsType {
return CAPSTYPE_FONT
}
type ColorCacheCapability struct {
CacheSize uint16 `struc:"little"`
Pad2octets uint16 `struc:"little"`
}
func (*ColorCacheCapability) Type() CapsType {
return CAPSTYPE_COLORCACHE
}
type ShareCapability struct {
NodeId uint16 `struc:"little"`
Pad2octets uint16 `struc:"little"`
}
func (*ShareCapability) Type() CapsType {
return CAPSTYPE_SHARE
}
type MultiFragmentUpdate struct {
// 1a00080000000000
MaxRequestSize uint32 `struc:"little"`
}
func (*MultiFragmentUpdate) Type() CapsType {
return CAPSETTYPE_MULTIFRAGMENTUPDATE
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpegdi/52635737-d144-4f47-9c88-b48ceaf3efb4
type DrawGDIPlusCapability struct {
SupportLevel uint32
GdipVersion uint32
CacheLevel uint32
GdipCacheEntries [10]byte
GdipCacheChunkSize [8]byte
GdipImageCacheProperties [6]byte
}
func (*DrawGDIPlusCapability) Type() CapsType {
return CAPSTYPE_DRAWGDIPLUS
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/86507fed-a0ee-4242-b802-237534a8f65e
type BitmapCodec struct {
GUID [16]byte
ID uint8
PropertiesLength uint16 `struc:"little,sizeof=Properties"`
Properties []byte
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/408b1878-9f6e-4106-8329-1af42219ba6a
type BitmapCodecS struct {
Count uint8 `struc:"sizeof=Array"`
Array []BitmapCodec
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/17e80f50-d163-49de-a23b-fd6456aa472f
type BitmapCodecsCapability struct {
SupportedBitmapCodecs BitmapCodecS // A variable-length field containing a TS_BITMAPCODECS structure (section 2.2.7.2.10.1).
}
func (*BitmapCodecsCapability) Type() CapsType {
return CAPSETTYPE_BITMAP_CODECS
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/fc05c385-46c3-42cb-9ed2-c475a3990e0b
type BitmapCacheHostSupportCapability struct {
CacheVersion uint8
Pad1 uint8
Pad2 uint16
}
func (*BitmapCacheHostSupportCapability) Type() CapsType {
return CAPSTYPE_BITMAPCACHE_HOSTSUPPORT
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/41323437-c753-460e-8108-495a6fdd68a8
type LargePointerCapability struct {
SupportFlags uint16 `struc:"little"`
}
func (*LargePointerCapability) Type() CapsType {
return CAPSETTYPE_LARGE_POINTER
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdperp/36a25e21-25e1-4954-aae8-09aaf6715c79
type RemoteProgramsCapability struct {
RailSupportLevel uint32 `struc:"little"`
}
func (*RemoteProgramsCapability) Type() CapsType {
return CAPSTYPE_RAIL
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdperp/82ec7a69-f7e3-4294-830d-666178b35d15
type WindowListCapability struct {
WndSupportLevel uint32 `struc:"little"`
NumIconCaches uint8
NumIconCacheEntries uint16 `struc:"little"`
}
func (*WindowListCapability) Type() CapsType {
return CAPSTYPE_WINDOW
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/9132002f-f133-4a0f-ba2f-2dc48f1e7f93
type DesktopCompositionCapability struct {
CompDeskSupportLevel uint16 `struc:"little"`
}
func (*DesktopCompositionCapability) Type() CapsType {
return CAPSETTYPE_COMPDESK
}
// see https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/aa953018-c0a8-4761-bb12-86586c2cd56a
type SurfaceCommandsCapability struct {
CmdFlags uint32 `struc:"little"`
Reserved uint32 `struc:"little"`
}
func (*SurfaceCommandsCapability) Type() CapsType {
return CAPSETTYPE_SURFACE_COMMANDS
}
type FrameAcknowledgeCapability struct {
FrameCount uint32 `struc:"little"`
}
func (*FrameAcknowledgeCapability) Type() CapsType {
return CAPSSETTYPE_FRAME_ACKNOWLEDGE
}
type DrawNineGridCapability struct {
SupportLevel uint32 `struc:"little"`
CacheSize uint16 `struc:"little"`
CacheEntries uint16 `struc:"little"`
}
func (*DrawNineGridCapability) Type() CapsType {
return CAPSTYPE_DRAWNINEGRIDCACHE
}
func readCapability(r io.Reader) (Capability, error) {
capType, err := core.ReadUint16LE(r)
if err != nil {
return nil, err
}
capLen, err := core.ReadUint16LE(r)
if err != nil {
return nil, err
}
if int(capLen)-4 <= 0 {
return nil, errors.New(fmt.Sprintf("Capability length expected %d", capLen))
}
capBytes, err := core.ReadBytes(int(capLen)-4, r)
if err != nil {
return nil, err
}
capReader := bytes.NewReader(capBytes)
var c Capability
glog.Debugf("Capability type 0x%04x", capType)
switch CapsType(capType) {
case CAPSTYPE_GENERAL:
c = &GeneralCapability{}
case CAPSTYPE_BITMAP:
c = &BitmapCapability{}
case CAPSTYPE_ORDER:
c = &OrderCapability{}
case CAPSTYPE_BITMAPCACHE:
c = &BitmapCacheCapability{}
case CAPSTYPE_POINTER:
c = &PointerCapability{}
case CAPSTYPE_INPUT:
c = &InputCapability{}
case CAPSTYPE_BRUSH:
c = &BrushCapability{}
case CAPSTYPE_GLYPHCACHE:
c = &GlyphCapability{}
case CAPSTYPE_OFFSCREENCACHE:
c = &OffscreenBitmapCacheCapability{}
case CAPSTYPE_VIRTUALCHANNEL:
c = &VirtualChannelCapability{}
case CAPSTYPE_SOUND:
c = &SoundCapability{}
case CAPSTYPE_CONTROL:
c = &ControlCapability{}
case CAPSTYPE_ACTIVATION:
c = &WindowActivationCapability{}
case CAPSTYPE_FONT:
c = &FontCapability{}
case CAPSTYPE_COLORCACHE:
c = &ColorCacheCapability{}
case CAPSTYPE_SHARE:
c = &ShareCapability{}
case CAPSETTYPE_MULTIFRAGMENTUPDATE:
c = &MultiFragmentUpdate{}
case CAPSTYPE_DRAWGDIPLUS:
c = &DrawGDIPlusCapability{}
case CAPSETTYPE_BITMAP_CODECS:
c = &BitmapCodecsCapability{}
case CAPSTYPE_BITMAPCACHE_HOSTSUPPORT:
c = &BitmapCacheHostSupportCapability{}
case CAPSETTYPE_LARGE_POINTER:
c = &LargePointerCapability{}
case CAPSTYPE_RAIL:
c = &RemoteProgramsCapability{}
case CAPSTYPE_WINDOW:
c = &WindowListCapability{}
case CAPSETTYPE_COMPDESK:
c = &DesktopCompositionCapability{}
case CAPSETTYPE_SURFACE_COMMANDS:
c = &SurfaceCommandsCapability{}
case CAPSSETTYPE_FRAME_ACKNOWLEDGE:
c = &FrameAcknowledgeCapability{}
default:
err := errors.New(fmt.Sprintf("unsupported Capability type 0x%04x", capType))
glog.Error(err)
return nil, err
}
if err := struc.Unpack(capReader, c); err != nil {
glog.Error("Capability unpack error", err, fmt.Sprintf("0x%04x", capType), hex.EncodeToString(capBytes))
return nil, err
}
glog.Debugf("Capability<%s>: %+v", c.Type(), c)
return c, nil
}
File diff suppressed because it is too large Load Diff
+541
View File
@@ -0,0 +1,541 @@
package pdu
/* Binary Raster Operations (ROP2) */
const (
GDI_R2_BLACK = 0x01
GDI_R2_NOTMERGEPEN = 0x02
GDI_R2_MASKNOTPEN = 0x03
GDI_R2_NOTCOPYPEN = 0x04
GDI_R2_MASKPENNOT = 0x05
GDI_R2_NOT = 0x06
GDI_R2_XORPEN = 0x07
GDI_R2_NOTMASKPEN = 0x08
GDI_R2_MASKPEN = 0x09
GDI_R2_NOTXORPEN = 0x0A
GDI_R2_NOP = 0x0B
GDI_R2_MERGENOTPEN = 0x0C
GDI_R2_COPYPEN = 0x0D
GDI_R2_MERGEPENNOT = 0x0E
GDI_R2_MERGEPEN = 0x0F
GDI_R2_WHITE = 0x10
)
/* Ternary Raster Operations (ROP3) */
const (
GDI_BLACKNESS = 0x00000042
GDI_DPSoon = 0x00010289
GDI_DPSona = 0x00020C89
GDI_PSon = 0x000300AA
GDI_SDPona = 0x00040C88
GDI_DPon = 0x000500A9
GDI_PDSxnon = 0x00060865
GDI_PDSaon = 0x000702C5
GDI_SDPnaa = 0x00080F08
GDI_PDSxon = 0x00090245
GDI_DPna = 0x000A0329
GDI_PSDnaon = 0x000B0B2A
GDI_SPna = 0x000C0324
GDI_PDSnaon = 0x000D0B25
GDI_PDSonon = 0x000E08A5
GDI_Pn = 0x000F0001
GDI_PDSona = 0x00100C85
GDI_NOTSRCERASE = 0x001100A6
GDI_SDPxnon = 0x00120868
GDI_SDPaon = 0x001302C8
GDI_DPSxnon = 0x00140869
GDI_DPSaon = 0x001502C9
GDI_PSDPSanaxx = 0x00165CCA
GDI_SSPxDSxaxn = 0x00171D54
GDI_SPxPDxa = 0x00180D59
GDI_SDPSanaxn = 0x00191CC8
GDI_PDSPaox = 0x001A06C5
GDI_SDPSxaxn = 0x001B0768
GDI_PSDPaox = 0x001C06CA
GDI_DSPDxaxn = 0x001D0766
GDI_PDSox = 0x001E01A5
GDI_PDSoan = 0x001F0385
GDI_DPSnaa = 0x00200F09
GDI_SDPxon = 0x00210248
GDI_DSna = 0x00220326
GDI_SPDnaon = 0x00230B24
GDI_SPxDSxa = 0x00240D55
GDI_PDSPanaxn = 0x00251CC5
GDI_SDPSaox = 0x002606C8
GDI_SDPSxnox = 0x00271868
GDI_DPSxa = 0x00280369
GDI_PSDPSaoxxn = 0x002916CA
GDI_DPSana = 0x002A0CC9
GDI_SSPxPDxaxn = 0x002B1D58
GDI_SPDSoax = 0x002C0784
GDI_PSDnox = 0x002D060A
GDI_PSDPxox = 0x002E064A
GDI_PSDnoan = 0x002F0E2A
GDI_PSna = 0x0030032A
GDI_SDPnaon = 0x00310B28
GDI_SDPSoox = 0x00320688
GDI_NOTSRCCOPY = 0x00330008
GDI_SPDSaox = 0x003406C4
GDI_SPDSxnox = 0x00351864
GDI_SDPox = 0x003601A8
GDI_SDPoan = 0x00370388
GDI_PSDPoax = 0x0038078A
GDI_SPDnox = 0x00390604
GDI_SPDSxox = 0x003A0644
GDI_SPDnoan = 0x003B0E24
GDI_PSx = 0x003C004A
GDI_SPDSonox = 0x003D18A4
GDI_SPDSnaox = 0x003E1B24
GDI_PSan = 0x003F00EA
GDI_PSDnaa = 0x00400F0A
GDI_DPSxon = 0x00410249
GDI_SDxPDxa = 0x00420D5D
GDI_SPDSanaxn = 0x00431CC4
GDI_SRCERASE = 0x00440328
GDI_DPSnaon = 0x00450B29
GDI_DSPDaox = 0x004606C6
GDI_PSDPxaxn = 0x0047076A
GDI_SDPxa = 0x00480368
GDI_PDSPDaoxxn = 0x004916C5
GDI_DPSDoax = 0x004A0789
GDI_PDSnox = 0x004B0605
GDI_SDPana = 0x004C0CC8
GDI_SSPxDSxoxn = 0x004D1954
GDI_PDSPxox = 0x004E0645
GDI_PDSnoan = 0x004F0E25
GDI_PDna = 0x00500325
GDI_DSPnaon = 0x00510B26
GDI_DPSDaox = 0x005206C9
GDI_SPDSxaxn = 0x00530764
GDI_DPSonon = 0x005408A9
GDI_DSTINVERT = 0x00550009
GDI_DPSox = 0x005601A9
GDI_DPSoan = 0x00570389
GDI_PDSPoax = 0x00580785
GDI_DPSnox = 0x00590609
GDI_PATINVERT = 0x005A0049
GDI_DPSDonox = 0x005B18A9
GDI_DPSDxox = 0x005C0649
GDI_DPSnoan = 0x005D0E29
GDI_DPSDnaox = 0x005E1B29
GDI_DPan = 0x005F00E9
GDI_PDSxa = 0x00600365
GDI_DSPDSaoxxn = 0x006116C6
GDI_DSPDoax = 0x00620786
GDI_SDPnox = 0x00630608
GDI_SDPSoax = 0x00640788
GDI_DSPnox = 0x00650606
GDI_SRCINVERT = 0x00660046
GDI_SDPSonox = 0x006718A8
GDI_DSPDSonoxxn = 0x006858A6
GDI_PDSxxn = 0x00690145
GDI_DPSax = 0x006A01E9
GDI_PSDPSoaxxn = 0x006B178A
GDI_SDPax = 0x006C01E8
GDI_PDSPDoaxxn = 0x006D1785
GDI_SDPSnoax = 0x006E1E28
GDI_PDSxnan = 0x006F0C65
GDI_PDSana = 0x00700CC5
GDI_SSDxPDxaxn = 0x00711D5C
GDI_SDPSxox = 0x00720648
GDI_SDPnoan = 0x00730E28
GDI_DSPDxox = 0x00740646
GDI_DSPnoan = 0x00750E26
GDI_SDPSnaox = 0x00761B28
GDI_DSan = 0x007700E6
GDI_PDSax = 0x007801E5
GDI_DSPDSoaxxn = 0x00791786
GDI_DPSDnoax = 0x007A1E29
GDI_SDPxnan = 0x007B0C68
GDI_SPDSnoax = 0x007C1E24
GDI_DPSxnan = 0x007D0C69
GDI_SPxDSxo = 0x007E0955
GDI_DPSaan = 0x007F03C9
GDI_DPSaa = 0x008003E9
GDI_SPxDSxon = 0x00810975
GDI_DPSxna = 0x00820C49
GDI_SPDSnoaxn = 0x00831E04
GDI_SDPxna = 0x00840C48
GDI_PDSPnoaxn = 0x00851E05
GDI_DSPDSoaxx = 0x008617A6
GDI_PDSaxn = 0x008701C5
GDI_SRCAND = 0x008800C6
GDI_SDPSnaoxn = 0x00891B08
GDI_DSPnoa = 0x008A0E06
GDI_DSPDxoxn = 0x008B0666
GDI_SDPnoa = 0x008C0E08
GDI_SDPSxoxn = 0x008D0668
GDI_SSDxPDxax = 0x008E1D7C
GDI_PDSanan = 0x008F0CE5
GDI_PDSxna = 0x00900C45
GDI_SDPSnoaxn = 0x00911E08
GDI_DPSDPoaxx = 0x009217A9
GDI_SPDaxn = 0x009301C4
GDI_PSDPSoaxx = 0x009417AA
GDI_DPSaxn = 0x009501C9
GDI_DPSxx = 0x00960169
GDI_PSDPSonoxx = 0x0097588A
GDI_SDPSonoxn = 0x00981888
GDI_DSxn = 0x00990066
GDI_DPSnax = 0x009A0709
GDI_SDPSoaxn = 0x009B07A8
GDI_SPDnax = 0x009C0704
GDI_DSPDoaxn = 0x009D07A6
GDI_DSPDSaoxx = 0x009E16E6
GDI_PDSxan = 0x009F0345
GDI_DPa = 0x00A000C9
GDI_PDSPnaoxn = 0x00A11B05
GDI_DPSnoa = 0x00A20E09
GDI_DPSDxoxn = 0x00A30669
GDI_PDSPonoxn = 0x00A41885
GDI_PDxn = 0x00A50065
GDI_DSPnax = 0x00A60706
GDI_PDSPoaxn = 0x00A707A5
GDI_DPSoa = 0x00A803A9
GDI_DPSoxn = 0x00A90189
GDI_DSTCOPY = 0x00AA0029
GDI_DPSono = 0x00AB0889
GDI_SPDSxax = 0x00AC0744
GDI_DPSDaoxn = 0x00AD06E9
GDI_DSPnao = 0x00AE0B06
GDI_DPno = 0x00AF0229
GDI_PDSnoa = 0x00B00E05
GDI_PDSPxoxn = 0x00B10665
GDI_SSPxDSxox = 0x00B21974
GDI_SDPanan = 0x00B30CE8
GDI_PSDnax = 0x00B4070A
GDI_DPSDoaxn = 0x00B507A9
GDI_DPSDPaoxx = 0x00B616E9
GDI_SDPxan = 0x00B70348
GDI_PSDPxax = 0x00B8074A
GDI_DSPDaoxn = 0x00B906E6
GDI_DPSnao = 0x00BA0B09
GDI_MERGEPAINT = 0x00BB0226
GDI_SPDSanax = 0x00BC1CE4
GDI_SDxPDxan = 0x00BD0D7D
GDI_DPSxo = 0x00BE0269
GDI_DPSano = 0x00BF08C9
GDI_MERGECOPY = 0x00C000CA
GDI_SPDSnaoxn = 0x00C11B04
GDI_SPDSonoxn = 0x00C21884
GDI_PSxn = 0x00C3006A
GDI_SPDnoa = 0x00C40E04
GDI_SPDSxoxn = 0x00C50664
GDI_SDPnax = 0x00C60708
GDI_PSDPoaxn = 0x00C707AA
GDI_SDPoa = 0x00C803A8
GDI_SPDoxn = 0x00C90184
GDI_DPSDxax = 0x00CA0749
GDI_SPDSaoxn = 0x00CB06E4
GDI_SRCCOPY = 0x00CC0020
GDI_SDPono = 0x00CD0888
GDI_SDPnao = 0x00CE0B08
GDI_SPno = 0x00CF0224
GDI_PSDnoa = 0x00D00E0A
GDI_PSDPxoxn = 0x00D1066A
GDI_PDSnax = 0x00D20705
GDI_SPDSoaxn = 0x00D307A4
GDI_SSPxPDxax = 0x00D41D78
GDI_DPSanan = 0x00D50CE9
GDI_PSDPSaoxx = 0x00D616EA
GDI_DPSxan = 0x00D70349
GDI_PDSPxax = 0x00D80745
GDI_SDPSaoxn = 0x00D906E8
GDI_DPSDanax = 0x00DA1CE9
GDI_SPxDSxan = 0x00DB0D75
GDI_SPDnao = 0x00DC0B04
GDI_SDno = 0x00DD0228
GDI_SDPxo = 0x00DE0268
GDI_SDPano = 0x00DF08C8
GDI_PDSoa = 0x00E003A5
GDI_PDSoxn = 0x00E10185
GDI_DSPDxax = 0x00E20746
GDI_PSDPaoxn = 0x00E306EA
GDI_SDPSxax = 0x00E40748
GDI_PDSPaoxn = 0x00E506E5
GDI_SDPSanax = 0x00E61CE8
GDI_SPxPDxan = 0x00E70D79
GDI_SSPxDSxax = 0x00E81D74
GDI_DSPDSanaxxn = 0x00E95CE6
GDI_DPSao = 0x00EA02E9
GDI_DPSxno = 0x00EB0849
GDI_SDPao = 0x00EC02E8
GDI_SDPxno = 0x00ED0848
GDI_SRCPAINT = 0x00EE0086
GDI_SDPnoo = 0x00EF0A08
GDI_PATCOPY = 0x00F00021
GDI_PDSono = 0x00F10885
GDI_PDSnao = 0x00F20B05
GDI_PSno = 0x00F3022A
GDI_PSDnao = 0x00F40B0A
GDI_PDno = 0x00F50225
GDI_PDSxo = 0x00F60265
GDI_PDSano = 0x00F708C5
GDI_PDSao = 0x00F802E5
GDI_PDSxno = 0x00F90845
GDI_DPo = 0x00FA0089
GDI_PATPAINT = 0x00FB0A09
GDI_PSo = 0x00FC008A
GDI_PSDnoo = 0x00FD0A0A
GDI_DPSoo = 0x00FE02A9
GDI_WHITENESS = 0x00FF0062
GDI_GLYPH_ORDER = 0xFFFFFFFF
)
var Rop3CodeTable = map[int]string{
GDI_BLACKNESS: "0",
GDI_DPSoon: "DPSoon",
GDI_DPSona: "DPSona",
GDI_PSon: "PSon",
GDI_SDPona: "SDPona",
GDI_DPon: "DPon",
GDI_PDSxnon: "PDSxnon",
GDI_PDSaon: "PDSaon",
GDI_SDPnaa: "SDPnaa",
GDI_PDSxon: "PDSxon",
GDI_DPna: "DPna",
GDI_PSDnaon: "PSDnaon",
GDI_SPna: "SPna",
GDI_PDSnaon: "PDSnaon",
GDI_PDSonon: "PDSonon",
GDI_Pn: "Pn",
GDI_PDSona: "PDSona",
GDI_NOTSRCERASE: "DSon",
GDI_SDPxnon: "SDPxnon",
GDI_SDPaon: "SDPaon",
GDI_DPSxnon: "DPSxnon",
GDI_DPSaon: "DPSaon",
GDI_PSDPSanaxx: "PSDPSanaxx",
GDI_SSPxDSxaxn: "SSPxDSxaxn",
GDI_SPxPDxa: "SPxPDxa",
GDI_SDPSanaxn: "SDPSanaxn",
GDI_PDSPaox: "PDSPaox",
GDI_SDPSxaxn: "SDPSxaxn",
GDI_PSDPaox: "PSDPaox",
GDI_DSPDxaxn: "DSPDxaxn",
GDI_PDSox: "PDSox",
GDI_PDSoan: "PDSoan",
GDI_DPSnaa: "DPSnaa",
GDI_SDPxon: "SDPxon",
GDI_DSna: "DSna",
GDI_SPDnaon: "SPDnaon",
GDI_SPxDSxa: "SPxDSxa",
GDI_PDSPanaxn: "PDSPanaxn",
GDI_SDPSaox: "SDPSaox",
GDI_SDPSxnox: "SDPSxnox",
GDI_DPSxa: "DPSxa",
GDI_PSDPSaoxxn: "PSDPSaoxxn",
GDI_DPSana: "DPSana",
GDI_SSPxPDxaxn: "SSPxPDxaxn",
GDI_SPDSoax: "SPDSoax",
GDI_PSDnox: "PSDnox",
GDI_PSDPxox: "PSDPxox",
GDI_PSDnoan: "PSDnoan",
GDI_PSna: "PSna",
GDI_SDPnaon: "SDPnaon",
GDI_SDPSoox: "SDPSoox",
GDI_NOTSRCCOPY: "Sn",
GDI_SPDSaox: "SPDSaox",
GDI_SPDSxnox: "SPDSxnox",
GDI_SDPox: "SDPox",
GDI_SDPoan: "SDPoan",
GDI_PSDPoax: "PSDPoax",
GDI_SPDnox: "SPDnox",
GDI_SPDSxox: "SPDSxox",
GDI_SPDnoan: "SPDnoan",
GDI_PSx: "PSx",
GDI_SPDSonox: "SPDSonox",
GDI_SPDSnaox: "SPDSnaox",
GDI_PSan: "PSan",
GDI_PSDnaa: "PSDnaa",
GDI_DPSxon: "DPSxon",
GDI_SDxPDxa: "SDxPDxa",
GDI_SPDSanaxn: "SPDSanaxn",
GDI_SRCERASE: "SDna",
GDI_DPSnaon: "DPSnaon",
GDI_DSPDaox: "DSPDaox",
GDI_PSDPxaxn: "PSDPxaxn",
GDI_SDPxa: "SDPxa",
GDI_PDSPDaoxxn: "PDSPDaoxxn",
GDI_DPSDoax: "DPSDoax",
GDI_PDSnox: "PDSnox",
GDI_SDPana: "SDPana",
GDI_SSPxDSxoxn: "SSPxDSxoxn",
GDI_PDSPxox: "PDSPxox",
GDI_PDSnoan: "PDSnoan",
GDI_PDna: "PDna",
GDI_DSPnaon: "DSPnaon",
GDI_DPSDaox: "DPSDaox",
GDI_SPDSxaxn: "SPDSxaxn",
GDI_DPSonon: "DPSonon",
GDI_DSTINVERT: "Dn",
GDI_DPSox: "DPSox",
GDI_DPSoan: "DPSoan",
GDI_PDSPoax: "PDSPoax",
GDI_DPSnox: "DPSnox",
GDI_PATINVERT: "DPx",
GDI_DPSDonox: "DPSDonox",
GDI_DPSDxox: "DPSDxox",
GDI_DPSnoan: "DPSnoan",
GDI_DPSDnaox: "DPSDnaox",
GDI_DPan: "DPan",
GDI_PDSxa: "PDSxa",
GDI_DSPDSaoxxn: "DSPDSaoxxn",
GDI_DSPDoax: "DSPDoax",
GDI_SDPnox: "SDPnox",
GDI_SDPSoax: "SDPSoax",
GDI_DSPnox: "DSPnox",
GDI_SRCINVERT: "DSx",
GDI_SDPSonox: "SDPSonox",
GDI_DSPDSonoxxn: "DSPDSonoxxn",
GDI_PDSxxn: "PDSxxn",
GDI_DPSax: "DPSax",
GDI_PSDPSoaxxn: "PSDPSoaxxn",
GDI_SDPax: "SDPax",
GDI_PDSPDoaxxn: "PDSPDoaxxn",
GDI_SDPSnoax: "SDPSnoax",
GDI_PDSxnan: "PDSxnan",
GDI_PDSana: "PDSana",
GDI_SSDxPDxaxn: "SSDxPDxaxn",
GDI_SDPSxox: "SDPSxox",
GDI_SDPnoan: "SDPnoan",
GDI_DSPDxox: "DSPDxox",
GDI_DSPnoan: "DSPnoan",
GDI_SDPSnaox: "SDPSnaox",
GDI_DSan: "DSan",
GDI_PDSax: "PDSax",
GDI_DSPDSoaxxn: "DSPDSoaxxn",
GDI_DPSDnoax: "DPSDnoax",
GDI_SDPxnan: "SDPxnan",
GDI_SPDSnoax: "SPDSnoax",
GDI_DPSxnan: "DPSxnan",
GDI_SPxDSxo: "SPxDSxo",
GDI_DPSaan: "DPSaan",
GDI_DPSaa: "DPSaa",
GDI_SPxDSxon: "SPxDSxon",
GDI_DPSxna: "DPSxna",
GDI_SPDSnoaxn: "SPDSnoaxn",
GDI_SDPxna: "SDPxna",
GDI_PDSPnoaxn: "PDSPnoaxn",
GDI_DSPDSoaxx: "DSPDSoaxx",
GDI_PDSaxn: "PDSaxn",
GDI_SRCAND: "DSa",
GDI_SDPSnaoxn: "SDPSnaoxn",
GDI_DSPnoa: "DSPnoa",
GDI_DSPDxoxn: "DSPDxoxn",
GDI_SDPnoa: "SDPnoa",
GDI_SDPSxoxn: "SDPSxoxn",
GDI_SSDxPDxax: "SSDxPDxax",
GDI_PDSanan: "PDSanan",
GDI_PDSxna: "PDSxna",
GDI_SDPSnoaxn: "SDPSnoaxn",
GDI_DPSDPoaxx: "DPSDPoaxx",
GDI_SPDaxn: "SPDaxn",
GDI_PSDPSoaxx: "PSDPSoaxx",
GDI_DPSaxn: "DPSaxn",
GDI_DPSxx: "DPSxx",
GDI_PSDPSonoxx: "PSDPSonoxx",
GDI_SDPSonoxn: "SDPSonoxn",
GDI_DSxn: "DSxn",
GDI_DPSnax: "DPSnax",
GDI_SDPSoaxn: "SDPSoaxn",
GDI_SPDnax: "SPDnax",
GDI_DSPDoaxn: "DSPDoaxn",
GDI_DSPDSaoxx: "DSPDSaoxx",
GDI_PDSxan: "PDSxan",
GDI_DPa: "DPa",
GDI_PDSPnaoxn: "PDSPnaoxn",
GDI_DPSnoa: "DPSnoa",
GDI_DPSDxoxn: "DPSDxoxn",
GDI_PDSPonoxn: "PDSPonoxn",
GDI_PDxn: "PDxn",
GDI_DSPnax: "DSPnax",
GDI_PDSPoaxn: "PDSPoaxn",
GDI_DPSoa: "DPSoa",
GDI_DPSoxn: "DPSoxn",
GDI_DSTCOPY: "D",
GDI_DPSono: "DPSono",
GDI_SPDSxax: "SPDSxax",
GDI_DPSDaoxn: "DPSDaoxn",
GDI_DSPnao: "DSPnao",
GDI_DPno: "DPno",
GDI_PDSnoa: "PDSnoa",
GDI_PDSPxoxn: "PDSPxoxn",
GDI_SSPxDSxox: "SSPxDSxox",
GDI_SDPanan: "SDPanan",
GDI_PSDnax: "PSDnax",
GDI_DPSDoaxn: "DPSDoaxn",
GDI_DPSDPaoxx: "DPSDPaoxx",
GDI_SDPxan: "SDPxan",
GDI_PSDPxax: "PSDPxax",
GDI_DSPDaoxn: "DSPDaoxn",
GDI_DPSnao: "DPSnao",
GDI_MERGEPAINT: "DSno",
GDI_SPDSanax: "SPDSanax",
GDI_SDxPDxan: "SDxPDxan",
GDI_DPSxo: "DPSxo",
GDI_DPSano: "DPSano",
GDI_MERGECOPY: "PSa",
GDI_SPDSnaoxn: "SPDSnaoxn",
GDI_SPDSonoxn: "SPDSonoxn",
GDI_PSxn: "PSxn",
GDI_SPDnoa: "SPDnoa",
GDI_SPDSxoxn: "SPDSxoxn",
GDI_SDPnax: "SDPnax",
GDI_PSDPoaxn: "PSDPoaxn",
GDI_SDPoa: "SDPoa",
GDI_SPDoxn: "SPDoxn",
GDI_DPSDxax: "DPSDxax",
GDI_SPDSaoxn: "SPDSaoxn",
GDI_SRCCOPY: "S",
GDI_SDPono: "SDPono",
GDI_SDPnao: "SDPnao",
GDI_SPno: "SPno",
GDI_PSDnoa: "PSDnoa",
GDI_PSDPxoxn: "PSDPxoxn",
GDI_PDSnax: "PDSnax",
GDI_SPDSoaxn: "SPDSoaxn",
GDI_SSPxPDxax: "SSPxPDxax",
GDI_DPSanan: "DPSanan",
GDI_PSDPSaoxx: "PSDPSaoxx",
GDI_DPSxan: "DPSxan",
GDI_PDSPxax: "PDSPxax",
GDI_SDPSaoxn: "SDPSaoxn",
GDI_DPSDanax: "DPSDanax",
GDI_SPxDSxan: "SPxDSxan",
GDI_SPDnao: "SPDnao",
GDI_SDno: "SDno",
GDI_SDPxo: "SDPxo",
GDI_SDPano: "SDPano",
GDI_PDSoa: "PDSoa",
GDI_PDSoxn: "PDSoxn",
GDI_DSPDxax: "DSPDxax",
GDI_PSDPaoxn: "PSDPaoxn",
GDI_SDPSxax: "SDPSxax",
GDI_PDSPaoxn: "PDSPaoxn",
GDI_SDPSanax: "SDPSanax",
GDI_SPxPDxan: "SPxPDxan",
GDI_SSPxDSxax: "SSPxDSxax",
GDI_DSPDSanaxxn: "DSPDSanaxxn",
GDI_DPSao: "DPSao",
GDI_DPSxno: "DPSxno",
GDI_SDPao: "SDPao",
GDI_SDPxno: "SDPxno",
GDI_SRCPAINT: "DSo",
GDI_SDPnoo: "SDPnoo",
GDI_PATCOPY: "P",
GDI_PDSono: "PDSono",
GDI_PDSnao: "PDSnao",
GDI_PSno: "PSno",
GDI_PSDnao: "PSDnao",
GDI_PDno: "PDno",
GDI_PDSxo: "PDSxo",
GDI_PDSano: "PDSano",
GDI_PDSao: "PDSao",
GDI_PDSxno: "PDSxno",
GDI_DPo: "DPo",
GDI_PATPAINT: "DPSnoo",
GDI_PSo: "PSo",
GDI_PSDnoo: "PSDnoo",
GDI_DPSoo: "DPSoo",
GDI_WHITENESS: "1",
}
File diff suppressed because it is too large Load Diff
+469
View File
@@ -0,0 +1,469 @@
package pdu
import (
"bytes"
"encoding/hex"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/gcc"
)
type PDULayer struct {
emission.Emitter
transport core.Transport
sharedId uint32
userId uint16
channelId uint16
serverCapabilities map[CapsType]Capability
clientCapabilities map[CapsType]Capability
fastPathSender core.FastPathSender
demandActivePDU *DemandActivePDU
}
func NewPDULayer(t core.Transport) *PDULayer {
p := &PDULayer{
Emitter: *emission.NewEmitter(),
transport: t,
sharedId: 0x103EA,
serverCapabilities: map[CapsType]Capability{
CAPSTYPE_GENERAL: &GeneralCapability{
ProtocolVersion: 0x0200,
},
CAPSTYPE_BITMAP: &BitmapCapability{
Receive1BitPerPixel: 0x0001,
Receive4BitsPerPixel: 0x0001,
Receive8BitsPerPixel: 0x0001,
BitmapCompressionFlag: 0x0001,
MultipleRectangleSupport: 0x0001,
},
CAPSTYPE_ORDER: &OrderCapability{
DesktopSaveXGranularity: 1,
DesktopSaveYGranularity: 20,
MaximumOrderLevel: 1,
OrderFlags: NEGOTIATEORDERSUPPORT,
DesktopSaveSize: 480 * 480,
},
CAPSTYPE_POINTER: &PointerCapability{ColorPointerCacheSize: 20},
CAPSTYPE_INPUT: &InputCapability{},
CAPSTYPE_VIRTUALCHANNEL: &VirtualChannelCapability{},
CAPSTYPE_FONT: &FontCapability{SupportFlags: 0x0001},
CAPSTYPE_COLORCACHE: &ColorCacheCapability{CacheSize: 0x0006},
CAPSTYPE_SHARE: &ShareCapability{},
},
clientCapabilities: map[CapsType]Capability{
CAPSTYPE_GENERAL: &GeneralCapability{
ProtocolVersion: 0x0200,
},
CAPSTYPE_BITMAP: &BitmapCapability{
Receive1BitPerPixel: 0x0001,
Receive4BitsPerPixel: 0x0001,
Receive8BitsPerPixel: 0x0001,
BitmapCompressionFlag: 0x0001,
MultipleRectangleSupport: 0x0001,
},
CAPSTYPE_ORDER: &OrderCapability{
DesktopSaveXGranularity: 1,
DesktopSaveYGranularity: 20,
MaximumOrderLevel: 1,
OrderFlags: NEGOTIATEORDERSUPPORT,
DesktopSaveSize: 480 * 480,
TextANSICodePage: 0x4e4,
},
CAPSTYPE_CONTROL: &ControlCapability{0, 0, 2, 2},
CAPSTYPE_ACTIVATION: &WindowActivationCapability{},
CAPSTYPE_POINTER: &PointerCapability{1, 20, 20},
CAPSTYPE_SHARE: &ShareCapability{},
CAPSTYPE_COLORCACHE: &ColorCacheCapability{6, 0},
CAPSTYPE_SOUND: &SoundCapability{0x0001, 0},
CAPSTYPE_INPUT: &InputCapability{},
CAPSTYPE_FONT: &FontCapability{0x0001, 0},
CAPSTYPE_BRUSH: &BrushCapability{BRUSH_COLOR_8x8},
CAPSTYPE_GLYPHCACHE: &GlyphCapability{},
CAPSETTYPE_BITMAP_CODECS: &BitmapCodecsCapability{},
CAPSTYPE_BITMAPCACHE_REV2: &BitmapCache2Capability{
BitmapCachePersist: 2,
CachesNum: 5,
BmpC0Cells: 0x258,
BmpC1Cells: 0x258,
BmpC2Cells: 0x800,
BmpC3Cells: 0x1000,
BmpC4Cells: 0x800,
},
CAPSTYPE_VIRTUALCHANNEL: &VirtualChannelCapability{0, 1600},
CAPSETTYPE_MULTIFRAGMENTUPDATE: &MultiFragmentUpdate{65535},
CAPSTYPE_RAIL: &RemoteProgramsCapability{
RailSupportLevel: RAIL_LEVEL_SUPPORTED |
RAIL_LEVEL_SHELL_INTEGRATION_SUPPORTED |
RAIL_LEVEL_LANGUAGE_IME_SYNC_SUPPORTED |
RAIL_LEVEL_SERVER_TO_CLIENT_IME_SYNC_SUPPORTED |
RAIL_LEVEL_HIDE_MINIMIZED_APPS_SUPPORTED |
RAIL_LEVEL_WINDOW_CLOAKING_SUPPORTED |
RAIL_LEVEL_HANDSHAKE_EX_SUPPORTED |
RAIL_LEVEL_DOCKED_LANGBAR_SUPPORTED,
},
CAPSETTYPE_LARGE_POINTER: &LargePointerCapability{1},
CAPSETTYPE_SURFACE_COMMANDS: &SurfaceCommandsCapability{
CmdFlags: SURFCMDS_SET_SURFACE_BITS | SURFCMDS_STREAM_SURFACE_BITS | SURFCMDS_FRAME_MARKER,
},
CAPSSETTYPE_FRAME_ACKNOWLEDGE: &FrameAcknowledgeCapability{2},
},
}
t.On("close", func() {
p.Emit("close")
}).On("error", func(err error) {
p.Emit("error", err)
})
return p
}
func (p *PDULayer) sendPDU(message PDUMessage) {
pdu := NewPDU(p.userId, message)
p.transport.Write(pdu.serialize())
}
func (p *PDULayer) sendDataPDU(message DataPDUData) {
dataPdu := NewDataPDU(message, p.sharedId)
p.sendPDU(dataPdu)
}
func (p *PDULayer) SetFastPathSender(f core.FastPathSender) {
p.fastPathSender = f
}
type Client struct {
*PDULayer
clientCoreData *gcc.ClientCoreData
buff *bytes.Buffer
}
func NewClient(t core.Transport) *Client {
c := &Client{
PDULayer: NewPDULayer(t),
buff: &bytes.Buffer{},
}
c.transport.Once("connect", c.connect)
return c
}
func (c *Client) connect(data *gcc.ClientCoreData, userId uint16, channelId uint16) {
glog.Debug("pdu connect:", userId, ",", channelId)
c.clientCoreData = data
c.userId = userId
c.channelId = channelId
c.transport.Once("data", c.recvDemandActivePDU)
}
func (c *Client) recvDemandActivePDU(s []byte) {
glog.Trace("PDU recvDemandActivePDU", hex.EncodeToString(s))
r := bytes.NewReader(s)
pdu, err := readPDU(r)
if err != nil {
glog.Error(err)
return
}
if pdu.ShareCtrlHeader.PDUType != PDUTYPE_DEMANDACTIVEPDU {
glog.Info("PDU ignore message during connection sequence, type is", pdu.ShareCtrlHeader.PDUType)
c.transport.Once("data", c.recvDemandActivePDU)
return
}
c.sharedId = pdu.Message.(*DemandActivePDU).SharedId
c.demandActivePDU = pdu.Message.(*DemandActivePDU)
for _, caps := range c.demandActivePDU.CapabilitySets {
glog.Debugf("serverCapabilities<%s>: %+v", caps.Type(), caps)
c.serverCapabilities[caps.Type()] = caps
}
c.sendConfirmActivePDU()
c.sendClientFinalizeSynchronizePDU()
c.transport.Once("data", c.recvServerSynchronizePDU)
}
func (c *Client) sendConfirmActivePDU() {
glog.Debug("PDU start sendConfirmActivePDU")
pdu := NewConfirmActivePDU()
generalCapa := c.clientCapabilities[CAPSTYPE_GENERAL].(*GeneralCapability)
generalCapa.OSMajorType = OSMAJORTYPE_WINDOWS
generalCapa.OSMinorType = OSMINORTYPE_WINDOWS_NT
generalCapa.ExtraFlags = LONG_CREDENTIALS_SUPPORTED | NO_BITMAP_COMPRESSION_HDR |
FASTPATH_OUTPUT_SUPPORTED | AUTORECONNECT_SUPPORTED
generalCapa.RefreshRectSupport = 0
generalCapa.SuppressOutputSupport = 0
bitmapCapa := c.clientCapabilities[CAPSTYPE_BITMAP].(*BitmapCapability)
bitmapCapa.PreferredBitsPerPixel = c.clientCoreData.HighColorDepth
bitmapCapa.DesktopWidth = c.clientCoreData.DesktopWidth
bitmapCapa.DesktopHeight = c.clientCoreData.DesktopHeight
bitmapCapa.DesktopResizeFlag = 0x0001
orderCapa := c.clientCapabilities[CAPSTYPE_ORDER].(*OrderCapability)
orderCapa.OrderFlags = NEGOTIATEORDERSUPPORT | ZEROBOUNDSDELTASSUPPORT | COLORINDEXSUPPORT | ORDERFLAGS_EXTRA_FLAGS
orderCapa.OrderSupportExFlags |= ORDERFLAGS_EX_ALTSEC_FRAME_MARKER_SUPPORT
orderCapa.OrderSupport[TS_NEG_DSTBLT_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_PATBLT_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_SCRBLT_INDEX] = 1
//orderCapa.OrderSupport[TS_NEG_LINETO_INDEX] = 1
//orderCapa.OrderSupport[TS_NEG_MEMBLT_INDEX] = 1
//orderCapa.OrderSupport[TS_NEG_MEM3BLT_INDEX] = 1
//orderCapa.OrderSupport[TS_NEG_POLYLINE_INDEX] = 1
/*orderCapa.OrderSupport[TS_NEG_MULTIOPAQUERECT_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_GLYPH_INDEX_INDEX] = 1
//orderCapa.OrderSupport[TS_NEG_DRAWNINEGRID_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_SAVEBITMAP_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_POLYGON_SC_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_POLYGON_CB_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_ELLIPSE_SC_INDEX] = 1
orderCapa.OrderSupport[TS_NEG_ELLIPSE_CB_INDEX] = 1*/
orderCapa.OrderSupport[TS_NEG_FAST_GLYPH_INDEX] = 1
inputCapa := c.clientCapabilities[CAPSTYPE_INPUT].(*InputCapability)
inputCapa.Flags = INPUT_FLAG_SCANCODES | INPUT_FLAG_MOUSEX | INPUT_FLAG_UNICODE
inputCapa.KeyboardLayout = c.clientCoreData.KbdLayout
inputCapa.KeyboardType = c.clientCoreData.KeyboardType
inputCapa.KeyboardSubType = c.clientCoreData.KeyboardSubType
inputCapa.KeyboardFunctionKey = c.clientCoreData.KeyboardFnKeys
inputCapa.ImeFileName = c.clientCoreData.ImeFileName
glyphCapa := c.clientCapabilities[CAPSTYPE_GLYPHCACHE].(*GlyphCapability)
/*glyphCapa.GlyphCache[0] = cacheEntry{254, 4}
glyphCapa.GlyphCache[1] = cacheEntry{254, 4}
glyphCapa.GlyphCache[2] = cacheEntry{254, 8}
glyphCapa.GlyphCache[3] = cacheEntry{254, 8}
glyphCapa.GlyphCache[4] = cacheEntry{254, 16}
glyphCapa.GlyphCache[5] = cacheEntry{254, 32}
glyphCapa.GlyphCache[6] = cacheEntry{254, 64}
glyphCapa.GlyphCache[7] = cacheEntry{254, 128}
glyphCapa.GlyphCache[8] = cacheEntry{254, 256}
glyphCapa.GlyphCache[9] = cacheEntry{64, 2048}
glyphCapa.FragCache = 0x01000100*/
glyphCapa.SupportLevel = GLYPH_SUPPORT_NONE
pdu.SharedId = c.sharedId
for _, v := range c.clientCapabilities {
glog.Debugf("clientCapabilities<%s>: %+v", v.Type(), v)
pdu.CapabilitySets = append(pdu.CapabilitySets, v)
}
pdu.NumberCapabilities = uint16(len(pdu.CapabilitySets))
pdu.LengthSourceDescriptor = c.demandActivePDU.LengthSourceDescriptor
pdu.SourceDescriptor = c.demandActivePDU.SourceDescriptor
pdu.LengthCombinedCapabilities = c.demandActivePDU.LengthCombinedCapabilities
c.sendPDU(pdu)
}
func (c *Client) sendClientFinalizeSynchronizePDU() {
glog.Debug("PDU start sendClientFinalizeSynchronizePDU")
c.sendDataPDU(NewSynchronizeDataPDU(c.channelId))
c.sendDataPDU(&ControlDataPDU{Action: CTRLACTION_COOPERATE})
c.sendDataPDU(&ControlDataPDU{Action: CTRLACTION_REQUEST_CONTROL})
//c.sendDataPDU(&PersistKeyPDU{BBitMask: 0x03})
c.sendDataPDU(&FontListDataPDU{ListFlags: 0x0003, EntrySize: 0x0032})
}
func (c *Client) recvServerSynchronizePDU(s []byte) {
glog.Debug("PDU recvServerSynchronizePDU")
r := bytes.NewReader(s)
pdu, err := readPDU(r)
if err != nil {
glog.Error(err)
return
}
dataPdu, ok := pdu.Message.(*DataPDU)
if !ok || dataPdu.Header.PDUType2 != PDUTYPE2_SYNCHRONIZE {
if ok {
glog.Error("recvServerSynchronizePDU ignore datapdu type2", dataPdu.Header.PDUType2)
} else {
glog.Error("recvServerSynchronizePDU ignore message type", pdu.ShareCtrlHeader.PDUType)
}
glog.Infof("%+v", dataPdu)
c.transport.Once("data", c.recvServerSynchronizePDU)
return
}
c.transport.Once("data", c.recvServerControlCooperatePDU)
}
func (c *Client) recvServerControlCooperatePDU(s []byte) {
glog.Debug("PDU recvServerControlCooperatePDU")
r := bytes.NewReader(s)
pdu, err := readPDU(r)
if err != nil {
glog.Error(err)
return
}
dataPdu, ok := pdu.Message.(*DataPDU)
if !ok || dataPdu.Header.PDUType2 != PDUTYPE2_CONTROL {
if ok {
glog.Error("recvServerControlCooperatePDU ignore datapdu type2", dataPdu.Header.PDUType2)
} else {
glog.Error("recvServerControlCooperatePDU ignore message type", pdu.ShareCtrlHeader.PDUType)
}
c.transport.Once("data", c.recvServerControlCooperatePDU)
return
}
glog.Debugf("-------------PDUType2 = %02x\n", dataPdu.Header.PDUType2)
if dataPdu.Header.PDUType2 == PDUTYPE2_SAVE_SESSION_INFO {
c.Emit("success")
}
if dataPdu.Data.(*ControlDataPDU).Action != CTRLACTION_COOPERATE {
glog.Error("recvServerControlCooperatePDU ignore action", dataPdu.Data.(*ControlDataPDU).Action)
c.transport.Once("data", c.recvServerControlCooperatePDU)
return
}
c.transport.Once("data", c.recvServerControlGrantedPDU)
}
func (c *Client) recvServerControlGrantedPDU(s []byte) {
glog.Debug("PDU recvServerControlGrantedPDU")
r := bytes.NewReader(s)
pdu, err := readPDU(r)
if err != nil {
glog.Error(err)
return
}
dataPdu, ok := pdu.Message.(*DataPDU)
if !ok || dataPdu.Header.PDUType2 != PDUTYPE2_CONTROL {
if ok {
glog.Error("recvServerControlGrantedPDU ignore datapdu type2", dataPdu.Header.PDUType2)
} else {
glog.Error("recvServerControlGrantedPDU ignore message type", pdu.ShareCtrlHeader.PDUType)
}
c.transport.Once("data", c.recvServerControlGrantedPDU)
return
}
if dataPdu.Data.(*ControlDataPDU).Action != CTRLACTION_GRANTED_CONTROL {
glog.Error("recvServerControlGrantedPDU ignore action", dataPdu.Data.(*ControlDataPDU).Action)
c.transport.Once("data", c.recvServerControlGrantedPDU)
return
}
c.transport.Once("data", c.recvServerFontMapPDU)
}
func (c *Client) recvServerFontMapPDU(s []byte) {
glog.Debug("PDU recvServerFontMapPDU")
r := bytes.NewReader(s)
pdu, err := readPDU(r)
if err != nil {
glog.Error(err)
return
}
dataPdu, ok := pdu.Message.(*DataPDU)
if !ok || dataPdu.Header.PDUType2 != PDUTYPE2_FONTMAP {
if ok {
glog.Error("recvServerFontMapPDU ignore datapdu type2", dataPdu.Header.PDUType2)
} else {
glog.Error("recvServerFontMapPDU ignore message type", pdu.ShareCtrlHeader.PDUType)
}
return
}
c.transport.On("data", c.recvPDU)
c.Emit("ready")
}
func (c *Client) recvPDU(s []byte) {
glog.Trace("PDU recvPDU", hex.EncodeToString(s))
r := bytes.NewReader(s)
if r.Len() > 0 {
p, err := readPDU(r)
if err != nil {
glog.Error(err)
return
}
if p.ShareCtrlHeader.PDUType == PDUTYPE_DEACTIVATEALLPDU {
c.transport.Once("data", c.recvDemandActivePDU)
} else if p.ShareCtrlHeader.PDUType == PDUTYPE_DATAPDU {
d := p.Message.(*DataPDU)
if d.Header.PDUType2 == PDUTYPE2_UPDATE {
up := d.Data.(*UpdateDataPDU)
p := up.Udata
if up.UpdateType == FASTPATH_UPDATETYPE_BITMAP {
c.Emit("bitmap", p.(*BitmapUpdateDataPDU).Rectangles)
} else if up.UpdateType == FASTPATH_UPDATETYPE_ORDERS {
c.Emit("orders", p.(*FastPathOrdersPDU).OrderPdus)
}
}
if d.Header.PDUType2 == PDUTYPE2_SAVE_SESSION_INFO {
c.Emit("success")
}
}
}
}
func (c *Client) RecvFastPath(secFlag byte, s []byte) {
glog.Trace("PDU RecvFastPath", hex.EncodeToString(s))
r := bytes.NewReader(s)
for r.Len() > 0 {
updateHeader, err := core.ReadUInt8(r)
if err != nil {
return
}
updateCode := updateHeader & 0x0f
fragmentation := updateHeader & 0x30
compression := updateHeader & 0xC0
var compressionFlags uint8 = 0
if compression == FASTPATH_OUTPUT_COMPRESSION_USED {
compressionFlags, err = core.ReadUInt8(r)
}
size, err := core.ReadUint16LE(r)
if err != nil {
return
}
glog.Trace("Code:", FastPathUpdateType(updateCode),
"compressionFlags:", compressionFlags,
"fragmentation:", fragmentation,
"size:", size, "len:", r.Len())
if compressionFlags&RDP_MPPC_COMPRESSED != 0 {
glog.Info("RDP_MPPC_COMPRESSED")
}
if fragmentation != FASTPATH_FRAGMENT_SINGLE {
if fragmentation == FASTPATH_FRAGMENT_FIRST {
c.buff.Reset()
}
b, _ := core.ReadBytes(r.Len(), r)
c.buff.Write(b)
if fragmentation != FASTPATH_FRAGMENT_LAST {
return
}
r = bytes.NewReader(c.buff.Bytes())
}
p, err := readFastPathUpdatePDU(r, updateCode)
if err != nil || p == nil || p.Data == nil {
glog.Debug("readFastPathUpdatePDU:", err)
return
}
if updateCode == FASTPATH_UPDATETYPE_BITMAP {
c.Emit("bitmap", p.Data.(*FastPathBitmapUpdateDataPDU).Rectangles)
} else if updateCode == FASTPATH_UPDATETYPE_COLOR {
c.Emit("color", p.Data.(*FastPathColorPdu))
} else if updateCode == FASTPATH_UPDATETYPE_ORDERS {
c.Emit("orders", p.Data.(*FastPathOrdersPDU).OrderPdus)
}
}
}
type InputEventsInterface interface {
Serialize() []byte
}
func (c *Client) SendInputEvents(msgType uint16, events []InputEventsInterface) {
p := &ClientInputEventPDU{}
p.NumEvents = uint16(len(events))
p.SlowPathInputEvents = make([]SlowPathInputEvent, 0, p.NumEvents)
for _, in := range events {
seria := in.Serialize()
s := SlowPathInputEvent{0, msgType, len(seria), seria}
p.SlowPathInputEvents = append(p.SlowPathInputEvents, s)
}
c.sendDataPDU(p)
}
+457
View File
@@ -0,0 +1,457 @@
// rfb.go
package rfb
import (
"bytes"
"crypto/des"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"github.com/lunixbochs/struc"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
)
// ProtocolVersion
const (
RFB003003 = "RFB 003.003\n"
RFB003007 = "RFB 003.007\n"
RFB003008 = "RFB 003.008\n"
)
// SecurityType
const (
SEC_INVALID uint8 = 0
SEC_NONE uint8 = 1
SEC_VNC uint8 = 2
)
type RFBConn struct {
emission.Emitter
// The Socket connection to the client
Conn net.Conn
s *ServerInit
NbRect uint16
BitRect *BitRect
Password string
}
func NewRFBConn(s net.Conn, passwd string) *RFBConn {
fc := &RFBConn{
Emitter: *emission.NewEmitter(),
Conn: s,
BitRect: new(BitRect),
Password: passwd,
}
core.StartReadBytes(12, fc, fc.recvProtocolVersion)
return fc
}
func (fc *RFBConn) Read(b []byte) (n int, err error) {
return fc.Conn.Read(b)
}
func (fc *RFBConn) Write(data []byte) (n int, err error) {
buff := &bytes.Buffer{}
buff.Write(data)
return fc.Conn.Write(buff.Bytes())
}
func (fc *RFBConn) Close() error {
return fc.Conn.Close()
}
func (fc *RFBConn) recvProtocolVersion(s []byte, err error) {
version := string(s)
glog.Debug("RFBConn recvProtocolVersion", version, err)
if err != nil {
fc.Emit("error", err)
return
}
fc.Emit("data", version)
if version == RFB003003 {
fc.Emit("error", fmt.Errorf("%s", "Not Support RFB003003"))
return
//core.StartReadBytes(4, fc, fc.recvSecurityServer)
} else {
core.StartReadBytes(1, fc, fc.checkSecurityList)
}
}
func (fc *RFBConn) checkSecurityList(s []byte, err error) {
r := bytes.NewReader(s)
result, _ := core.ReadUInt8(r)
glog.Debug("RFBConn recvSecurityList", result, err)
core.StartReadBytes(int(result), fc, fc.recvSecurityList)
}
func (fc *RFBConn) recvSecurityList(s []byte, err error) {
r := bytes.NewReader(s)
secLevel := SEC_VNC
for r.Len() > 0 {
result, _ := core.ReadUInt8(r)
if result == SEC_NONE || result == SEC_VNC {
secLevel = result
break
}
}
glog.Debug("RFBConn recvSecurityList", secLevel, err)
buff := &bytes.Buffer{}
core.WriteUInt8(secLevel, buff)
fc.Write(buff.Bytes())
if secLevel == SEC_VNC {
core.StartReadBytes(16, fc, fc.recvVNCChallenge)
} else {
core.StartReadBytes(4, fc, fc.recvSecurityResult)
}
}
func fixDesKeyByte(val byte) byte {
var newval byte = 0
for i := 0; i < 8; i++ {
newval <<= 1
newval += (val & 1)
val >>= 1
}
return newval
}
// fixDesKey will make sure that exactly 8 bytes is used either by truncating or padding with nulls
// The bytes are then bit mirrored and returned
func fixDesKey(key []byte) []byte {
tmp := key
buf := make([]byte, 8)
if len(tmp) <= 8 {
copy(buf, tmp)
} else {
copy(buf, tmp[:8])
}
for i := 0; i < 8; i++ {
buf[i] = fixDesKeyByte(buf[i])
}
return buf
}
func (fc *RFBConn) recvVNCChallenge(s []byte, err error) {
glog.Debug("RFBConn recvVNCChallenge", hex.EncodeToString(s), len(s), err)
key := core.UnicodeEncode(fc.Password)
bk, err := des.NewCipher(fixDesKey(key))
if err != nil {
log.Printf("Error generating authentication cipher: %s\n", err.Error())
return
}
result := make([]byte, 16)
bk.Encrypt(result, s) //Encrypt first 8 bytes
bk.Encrypt(result[8:], s[8:])
if err != nil {
fmt.Println(err)
}
fmt.Println(string(result))
fc.Write(result)
core.StartReadBytes(4, fc, fc.recvSecurityResult)
}
func (fc *RFBConn) recvSecurityResult(s []byte, err error) {
r := bytes.NewReader(s)
result, _ := core.ReadUInt32BE(r)
glog.Debug("RFBConn recvSecurityResult", result, err)
if result == 1 {
fc.Emit("error", fmt.Errorf("%s", "Authentification failed"))
return
}
buff := &bytes.Buffer{}
core.WriteUInt8(0, buff) //share
fc.Write(buff.Bytes())
core.StartReadBytes(20, fc, fc.recvServerInit)
}
type ServerInit struct {
Width uint16 `struc:"little"`
Height uint16 `struc:"little"`
PixelFormat *PixelFormat `struc:"little"`
}
func (fc *RFBConn) recvServerInit(s []byte, err error) {
glog.Debug("RFBConn recvServerInit", len(s), err)
r := bytes.NewReader(s)
si := &ServerInit{}
si.Width, err = core.ReadUint16BE(r)
si.Height, err = core.ReadUint16BE(r)
si.PixelFormat = ReadPixelFormat(r)
glog.Infof("serverInit:%+v, %+v", si, si.PixelFormat)
fc.s = si
fc.BitRect.Pf = si.PixelFormat
core.StartReadBytes(4, fc, fc.checkServerName)
}
func (fc *RFBConn) checkServerName(s []byte, err error) {
r := bytes.NewReader(s)
result, _ := core.ReadUInt32BE(r)
glog.Debug("RFBConn recvSecurityList", result, err)
core.StartReadBytes(int(result), fc, fc.recvServerName)
}
func (fc *RFBConn) recvServerName(s []byte, err error) {
glog.Debug("RFBConn recvServerName", string(s), err)
//fc.sendPixelFormat()
fc.sendSetEncoding()
fc.sendFramebufferUpdateRequest(0, 0, 0, fc.s.Width, fc.s.Height)
fc.Emit("ready")
core.StartReadBytes(1, fc, fc.recvServerOrder)
}
func (fc *RFBConn) sendSetEncoding() {
glog.Debug("sendSetEncoding")
buff := &bytes.Buffer{}
core.WriteUInt8(2, buff)
core.WriteUInt8(0, buff)
core.WriteUInt16BE(1, buff)
core.WriteUInt32BE(0, buff)
fc.Write(buff.Bytes())
}
type FrameBufferUpdateRequest struct {
Incremental uint8
X uint16
Y uint16
Width uint16
Height uint16
}
func (fc *RFBConn) sendFramebufferUpdateRequest(Incremental uint8,
X uint16,
Y uint16,
Width uint16,
Height uint16) {
glog.Debug("sendFramebufferUpdateRequest")
buff := &bytes.Buffer{}
core.WriteUInt8(3, buff)
core.WriteUInt8(Incremental, buff)
core.WriteUInt16BE(X, buff)
core.WriteUInt16BE(Y, buff)
core.WriteUInt16BE(Width, buff)
core.WriteUInt16BE(Height, buff)
fc.Write(buff.Bytes())
}
func (fc *RFBConn) recvServerOrder(s []byte, err error) {
glog.Debug("RFBConn recvServerOrder", hex.EncodeToString(s), err)
r := bytes.NewReader(s)
packetType, _ := core.ReadUInt8(r)
switch packetType {
case 0:
core.StartReadBytes(3, fc, fc.recvFrameBufferUpdateHeader)
case 2:
//TODO
case 3:
core.StartReadBytes(7, fc, fc.recvServerCutTextHeader)
default:
glog.Errorf("Unknown message type %d", packetType)
}
}
type BitRect struct {
Rects []Rectangles
Pf *PixelFormat
}
type Rectangles struct {
Rect *Rectangle
Data []byte
}
func (fc *RFBConn) recvFrameBufferUpdateHeader(s []byte, err error) {
glog.Debug("RFBConn recvFrameBufferUpdateHeader", hex.EncodeToString(s), err)
r := bytes.NewReader(s)
core.ReadUInt8(r)
NbRect, _ := core.ReadUint16BE(r)
fc.NbRect = NbRect
fc.BitRect.Rects = make([]Rectangles, fc.NbRect)
if NbRect == 0 {
return
}
glog.Info("NbRect:", NbRect)
core.StartReadBytes(12, fc, fc.recvRectHeader)
}
type Rectangle struct {
X uint16 `struc:"little"`
Y uint16 `struc:"little"`
Width uint16 `struc:"little"`
Height uint16 `struc:"little"`
Encoding uint32 `struc:"little"`
}
func (fc *RFBConn) recvRectHeader(s []byte, err error) {
glog.Debug("RFBConn recvRectHeader", hex.EncodeToString(s), err)
r := bytes.NewReader(s)
x, err := core.ReadUint16BE(r)
y, err := core.ReadUint16BE(r)
w, err := core.ReadUint16BE(r)
h, err := core.ReadUint16BE(r)
e, err := core.ReadUInt32BE(r)
rect := &Rectangle{x, y, w, h, e}
fc.BitRect.Rects[fc.NbRect-1].Rect = rect
glog.Infof("rect:%+v, len=%d", rect, int(rect.Width)*int(rect.Height)*4)
core.StartReadBytes(int(rect.Width)*int(rect.Height)*4, fc, fc.recvRectBody)
}
func (fc *RFBConn) recvRectBody(s []byte, err error) {
glog.Debug("RFBConn recvRectBody", hex.EncodeToString(s), err)
fc.BitRect.Rects[fc.NbRect-1].Data = s
fc.NbRect--
glog.Info("fc.NbRect:", fc.NbRect)
if fc.NbRect == 0 {
fc.Emit("bitmap", fc.BitRect)
fc.sendFramebufferUpdateRequest(1, 0, 0, fc.s.Width, fc.s.Height)
core.StartReadBytes(1, fc, fc.recvServerOrder)
} else {
core.StartReadBytes(12, fc, fc.recvRectHeader)
}
}
type ServerCutTextHeader struct {
Padding [3]byte `struc:"little"`
Size uint32 `struc:"little"`
}
func (fc *RFBConn) recvServerCutTextHeader(s []byte, err error) {
glog.Debug("RFBConn recvServerCutTextHeader", string(s), err)
r := bytes.NewReader(s)
header := &ServerCutTextHeader{}
err = struc.Unpack(r, header)
if err != nil {
fc.Emit("error", err)
return
}
core.StartReadBytes(int(header.Size), fc, fc.recvServerCutTextBody)
}
func (fc *RFBConn) recvServerCutTextBody(s []byte, err error) {
glog.Debug("RFBConn recvServerCutTextBody", string(s), err)
fc.Emit("CutText", s)
core.StartReadBytes(1, fc, fc.recvServerOrder)
}
type PixelFormat struct {
BitsPerPixel uint8 `struc:"little"`
Depth uint8 `struc:"little"`
BigEndianFlag uint8 `struc:"little"`
TrueColorFlag uint8 `struc:"little"`
RedMax uint16 `struc:"little"`
GreenMax uint16 `struc:"little"`
BlueMax uint16 `struc:"little"`
RedShift uint8 `struc:"little"`
GreenShift uint8 `struc:"little"`
BlueShift uint8 `struc:"little"`
Padding uint16 `struc:"little"`
Padding1 uint8 `struc:"little"`
}
func ReadPixelFormat(r io.Reader) *PixelFormat {
p := NewPixelFormat()
p.BitsPerPixel, _ = core.ReadUInt8(r)
p.Depth, _ = core.ReadUInt8(r)
p.BigEndianFlag, _ = core.ReadUInt8(r)
p.TrueColorFlag, _ = core.ReadUInt8(r)
p.RedMax, _ = core.ReadUint16BE(r)
p.GreenMax, _ = core.ReadUint16BE(r)
p.BlueMax, _ = core.ReadUint16BE(r)
p.RedShift, _ = core.ReadUInt8(r)
p.GreenShift, _ = core.ReadUInt8(r)
p.BlueShift, _ = core.ReadUInt8(r)
p.Padding, _ = core.ReadUint16BE(r)
p.Padding1, _ = core.ReadUInt8(r)
return p
}
func NewPixelFormat() *PixelFormat {
return &PixelFormat{
32, 24, 0, 1, 65280, 65280, 65280, 16, 8, 0, 0, 0,
}
}
type RFB struct {
core.Transport
Version string
SecurityLevel uint8
ServerName string
PixelFormat *PixelFormat
NbRect int
CurrentRect *Rectangle
}
func NewRFB(t core.Transport) *RFB {
fb := &RFB{t, RFB003008, SEC_INVALID, "", NewPixelFormat(), 0, &Rectangle{}}
return fb
}
func (fb *RFB) Connect() error {
if fb.Transport == nil {
return errors.New("no transport")
}
fb.Once("data", fb.recvProtocolVersion)
return nil
}
func (fb *RFB) recvProtocolVersion(version string) {
if version != RFB003003 && version != RFB003007 && version != RFB003008 {
version = RFB003008
}
glog.Infof("version:%s", version)
b := &bytes.Buffer{}
b.WriteString(version)
fb.Write(b.Bytes())
}
type KeyEvent struct {
DownFlag uint8 `struc:"little"`
Padding uint16 `struc:"little"`
Key uint32 `struc:"little"`
}
func (fb *RFB) SendKeyEvent(k *KeyEvent) {
b := &bytes.Buffer{}
core.WriteUInt8(4, b)
core.WriteUInt8(k.DownFlag, b)
core.WriteUInt16BE(k.Padding, b)
core.WriteUInt32BE(k.Key, b)
fmt.Println(b.Bytes())
fb.Write(b.Bytes())
}
type PointerEvent struct {
Mask uint8 `struc:"little"`
XPos uint16 `struc:"little"`
YPos uint16 `struc:"little"`
}
func (fb *RFB) SendPointEvent(p *PointerEvent) {
b := &bytes.Buffer{}
core.WriteUInt8(5, b)
core.WriteUInt8(p.Mask, b)
core.WriteUInt16BE(p.XPos, b)
core.WriteUInt16BE(p.YPos, b)
fmt.Println(b.Bytes())
fb.Write(b.Bytes())
}
type ClientCutText struct {
Padding uint16 `struc:"little"`
Padding1 uint8 `struc:"little"`
Size uint32 `struc:"little"`
Message string `struc:"little"`
}
func (fb *RFB) SendClientCutText(t *ClientCutText) {
b := &bytes.Buffer{}
core.WriteUInt8(6, b)
struc.Pack(b, t)
fb.Write(b.Bytes())
}
+913
View File
@@ -0,0 +1,913 @@
package sec
import (
"bytes"
"crypto/md5"
"crypto/rand"
"crypto/rc4"
"crypto/rsa"
"crypto/sha1"
"encoding/hex"
"errors"
"io"
"unicode/utf16"
"github.com/lunixbochs/struc"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/nla"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/lic"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/gcc"
)
/**
* SecurityFlag
* @see http://msdn.microsoft.com/en-us/library/cc240579.aspx
*/
const (
EXCHANGE_PKT uint16 = 0x0001
TRANSPORT_REQ = 0x0002
TRANSPORT_RSP = 0x0004
ENCRYPT = 0x0008
RESET_SEQNO = 0x0010
IGNORE_SEQNO = 0x0020
INFO_PKT = 0x0040
LICENSE_PKT = 0x0080
LICENSE_ENCRYPT_CS = 0x0200
LICENSE_ENCRYPT_SC = 0x0200
REDIRECTION_PKT = 0x0400
SECURE_CHECKSUM = 0x0800
AUTODETECT_REQ = 0x1000
AUTODETECT_RSP = 0x2000
HEARTBEAT = 0x4000
FLAGSHI_VALID = 0x8000
)
const (
INFO_MOUSE uint32 = 0x00000001
INFO_DISABLECTRLALTDEL = 0x00000002
INFO_AUTOLOGON = 0x00000008
INFO_UNICODE = 0x00000010
INFO_MAXIMIZESHELL = 0x00000020
INFO_LOGONNOTIFY = 0x00000040
INFO_COMPRESSION = 0x00000080
INFO_ENABLEWINDOWSKEY = 0x00000100
INFO_REMOTECONSOLEAUDIO = 0x00002000
INFO_FORCE_ENCRYPTED_CS_PDU = 0x00004000
INFO_RAIL = 0x00008000
INFO_LOGONERRORS = 0x00010000
INFO_MOUSE_HAS_WHEEL = 0x00020000
INFO_PASSWORD_IS_SC_PIN = 0x00040000
INFO_NOAUDIOPLAYBACK = 0x00080000
INFO_USING_SAVED_CREDS = 0x00100000
INFO_AUDIOCAPTURE = 0x00200000
INFO_VIDEO_DISABLE = 0x00400000
INFO_CompressionTypeMask = 0x00001E00
)
const (
AF_INET uint16 = 0x00002
AF_INET6 = 0x0017
)
const (
PERF_DISABLE_WALLPAPER uint32 = 0x00000001
PERF_DISABLE_FULLWINDOWDRAG = 0x00000002
PERF_DISABLE_MENUANIMATIONS = 0x00000004
PERF_DISABLE_THEMING = 0x00000008
PERF_DISABLE_CURSOR_SHADOW = 0x00000020
PERF_DISABLE_CURSORSETTINGS = 0x00000040
PERF_ENABLE_FONT_SMOOTHING = 0x00000080
PERF_ENABLE_DESKTOP_COMPOSITION = 0x00000100
)
const (
FASTPATH_OUTPUT_SECURE_CHECKSUM = 0x1
FASTPATH_OUTPUT_ENCRYPTED = 0x2
)
type ClientAutoReconnect struct {
CbAutoReconnectLen uint16
CbLen uint32
Version uint32
LogonId uint32
SecVerifier []byte
}
func NewClientAutoReconnect(id uint32, random []byte) *ClientAutoReconnect {
return &ClientAutoReconnect{
CbAutoReconnectLen: 28,
CbLen: 28,
Version: 1,
LogonId: id,
SecVerifier: nla.HMAC_MD5(random, random),
}
}
type RDPExtendedInfo struct {
ClientAddressFamily uint16 `struc:"little"`
CbClientAddress uint16 `struc:"little,sizeof=ClientAddress"`
ClientAddress []byte `struc:"[]byte"`
CbClientDir uint16 `struc:"little,sizeof=ClientDir"`
ClientDir []byte `struc:"[]byte"`
ClientTimeZone []byte `struc:"[172]byte"`
ClientSessionId uint32 `struc:"litttle"`
PerformanceFlags uint32 `struc:"little"`
AutoReconnect *ClientAutoReconnect
}
func NewExtendedInfo(auto *ClientAutoReconnect) *RDPExtendedInfo {
return &RDPExtendedInfo{
ClientAddressFamily: AF_INET,
ClientAddress: []byte{0, 0},
ClientDir: []byte{0, 0},
ClientTimeZone: make([]byte, 172),
ClientSessionId: 0,
AutoReconnect: auto,
}
}
func (o *RDPExtendedInfo) Serialize() []byte {
buff := &bytes.Buffer{}
core.WriteUInt16LE(o.ClientAddressFamily, buff)
core.WriteUInt16LE(uint16(len(o.ClientAddress)), buff)
core.WriteBytes(o.ClientAddress, buff)
core.WriteUInt16LE(uint16(len(o.ClientDir)), buff)
core.WriteBytes(o.ClientDir, buff)
core.WriteBytes(o.ClientTimeZone, buff)
core.WriteUInt32LE(o.ClientSessionId, buff)
core.WriteUInt32LE(o.PerformanceFlags, buff)
if o.AutoReconnect != nil {
core.WriteUInt16LE(o.AutoReconnect.CbAutoReconnectLen, buff)
core.WriteUInt32LE(o.AutoReconnect.CbLen, buff)
core.WriteUInt32LE(o.AutoReconnect.Version, buff)
core.WriteUInt32LE(o.AutoReconnect.LogonId, buff)
core.WriteBytes(o.AutoReconnect.SecVerifier, buff)
}
return buff.Bytes()
}
type RDPInfo struct {
CodePage uint32
Flag uint32
CbDomain uint16
CbUserName uint16
CbPassword uint16
CbAlternateShell uint16
CbWorkingDir uint16
Domain []byte
UserName []byte
Password []byte
AlternateShell []byte
WorkingDir []byte
ExtendedInfo *RDPExtendedInfo
}
func NewRDPInfo() *RDPInfo {
info := &RDPInfo{
Flag: INFO_MOUSE | INFO_UNICODE | INFO_MAXIMIZESHELL |
INFO_ENABLEWINDOWSKEY | INFO_DISABLECTRLALTDEL | INFO_MOUSE_HAS_WHEEL |
INFO_FORCE_ENCRYPTED_CS_PDU | INFO_AUTOLOGON,
Domain: []byte{0, 0},
UserName: []byte{0, 0},
Password: []byte{0, 0},
AlternateShell: []byte{0, 0},
WorkingDir: []byte{0, 0},
ExtendedInfo: NewExtendedInfo(nil),
}
return info
}
func (o *RDPInfo) SetClientAutoReconnect(auto *ClientAutoReconnect) {
o.ExtendedInfo.AutoReconnect = auto
}
func (o *RDPInfo) SetClientInfo() {
o.Flag |= INFO_LOGONNOTIFY | INFO_LOGONERRORS
}
func (o *RDPInfo) Serialize(hasExtended bool) []byte {
buff := &bytes.Buffer{}
core.WriteUInt32LE(o.CodePage, buff) // 0000000
core.WriteUInt32LE(o.Flag, buff) // 0530101
core.WriteUInt16LE(uint16(len(o.Domain)-2), buff) // 001c
core.WriteUInt16LE(uint16(len(o.UserName)-2), buff) // 0008
core.WriteUInt16LE(uint16(len(o.Password)-2), buff) //000c
core.WriteUInt16LE(uint16(len(o.AlternateShell)-2), buff) //0000
core.WriteUInt16LE(uint16(len(o.WorkingDir)-2), buff) //0000
core.WriteBytes(o.Domain, buff)
core.WriteBytes(o.UserName, buff)
core.WriteBytes(o.Password, buff)
core.WriteBytes(o.AlternateShell, buff)
core.WriteBytes(o.WorkingDir, buff)
if hasExtended {
core.WriteBytes(o.ExtendedInfo.Serialize(), buff)
}
return buff.Bytes()
}
type SecurityHeader struct {
securityFlag uint16
securityFlagHi uint16
}
func readSecurityHeader(r io.Reader) *SecurityHeader {
s := &SecurityHeader{}
s.securityFlag, _ = core.ReadUint16LE(r)
s.securityFlagHi, _ = core.ReadUint16LE(r)
return s
}
type SEC struct {
emission.Emitter
transport core.Transport
info *RDPInfo
machineName string
clientData []interface{}
serverData []interface{}
enableEncryption bool
//Enable Secure Mac generation
enableSecureCheckSum bool
//counter before update
nbEncryptedPacket int
nbDecryptedPacket int
currentDecrytKey []byte
currentEncryptKey []byte
//current rc4 tab
decryptRc4 *rc4.Cipher
encryptRc4 *rc4.Cipher
macKey []byte
macSalt []byte
}
func NewSEC(t core.Transport) *SEC {
sec := &SEC{
*emission.NewEmitter(),
t,
NewRDPInfo(),
"",
nil,
nil,
false,
false,
0,
0,
nil,
nil,
nil,
nil,
nil,
nil,
}
t.On("close", func() {
sec.Emit("close")
}).On("error", func(err error) {
sec.Emit("error", err)
})
return sec
}
func (s *SEC) Read(data []byte) (n int, err error) {
return s.transport.Read(data)
}
func (s *SEC) Write(b []byte) (n int, err error) {
if !s.enableEncryption {
return s.transport.Write(b)
}
data := s.encrytData(b)
return s.transport.Write(data)
}
func (s *SEC) Close() error {
return s.transport.Close()
}
func (s *SEC) sendFlagged(flag uint16, data []byte) (n int, err error) {
glog.Trace("sendFlagged:", hex.EncodeToString(data))
b := s.encryt(flag, data)
return s.transport.Write(b)
}
/*
@see: http://msdn.microsoft.com/en-us/library/cc241995.aspx
@param macSaltKey: {str} mac key
@param data: {str} data to sign
@return: {str} signature
*/
func macData(macSaltKey, data []byte) []byte {
sha1Digest := sha1.New()
md5Digest := md5.New()
b := &bytes.Buffer{}
core.WriteUInt32LE(uint32(len(data)), b)
sha1Digest.Write(macSaltKey)
for i := 0; i < 40; i++ {
sha1Digest.Write([]byte("\x36"))
}
sha1Digest.Write(b.Bytes())
sha1Digest.Write(data)
sha1Sig := sha1Digest.Sum(nil)
md5Digest.Write(macSaltKey)
for i := 0; i < 48; i++ {
md5Digest.Write([]byte("\x5c"))
}
md5Digest.Write(sha1Sig)
return md5Digest.Sum(nil)
}
func (s *SEC) readEncryptedPayload(data []byte, checkSum bool) []byte {
r := bytes.NewReader(data)
sign, _ := core.ReadBytes(8, r)
glog.Debug("read sign:", sign)
encryptedPayload, _ := core.ReadBytes(r.Len(), r)
if s.decryptRc4 == nil {
s.decryptRc4, _ = rc4.NewCipher(s.currentDecrytKey)
}
s.nbDecryptedPacket++
glog.Debug("nbDecryptedPacket:", s.nbDecryptedPacket)
plaintext := make([]byte, len(encryptedPayload))
s.decryptRc4.XORKeyStream(plaintext, encryptedPayload)
return plaintext
}
func (s *SEC) writeEncryptedPayload(data []byte, checkSum bool) []byte {
if s.nbEncryptedPacket == 4096 {
}
if checkSum {
glog.Debug("need checkSum")
return []byte{}
}
s.nbEncryptedPacket++
glog.Debug("nbEncryptedPacket:", s.nbEncryptedPacket)
b := &bytes.Buffer{}
sign := macData(s.macKey, data)[:8]
//sign := macData(s.macSalt, data)[:8]
if s.encryptRc4 == nil {
s.encryptRc4, _ = rc4.NewCipher(s.currentEncryptKey)
}
plaintext := make([]byte, len(data))
s.encryptRc4.XORKeyStream(plaintext, data)
b.Write(sign)
b.Write(plaintext)
glog.Debug("sign:", hex.EncodeToString(sign), "plaintext:", hex.EncodeToString(plaintext))
return b.Bytes()
}
func (s *SEC) encryt(flag uint16, b []byte) []byte {
data := b
if flag&ENCRYPT != 0 {
data = s.writeEncryptedPayload(b, flag&SECURE_CHECKSUM != 0)
}
buff := &bytes.Buffer{}
core.WriteUInt16LE(flag, buff)
core.WriteUInt16LE(0, buff)
core.WriteBytes(data, buff)
return buff.Bytes()
}
func (s *SEC) encrytData(b []byte) []byte {
if !s.enableEncryption {
return b
}
var flag uint16 = ENCRYPT
if s.enableSecureCheckSum {
flag |= SECURE_CHECKSUM
}
return s.encryt(flag, b)
}
func (s *SEC) decrytData(b []byte) []byte {
if !s.enableEncryption {
return b
}
r := bytes.NewReader(b)
securityFlag, _ := core.ReadUint16LE(r)
_, _ = core.ReadUint16LE(r) //securityFlagHi
data, _ := core.ReadBytes(r.Len(), r)
if securityFlag&ENCRYPT != 0 {
data = s.readEncryptedPayload(data, securityFlag&SECURE_CHECKSUM != 0)
}
return data
}
type Client struct {
*SEC
userId uint16
channelId uint16
//initialise decrypt and encrypt keys
initialDecrytKey []byte
initialEncryptKey []byte
fastPathListener core.FastPathListener
channelSender core.ChannelSender
}
func NewClient(t core.Transport) *Client {
c := &Client{
SEC: NewSEC(t),
}
t.On("connect", c.connect)
return c
}
func (c *Client) SetClientAutoReconnect(id uint32, random []byte) {
auto := NewClientAutoReconnect(id, random)
c.info.SetClientAutoReconnect(auto)
}
func (c *Client) SetAlternateShell(shell string) {
buff := &bytes.Buffer{}
for _, ch := range utf16.Encode([]rune(shell)) {
core.WriteUInt16LE(ch, buff)
}
core.WriteUInt16LE(0, buff)
c.info.AlternateShell = buff.Bytes()
c.info.Flag |= INFO_RAIL
}
func (c *Client) SetUser(user string) {
buff := &bytes.Buffer{}
for _, ch := range utf16.Encode([]rune(user)) {
core.WriteUInt16LE(ch, buff)
}
core.WriteUInt16LE(0, buff)
c.info.UserName = buff.Bytes()
}
func (c *Client) SetPwd(pwd string) {
buff := &bytes.Buffer{}
for _, ch := range utf16.Encode([]rune(pwd)) {
core.WriteUInt16LE(ch, buff)
}
core.WriteUInt16LE(0, buff)
c.info.Password = buff.Bytes()
}
func (c *Client) SetDomain(domain string) {
buff := &bytes.Buffer{}
for _, ch := range utf16.Encode([]rune(domain)) {
core.WriteUInt16LE(ch, buff)
}
core.WriteUInt16LE(0, buff)
c.info.Domain = buff.Bytes()
}
func (c *Client) connect(clientData []interface{}, serverData []interface{}, userId uint16, channels []t125.MCSChannelInfo) {
glog.Debug("sec on connect:", clientData)
glog.Debug("sec on connect:", serverData)
glog.Debug("sec on connect:", userId)
glog.Debug("sec on connect:", channels)
c.clientData = clientData
c.serverData = serverData
c.userId = userId
for _, channel := range channels {
glog.Infof("channel: %s <%d>:", channel.Name, channel.ID)
if channel.Name == t125.GLOBAL_CHANNEL_NAME {
c.channelId = channel.ID
//break
}
}
c.enableEncryption = c.ClientCoreData().ServerSelectedProtocol == 0
if c.enableEncryption {
c.sendClientRandom()
}
c.sendInfoPkt()
c.transport.Once("sec", c.recvLicenceInfo)
}
func (c *Client) ClientCoreData() *gcc.ClientCoreData {
return c.clientData[0].(*gcc.ClientCoreData)
}
func (c *Client) ClientSecurityData() *gcc.ClientSecurityData {
return c.clientData[1].(*gcc.ClientSecurityData)
}
func (c *Client) ClientNetworkData() *gcc.ClientNetworkData {
return c.clientData[2].(*gcc.ClientNetworkData)
}
func (c *Client) ServerSecurityData() *gcc.ServerSecurityData {
return c.serverData[1].(*gcc.ServerSecurityData)
}
/*
@summary: generate 40 bits data from 128 bits data
@param data: {str} 128 bits data
@return: {str} 40 bits data
@see: http://msdn.microsoft.com/en-us/library/cc240785.aspx
*/
func gen40bits(data []byte) []byte {
return append([]byte("\xd1\x26\x9e"), data[3:8]...)
}
/*
@summary: generate 56 bits data from 128 bits data
@param data: {str} 128 bits data
@return: {str} 56 bits data
@see: http://msdn.microsoft.com/en-us/library/cc240785.aspx
*/
func gen56bits(data []byte) []byte {
return append([]byte("\xd1"), data[1:8]...)
}
/*
@summary: Generate particular signature from combination of sha1 and md5
@see: http://msdn.microsoft.com/en-us/library/cc241992.aspx
@param inputData: strange input (see doc)
@param salt: salt for context call
@param salt1: another salt (ex : client random)
@param salt2: another another salt (ex: server random)
@return : MD5(Salt + SHA1(Input + Salt + Salt1 + Salt2))
*/
func saltedHash(inputData, salt, salt1, salt2 []byte) []byte {
sha1Digest := sha1.New()
md5Digest := md5.New()
sha1Digest.Write(inputData)
sha1Digest.Write(salt[:48])
sha1Digest.Write(salt1)
sha1Digest.Write(salt2)
sha1Sig := sha1Digest.Sum(nil)
md5Digest.Write(salt[:48])
md5Digest.Write(sha1Sig)
return md5Digest.Sum(nil)[:16]
}
/*
@summary: MD5(in0[:16] + in1[:32] + in2[:32])
@param key: in 16
@param random1: in 32
@param random2: in 32
@return MD5(in0[:16] + in1[:32] + in2[:32])
*/
func finalHash(key, random1, random2 []byte) []byte {
md5Digest := md5.New()
md5Digest.Write(key)
md5Digest.Write(random1)
md5Digest.Write(random2)
return md5Digest.Sum(nil)
}
/*
@summary: Generate master secret
@param secret: {str} secret
@param clientRandom : {str} client random
@param serverRandom : {str} server random
@see: http://msdn.microsoft.com/en-us/library/cc241992.aspx
*/
func masterSecret(secret, random1, random2 []byte) []byte {
sh1 := saltedHash([]byte("A"), secret, random1, random2)
sh2 := saltedHash([]byte("BB"), secret, random1, random2)
sh3 := saltedHash([]byte("CCC"), secret, random1, random2)
ms := bytes.NewBuffer(nil)
ms.Write(sh1)
ms.Write(sh2)
ms.Write(sh3)
return ms.Bytes()
}
/*
@summary: Generate master secret
@param secret: secret
@param clientRandom : client random
@param serverRandom : server random
*/
func sessionKeyBlob(secret, random1, random2 []byte) []byte {
sh1 := saltedHash([]byte("X"), secret, random1, random2)
sh2 := saltedHash([]byte("YY"), secret, random1, random2)
sh3 := saltedHash([]byte("ZZZ"), secret, random1, random2)
ms := bytes.NewBuffer(nil)
ms.Write(sh1)
ms.Write(sh2)
ms.Write(sh3)
return ms.Bytes()
}
func generateKeys(clientRandom, serverRandom []byte, method uint32) ([]byte, []byte, []byte) {
b := &bytes.Buffer{}
b.Write(clientRandom[:24])
b.Write(serverRandom[:24])
preMasterHash := b.Bytes()
glog.Debug("preMasterHash:", hex.EncodeToString(preMasterHash))
masterHash := masterSecret(preMasterHash, clientRandom, serverRandom)
glog.Debug("masterHash:", hex.EncodeToString(masterHash))
sessionKey := sessionKeyBlob(masterHash, clientRandom, serverRandom)
glog.Debug("sessionKey:", hex.EncodeToString(sessionKey))
macKey128 := sessionKey[:16]
initialFirstKey128 := finalHash(sessionKey[16:32], clientRandom, serverRandom)
initialSecondKey128 := finalHash(sessionKey[32:48], clientRandom, serverRandom)
glog.Debug("macKey128:", hex.EncodeToString(macKey128))
glog.Debug("FirstKey128:", hex.EncodeToString(initialFirstKey128))
glog.Debug("SecondKey128:", hex.EncodeToString(initialSecondKey128))
//generate valid key
if method == gcc.ENCRYPTION_FLAG_40BIT {
return gen40bits(macKey128), gen40bits(initialFirstKey128), gen40bits(initialSecondKey128)
} else if method == gcc.ENCRYPTION_FLAG_56BIT {
return gen56bits(macKey128), gen56bits(initialFirstKey128), gen56bits(initialSecondKey128)
}
// method == gcc.ENCRYPTION_FLAG_128BIT
return macKey128, initialFirstKey128, initialSecondKey128
}
type ClientSecurityExchangePDU struct {
Length uint32 `struc:"little"`
EncryptedClientRandom []byte `struc:"little"`
Padding []byte `struc:"[8]byte"`
}
func (e *ClientSecurityExchangePDU) serialize() []byte {
buff := &bytes.Buffer{}
core.WriteUInt32LE(e.Length, buff)
core.WriteBytes(e.EncryptedClientRandom, buff)
core.WriteBytes(e.Padding, buff)
return buff.Bytes()
}
func (c *Client) sendClientRandom() {
glog.Debug("send Client Random")
clientRandom := core.Random(32)
glog.Debug("clientRandom:", hex.EncodeToString(clientRandom))
serverRandom := c.ServerSecurityData().ServerRandom
glog.Debug("ServerRandom:", hex.EncodeToString(serverRandom))
c.macKey, c.initialDecrytKey, c.initialEncryptKey = generateKeys(clientRandom,
serverRandom, c.ServerSecurityData().EncryptionMethod)
//initialize keys
c.currentDecrytKey = c.initialDecrytKey
c.currentEncryptKey = c.initialEncryptKey
//verify certificate
if !c.ServerSecurityData().ServerCertificate.CertData.Verify() {
glog.Warn("Cannot verify server identity")
}
serverPubKey, err := c.ServerSecurityData().ServerCertificate.CertData.GetPublicKey()
if err != nil || serverPubKey == nil {
glog.Error("GetPublicKey failed:", err)
c.Emit("error", errors.New("failed to get server public key"))
return
}
ret, err := rsa.EncryptPKCS1v15(rand.Reader, serverPubKey, core.Reverse(clientRandom))
if err != nil {
glog.Error("EncryptPKCS1v15 err:", err)
c.Emit("error", err)
return
}
message := ClientSecurityExchangePDU{}
message.EncryptedClientRandom = core.Reverse(ret)
message.Length = uint32(len(message.EncryptedClientRandom) + 8)
message.Padding = make([]byte, 8)
glog.Debug("message:", message)
c.sendFlagged(EXCHANGE_PKT, message.serialize())
}
func (c *Client) sendInfoPkt() {
var secFlag uint16 = INFO_PKT
if c.enableEncryption {
secFlag |= ENCRYPT
}
glog.Debug("RdpVersion:", c.ClientCoreData().RdpVersion, ":", gcc.RDP_VERSION_5_PLUS)
c.sendFlagged(secFlag, c.info.Serialize(c.ClientCoreData().RdpVersion == gcc.RDP_VERSION_5_PLUS))
}
func (c *Client) recvLicenceInfo(channel string, s []byte) {
glog.Debug("sec recvLicenceInfo", hex.EncodeToString(s))
r := bytes.NewReader(s)
h := readSecurityHeader(r)
if (h.securityFlag & LICENSE_PKT) == 0 {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_PDU_SEC_BAD_LICENSE_HEADER"))
return
}
p := lic.ReadLicensePacket(r)
switch p.BMsgtype {
case lic.NEW_LICENSE:
glog.Info("sec NEW_LICENSE")
c.Emit("success")
goto connect
case lic.ERROR_ALERT:
message := p.LicensingMessage.(*lic.ErrorMessage)
glog.Info("sec ERROR_ALERT and ErrorCode:", message.DwErrorCode)
if message.DwErrorCode == lic.STATUS_VALID_CLIENT && message.DwStateTransaction == lic.ST_NO_TRANSITION {
goto connect
}
goto retry
case lic.LICENSE_REQUEST:
glog.Info("sec LICENSE_REQUEST")
c.sendClientNewLicenseRequest(p.LicensingMessage.([]byte))
goto retry
case lic.PLATFORM_CHALLENGE:
glog.Info("sec PLATFORM_CHALLENGE")
c.sendClientChallengeResponse(p.LicensingMessage.([]byte))
goto retry
default:
glog.Error("Not a valid license packet")
c.Emit("error", errors.New("Not a valid license packet"))
return
}
connect:
c.transport.On("sec", c.recvData)
c.Emit("connect", c.clientData[0].(*gcc.ClientCoreData), c.userId, c.channelId)
return
retry:
c.transport.Once("sec", c.recvLicenceInfo)
return
}
func (c *Client) sendClientNewLicenseRequest(data []byte) {
var req lic.ServerLicenseRequest
struc.Unpack(bytes.NewReader(data), &req)
var sc gcc.ServerCertificate
if c.ServerSecurityData().ServerCertificate.DwVersion != 0 {
sc = c.ServerSecurityData().ServerCertificate
} else {
rd := bytes.NewReader(req.ServerCertificate.BlobData)
err := sc.Unpack(rd)
if err != nil {
glog.Error("read serverCertificate err:", err)
return
}
}
serverRandom := req.ServerRandom
clientRandom := core.Random(32)
preMasterSecret := core.Random(48)
masSecret := masterSecret(preMasterSecret, clientRandom, serverRandom)
sessionKeyBlob := masterSecret(masSecret, serverRandom, clientRandom)
//c.macKey = sessionKeyBlob[:16]
c.macSalt = sessionKeyBlob[:16]
c.initialDecrytKey = finalHash(sessionKeyBlob[16:32], clientRandom, serverRandom)
//format message
message := &lic.ClientNewLicenseRequest{}
message.PreferredKeyExchangeAlg = 0x00000001
message.PlatformId = 0x04000000 | 0x00010000
message.ClientRandom = clientRandom
buff := &bytes.Buffer{}
serverPubKey, err := sc.CertData.GetPublicKey()
if err != nil {
glog.Error("GetPublicKey failed:", err)
return
}
ret, err := rsa.EncryptPKCS1v15(rand.Reader, serverPubKey, core.Reverse(preMasterSecret))
if err != nil {
glog.Error("EncryptPKCS1v15 failed:", err)
return
}
buff.Write(core.Reverse(ret))
buff.Write([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
message.EncryptedPreMasterSecret.BlobData = buff.Bytes()
message.EncryptedPreMasterSecret.WBlobLen = uint16(buff.Len())
message.EncryptedPreMasterSecret.WBlobType = lic.BB_RANDOM_BLOB
buff.Reset()
buff.Write(c.info.UserName)
buff.Write([]byte{0x00})
message.ClientUserName.BlobData = buff.Bytes()
message.ClientUserName.WBlobLen = uint16(buff.Len())
message.ClientUserName.WBlobType = lic.BB_CLIENT_USER_NAME_BLOB
buff.Reset()
buff.Write(c.ClientCoreData().ClientName[:])
buff.Write([]byte{0x00})
message.ClientMachineName.BlobData = buff.Bytes()
message.ClientMachineName.WBlobLen = uint16(buff.Len())
message.ClientMachineName.WBlobType = lic.BB_CLIENT_MACHINE_NAME_BLOB
buff.Reset()
err = struc.Pack(buff, message)
if err != nil {
glog.Error("err:", err)
}
c.sendFlagged(LICENSE_PKT, buff.Bytes())
}
func (c *Client) sendClientChallengeResponse(data []byte) {
var pc lic.ServerPlatformChallenge
struc.Unpack(bytes.NewReader(data), &pc)
serverEncryptedChallenge := pc.EncryptedPlatformChallenge.BlobData
//decrypt server challenge
//it should be TEST word in unicode format
rc, _ := rc4.NewCipher(c.initialDecrytKey)
serverChallenge := make([]byte, 20)
rc.XORKeyStream(serverChallenge, serverEncryptedChallenge)
//if serverChallenge != "T\x00E\x00S\x00T\x00\x00\x00":
//raise InvalidExpectedDataException("bad license server challenge")
//generate hwid
b := &bytes.Buffer{}
b.Write(c.ClientCoreData().ClientName[:])
b.Write(c.info.UserName)
for i := 0; i < 2; i++ {
b.Write([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
}
hwid := b.Bytes()[:20]
encryptedHWID := make([]byte, 20)
rc.XORKeyStream(encryptedHWID, hwid)
b.Reset()
b.Write(serverChallenge)
b.Write(hwid)
message := &lic.ClientPLatformChallengeResponse{}
message.EncryptedPlatformChallengeResponse.BlobData = serverEncryptedChallenge
message.EncryptedHWID.BlobData = encryptedHWID
//message.MACData = macData(c.macKey, b.Bytes())[:16]
message.MACData = macData(c.macSalt, b.Bytes())[:16]
b.Reset()
struc.Pack(b, message)
c.sendFlagged(LICENSE_PKT, b.Bytes())
}
func (c *Client) recvData(channel string, s []byte) {
glog.Trace("sec recvData", hex.EncodeToString(s))
glog.Debugf("channel<%s> data len: %d", channel, len(s))
data := c.decrytData(s)
if channel != t125.GLOBAL_CHANNEL_NAME {
c.Emit("channel", channel, data)
return
}
c.Emit("data", data)
}
func (c *Client) SetFastPathListener(f core.FastPathListener) {
c.fastPathListener = f
}
func (c *Client) RecvFastPath(secFlag byte, s []byte) {
data := s
if c.enableEncryption && secFlag&FASTPATH_OUTPUT_ENCRYPTED != 0 {
data = c.readEncryptedPayload(s, secFlag&FASTPATH_OUTPUT_SECURE_CHECKSUM != 0)
}
c.fastPathListener.RecvFastPath(secFlag, data)
}
func (c *Client) SetChannelSender(f core.ChannelSender) {
c.channelSender = f
}
func (c *Client) SendToChannel(channel string, b []byte) (int, error) {
if !c.enableEncryption {
glog.Debug("Sec Client write", hex.EncodeToString(b))
return c.channelSender.SendToChannel(channel, b)
}
var flag uint16 = ENCRYPT
if c.enableSecureCheckSum {
flag |= SECURE_CHECKSUM
}
data := c.writeEncryptedPayload(b, c.enableSecureCheckSum)
buff := &bytes.Buffer{}
core.WriteUInt16LE(flag, buff)
core.WriteUInt16LE(0, buff)
core.WriteBytes(data, buff)
glog.Debug("Sec Client write", channel, hex.EncodeToString(buff.Bytes()))
return c.channelSender.SendToChannel(channel, buff.Bytes())
}
+189
View File
@@ -0,0 +1,189 @@
package ber
import (
"errors"
"fmt"
"io"
"github.com/shadow1ng/fscan/mylib/grdp/core"
)
const (
CLASS_MASK uint8 = 0xC0
CLASS_UNIV = 0x00
CLASS_APPL = 0x40
CLASS_CTXT = 0x80
CLASS_PRIV = 0xC0
)
const (
PC_MASK uint8 = 0x20
PC_PRIMITIVE = 0x00
PC_CONSTRUCT = 0x20
)
const (
TAG_MASK uint8 = 0x1F
TAG_BOOLEAN = 0x01
TAG_INTEGER = 0x02
TAG_BIT_STRING = 0x03
TAG_OCTET_STRING = 0x04
TAG_OBJECT_IDENFIER = 0x06
TAG_ENUMERATED = 0x0A
TAG_SEQUENCE = 0x10
TAG_SEQUENCE_OF = 0x10
)
func berPC(pc bool) uint8 {
if pc {
return PC_CONSTRUCT
}
return PC_PRIMITIVE
}
func ReadEnumerated(r io.Reader) (uint8, error) {
if !ReadUniversalTag(TAG_ENUMERATED, false, r) {
return 0, errors.New("invalid ber tag")
}
length, err := ReadLength(r)
if err != nil {
return 0, err
}
if length != 1 {
return 0, errors.New(fmt.Sprintf("enumerate size is wrong, get %v, expect 1", length))
}
return core.ReadUInt8(r)
}
func ReadUniversalTag(tag uint8, pc bool, r io.Reader) bool {
bb, _ := core.ReadUInt8(r)
return bb == (CLASS_UNIV|berPC(pc))|(TAG_MASK&tag)
}
func WriteUniversalTag(tag uint8, pc bool, w io.Writer) {
core.WriteUInt8((CLASS_UNIV|berPC(pc))|(TAG_MASK&tag), w)
}
func ReadLength(r io.Reader) (int, error) {
ret := 0
size, _ := core.ReadUInt8(r)
if size&0x80 > 0 {
size = size &^ 0x80
if size == 1 {
r, err := core.ReadUInt8(r)
if err != nil {
return 0, err
}
ret = int(r)
} else if size == 2 {
r, err := core.ReadUint16BE(r)
if err != nil {
return 0, err
}
ret = int(r)
} else {
return 0, errors.New("BER length may be 1 or 2")
}
} else {
ret = int(size)
}
return ret, nil
}
func WriteLength(size int, w io.Writer) {
if size > 0x7f {
core.WriteUInt8(0x82, w)
core.WriteUInt16BE(uint16(size), w)
} else {
core.WriteUInt8(uint8(size), w)
}
}
func ReadInteger(r io.Reader) (int, error) {
if !ReadUniversalTag(TAG_INTEGER, false, r) {
return 0, errors.New("Bad integer tag")
}
size, _ := ReadLength(r)
switch size {
case 1:
num, _ := core.ReadUInt8(r)
return int(num), nil
case 2:
num, _ := core.ReadUint16BE(r)
return int(num), nil
case 3:
integer1, _ := core.ReadUInt8(r)
integer2, _ := core.ReadUint16BE(r)
return int(integer2) + (int(integer1) << 16), nil
case 4:
num, _ := core.ReadUInt32BE(r)
return int(num), nil
default:
return 0, errors.New("wrong size")
}
}
func WriteInteger(n int, w io.Writer) {
WriteUniversalTag(TAG_INTEGER, false, w)
if n <= 0xff {
WriteLength(1, w)
core.WriteUInt8(uint8(n), w)
} else if n <= 0xffff {
WriteLength(2, w)
core.WriteUInt16BE(uint16(n), w)
} else {
WriteLength(4, w)
core.WriteUInt32BE(uint32(n), w)
}
}
func WriteOctetstring(str string, w io.Writer) {
WriteUniversalTag(TAG_OCTET_STRING, false, w)
WriteLength(len(str), w)
core.WriteBytes([]byte(str), w)
}
func WriteBoolean(b bool, w io.Writer) {
bb := uint8(0)
if b {
bb = uint8(0xff)
}
WriteUniversalTag(TAG_BOOLEAN, false, w)
WriteLength(1, w)
core.WriteUInt8(bb, w)
}
func ReadApplicationTag(tag uint8, r io.Reader) (int, error) {
bb, _ := core.ReadUInt8(r)
if tag > 30 {
if bb != (CLASS_APPL|PC_CONSTRUCT)|TAG_MASK {
return 0, errors.New("ReadApplicationTag invalid data")
}
bb, _ := core.ReadUInt8(r)
if bb != tag {
return 0, errors.New("ReadApplicationTag bad tag")
}
} else {
if bb != (CLASS_APPL|PC_CONSTRUCT)|(TAG_MASK&tag) {
return 0, errors.New("ReadApplicationTag invalid data2")
}
}
return ReadLength(r)
}
func WriteApplicationTag(tag uint8, size int, w io.Writer) {
if tag > 30 {
core.WriteUInt8((CLASS_APPL|PC_CONSTRUCT)|TAG_MASK, w)
core.WriteUInt8(tag, w)
WriteLength(size, w)
} else {
core.WriteUInt8((CLASS_APPL|PC_CONSTRUCT)|(TAG_MASK&tag), w)
WriteLength(size, w)
}
}
func WriteEncodedDomainParams(data []byte, w io.Writer) {
WriteUniversalTag(TAG_SEQUENCE, true, w)
WriteLength(len(data), w)
core.WriteBytes(data, w)
}
+642
View File
@@ -0,0 +1,642 @@
package gcc
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"fmt"
"io"
"math/big"
"os"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/lunixbochs/struc"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/per"
)
var t124_02_98_oid = []byte{0, 0, 20, 124, 0, 1}
var h221_cs_key = "Duca"
var h221_sc_key = "McDn"
/**
* @see http://msdn.microsoft.com/en-us/library/cc240509.aspx
*/
type Message uint16
const (
//server -> client
SC_CORE Message = 0x0C01
SC_SECURITY = 0x0C02
SC_NET = 0x0C03
//client -> server
CS_CORE = 0xC001
CS_SECURITY = 0xC002
CS_NET = 0xC003
CS_CLUSTER = 0xC004
CS_MONITOR = 0xC005
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240510.aspx
*/
type ColorDepth uint16
const (
RNS_UD_COLOR_8BPP ColorDepth = 0xCA01
RNS_UD_COLOR_16BPP_555 = 0xCA02
RNS_UD_COLOR_16BPP_565 = 0xCA03
RNS_UD_COLOR_24BPP = 0xCA04
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240510.aspx
*/
type HighColor uint16
const (
HIGH_COLOR_4BPP HighColor = 0x0004
HIGH_COLOR_8BPP = 0x0008
HIGH_COLOR_15BPP = 0x000f
HIGH_COLOR_16BPP = 0x0010
HIGH_COLOR_24BPP = 0x0018
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240510.aspx
*/
type Support uint16
const (
RNS_UD_24BPP_SUPPORT uint16 = 0x0001
RNS_UD_16BPP_SUPPORT = 0x0002
RNS_UD_15BPP_SUPPORT = 0x0004
RNS_UD_32BPP_SUPPORT = 0x0008
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240510.aspx
*/
type CapabilityFlag uint16
const (
RNS_UD_CS_SUPPORT_ERRINFO_PDU uint16 = 0x0001
RNS_UD_CS_WANT_32BPP_SESSION = 0x0002
RNS_UD_CS_SUPPORT_STATUSINFO_PDU = 0x0004
RNS_UD_CS_STRONG_ASYMMETRIC_KEYS = 0x0008
RNS_UD_CS_UNUSED = 0x0010
RNS_UD_CS_VALID_CONNECTION_TYPE = 0x0020
RNS_UD_CS_SUPPORT_MONITOR_LAYOUT_PDU = 0x0040
RNS_UD_CS_SUPPORT_NETCHAR_AUTODETECT = 0x0080
RNS_UD_CS_SUPPORT_DYNVC_GFX_PROTOCOL = 0x0100
RNS_UD_CS_SUPPORT_DYNAMIC_TIME_ZONE = 0x0200
RNS_UD_CS_SUPPORT_HEARTBEAT_PDU = 0x0400
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240510.aspx
*/
type ConnectionType uint8
const (
CONNECTION_TYPE_MODEM ConnectionType = 0x01
CONNECTION_TYPE_BROADBAND_LOW = 0x02
CONNECTION_TYPE_SATELLITEV = 0x03
CONNECTION_TYPE_BROADBAND_HIGH = 0x04
CONNECTION_TYPE_WAN = 0x05
CONNECTION_TYPE_LAN = 0x06
CONNECTION_TYPE_AUTODETECT = 0x07
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240510.aspx
*/
type VERSION uint32
const (
RDP_VERSION_4 VERSION = 0x00080001
RDP_VERSION_5_PLUS = 0x00080004
)
type Sequence uint16
const (
RNS_UD_SAS_DEL Sequence = 0xAA03
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240511.aspx
*/
type EncryptionMethod uint32
const (
ENCRYPTION_FLAG_40BIT uint32 = 0x00000001
ENCRYPTION_FLAG_128BIT = 0x00000002
ENCRYPTION_FLAG_56BIT = 0x00000008
FIPS_ENCRYPTION_FLAG = 0x00000010
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240518.aspx
*/
type EncryptionLevel uint32
const (
ENCRYPTION_LEVEL_NONE EncryptionLevel = 0x00000000
ENCRYPTION_LEVEL_LOW = 0x00000001
ENCRYPTION_LEVEL_CLIENT_COMPATIBLE = 0x00000002
ENCRYPTION_LEVEL_HIGH = 0x00000003
ENCRYPTION_LEVEL_FIPS = 0x00000004
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240513.aspx
*/
type ChannelOptions uint32
const (
CHANNEL_OPTION_INITIALIZED ChannelOptions = 0x80000000
CHANNEL_OPTION_ENCRYPT_RDP = 0x40000000
CHANNEL_OPTION_ENCRYPT_SC = 0x20000000
CHANNEL_OPTION_ENCRYPT_CS = 0x10000000
CHANNEL_OPTION_PRI_HIGH = 0x08000000
CHANNEL_OPTION_PRI_MED = 0x04000000
CHANNEL_OPTION_PRI_LOW = 0x02000000
CHANNEL_OPTION_COMPRESS_RDP = 0x00800000
CHANNEL_OPTION_COMPRESS = 0x00400000
CHANNEL_OPTION_SHOW_PROTOCOL = 0x00200000
REMOTE_CONTROL_PERSISTENT = 0x00100000
)
/**
* IBM_101_102_KEYS is the most common keyboard type
*/
type KeyboardType uint32
const (
KT_IBM_PC_XT_83_KEY KeyboardType = 0x00000001
KT_OLIVETTI = 0x00000002
KT_IBM_PC_AT_84_KEY = 0x00000003
KT_IBM_101_102_KEYS = 0x00000004
KT_NOKIA_1050 = 0x00000005
KT_NOKIA_9140 = 0x00000006
KT_JAPANESE = 0x00000007
)
/**
* @see http://technet.microsoft.com/en-us/library/cc766503%28WS.10%29.aspx
*/
type KeyboardLayout uint32
const (
ARABIC KeyboardLayout = 0x00000401
BULGARIAN = 0x00000402
CHINESE_US_KEYBOARD = 0x00000404
CZECH = 0x00000405
DANISH = 0x00000406
GERMAN = 0x00000407
GREEK = 0x00000408
US = 0x00000409
SPANISH = 0x0000040a
FINNISH = 0x0000040b
FRENCH = 0x0000040c
HEBREW = 0x0000040d
HUNGARIAN = 0x0000040e
ICELANDIC = 0x0000040f
ITALIAN = 0x00000410
JAPANESE = 0x00000411
KOREAN = 0x00000412
DUTCH = 0x00000413
NORWEGIAN = 0x00000414
)
/**
* @see http://msdn.microsoft.com/en-us/library/cc240521.aspx
*/
type CertificateType uint32
const (
CERT_CHAIN_VERSION_1 CertificateType = 0x00000001
CERT_CHAIN_VERSION_2 = 0x00000002
)
type ChannelDef struct {
Name string `struc:"little"`
Options uint32 `struc:"little"`
}
type ClientCoreData struct {
RdpVersion VERSION `struc:"uint32,little"`
DesktopWidth uint16 `struc:"little"`
DesktopHeight uint16 `struc:"little"`
ColorDepth ColorDepth `struc:"little"`
SasSequence Sequence `struc:"little"`
KbdLayout KeyboardLayout `struc:"little"`
ClientBuild uint32 `struc:"little"`
ClientName [32]byte `struc:"[32]byte"`
KeyboardType uint32 `struc:"little"`
KeyboardSubType uint32 `struc:"little"`
KeyboardFnKeys uint32 `struc:"little"`
ImeFileName [64]byte `struc:"[64]byte"`
PostBeta2ColorDepth ColorDepth `struc:"little"`
ClientProductId uint16 `struc:"little"`
SerialNumber uint32 `struc:"little"`
HighColorDepth HighColor `struc:"little"`
SupportedColorDepths uint16 `struc:"little"`
EarlyCapabilityFlags uint16 `struc:"little"`
ClientDigProductId [64]byte `struc:"[64]byte"`
ConnectionType uint8 `struc:"uint8"`
Pad1octet uint8 `struc:"uint8"`
ServerSelectedProtocol uint32 `struc:"little"`
}
func NewClientCoreData() *ClientCoreData {
name, _ := os.Hostname()
var ClientName [32]byte
copy(ClientName[:], core.UnicodeEncode(name)[:])
return &ClientCoreData{
RDP_VERSION_5_PLUS, 1280, 800, RNS_UD_COLOR_8BPP,
RNS_UD_SAS_DEL, US, 3790, ClientName, KT_IBM_101_102_KEYS,
0, 12, [64]byte{}, RNS_UD_COLOR_8BPP, 1, 0, HIGH_COLOR_24BPP,
RNS_UD_15BPP_SUPPORT | RNS_UD_16BPP_SUPPORT | RNS_UD_24BPP_SUPPORT | RNS_UD_32BPP_SUPPORT,
RNS_UD_CS_SUPPORT_ERRINFO_PDU, [64]byte{}, 0, 0, 0}
}
func (data *ClientCoreData) Pack() []byte {
buff := &bytes.Buffer{}
core.WriteUInt16LE(CS_CORE, buff) // 01C0
core.WriteUInt16LE(0xd8, buff) // d800
struc.Pack(buff, data)
return buff.Bytes()
}
type ClientNetworkData struct {
ChannelCount uint32
ChannelDefArray []ChannelDef
}
func NewClientNetworkData() *ClientNetworkData {
n := &ClientNetworkData{ChannelDefArray: make([]ChannelDef, 0, 100)}
/*var d1 ChannelDef
d1.Name = plugin.RDPDR_SVC_CHANNEL_NAME
d1.Options = uint32(CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP |
CHANNEL_OPTION_COMPRESS_RDP)
n.ChannelDefArray = append(n.ChannelDefArray, d1)
var d2 ChannelDef
d2.Name = plugin.RDPSND_SVC_CHANNEL_NAME
d2.Options = uint32(CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP |
CHANNEL_OPTION_COMPRESS_RDP | CHANNEL_OPTION_SHOW_PROTOCOL)
n.ChannelDefArray = append(n.ChannelDefArray, d2)*/
return n
}
func (n *ClientNetworkData) AddVirtualChannel(name string, option uint32) {
var d ChannelDef
d.Name = name
d.Options = option
n.ChannelDefArray = append(n.ChannelDefArray, d)
n.ChannelCount++
}
func (n *ClientNetworkData) Pack() []byte {
buff := &bytes.Buffer{}
core.WriteUInt16LE(CS_NET, buff) // type
length := uint16(n.ChannelCount*12 + 8)
core.WriteUInt16LE(length, buff) // len 8
core.WriteUInt32LE(n.ChannelCount, buff)
for i := 0; i < int(n.ChannelCount); i++ {
v := n.ChannelDefArray[i]
name := make([]byte, 8)
copy(name, []byte(v.Name))
core.WriteBytes(name[:], buff)
core.WriteUInt32LE(v.Options, buff)
}
return buff.Bytes()
}
type ClientSecurityData struct {
EncryptionMethods uint32
ExtEncryptionMethods uint32
}
func NewClientSecurityData() *ClientSecurityData {
return &ClientSecurityData{
ENCRYPTION_FLAG_40BIT | ENCRYPTION_FLAG_56BIT | ENCRYPTION_FLAG_128BIT,
00}
}
func (d *ClientSecurityData) Pack() []byte {
buff := &bytes.Buffer{}
core.WriteUInt16LE(CS_SECURITY, buff) // type
core.WriteUInt16LE(0x0c, buff) // len 12
core.WriteUInt32LE(d.EncryptionMethods, buff)
core.WriteUInt32LE(d.ExtEncryptionMethods, buff)
return buff.Bytes()
}
type RSAPublicKey struct {
Magic uint32 `struc:"little"` //0x31415352
Keylen uint32 `struc:"little,sizeof=Modulus"`
Bitlen uint32 `struc:"little"`
Datalen uint32 `struc:"little"`
PubExp uint32 `struc:"little"`
Modulus []byte `struc:"little"`
Padding []byte `struc:"[8]byte"`
}
type ProprietaryServerCertificate struct {
DwSigAlgId uint32 `struc:"little"` //0x00000001
DwKeyAlgId uint32 `struc:"little"` //0x00000001
PublicKeyBlobType uint16 `struc:"little"` //0x0006
PublicKeyBlobLen uint16 `struc:"little,sizeof=PublicKeyBlob"`
PublicKeyBlob RSAPublicKey `struc:"little"`
SignatureBlobType uint16 `struc:"little"` //0x0008
SignatureBlobLen uint16 `struc:"little,sizeof=SignatureBlob"`
SignatureBlob []byte `struc:"little"`
//PaddingLen uint16 `struc:"little,sizeof=Padding,skip"`
Padding []byte `struc:"[8]byte"`
}
func (p *ProprietaryServerCertificate) GetPublicKey() (*rsa.PublicKey, error) {
b := new(big.Int).SetBytes(core.Reverse(p.PublicKeyBlob.Modulus))
e := new(big.Int).SetInt64(int64(p.PublicKeyBlob.PubExp))
return &rsa.PublicKey{N: b, E: int(e.Int64())}, nil
}
func (p *ProprietaryServerCertificate) Verify() bool {
return true
}
func (p *ProprietaryServerCertificate) Encrypt() []byte {
//todo
return nil
}
func (p *ProprietaryServerCertificate) Unpack(r io.Reader) error {
p.DwSigAlgId, _ = core.ReadUInt32LE(r)
p.DwKeyAlgId, _ = core.ReadUInt32LE(r)
p.PublicKeyBlobType, _ = core.ReadUint16LE(r)
p.PublicKeyBlobLen, _ = core.ReadUint16LE(r)
var b RSAPublicKey
b.Magic, _ = core.ReadUInt32LE(r)
b.Keylen, _ = core.ReadUInt32LE(r)
b.Bitlen, _ = core.ReadUInt32LE(r)
b.Datalen, _ = core.ReadUInt32LE(r)
b.PubExp, _ = core.ReadUInt32LE(r)
b.Modulus, _ = core.ReadBytes(int(b.Keylen)-8, r)
b.Padding, _ = core.ReadBytes(8, r)
p.PublicKeyBlob = b
p.SignatureBlobType, _ = core.ReadUint16LE(r)
p.SignatureBlobLen, _ = core.ReadUint16LE(r)
p.SignatureBlob, _ = core.ReadBytes(int(p.SignatureBlobLen)-8, r)
p.Padding, _ = core.ReadBytes(8, r)
return nil
}
type CertBlob struct {
CbCert uint32 `struc:"little,sizeof=AbCert"`
AbCert []byte `struc:"little"`
}
type X509CertificateChain struct {
NumCertBlobs uint32 `struc:"little,sizeof=CertBlobArray"`
CertBlobArray []CertBlob `struc:"little"`
Padding []byte `struc:"[12]byte"`
}
func (x *X509CertificateChain) GetPublicKey() (*rsa.PublicKey, error) {
if len(x.CertBlobArray) == 0 {
return nil, errors.New("empty certificate chain")
}
data := x.CertBlobArray[len(x.CertBlobArray)-1].AbCert
cert, err := x509.ParseCertificate(data)
if err != nil {
return nil, fmt.Errorf("parse certificate: %w", err)
}
if cert.PublicKey == nil {
var pubKeyInfo struct {
Algorithm pkix.AlgorithmIdentifier
SubjectPublicKey asn1.BitString
}
_, err = asn1.Unmarshal(cert.RawSubjectPublicKeyInfo, &pubKeyInfo)
if err != nil {
return nil, fmt.Errorf("unmarshal public key info: %w", err)
}
rsaPublicKey, err := x509.ParsePKCS1PublicKey(pubKeyInfo.SubjectPublicKey.Bytes)
if err != nil {
return nil, fmt.Errorf("parse PKCS1 public key: %w", err)
}
return rsaPublicKey, nil
}
rsaPublicKey, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("unsupported public key type: %T", cert.PublicKey)
}
return rsaPublicKey, nil
}
func (x *X509CertificateChain) Verify() bool {
return true
}
func (x *X509CertificateChain) Encrypt() []byte {
//todo
return nil
}
func (x *X509CertificateChain) Unpack(r io.Reader) error {
return struc.Unpack(r, x)
}
type ServerCoreData struct {
RdpVersion VERSION `struc:"uint32,little"`
ClientRequestedProtocol uint32 `struc:"little"`
EarlyCapabilityFlags uint32 `struc:"little"`
}
func NewServerCoreData() *ServerCoreData {
return &ServerCoreData{
RDP_VERSION_5_PLUS, 0, 0}
}
func (d *ServerCoreData) Serialize() []byte {
return []byte{}
}
func (d *ServerCoreData) ScType() Message {
return SC_CORE
}
func (d *ServerCoreData) Unpack(r io.Reader) error {
version, _ := core.ReadUInt32LE(r)
d.RdpVersion = VERSION(version)
d.ClientRequestedProtocol, _ = core.ReadUInt32LE(r)
d.EarlyCapabilityFlags, _ = core.ReadUInt32LE(r)
return nil
//return struc.Unpack(r, d)
}
type ServerNetworkData struct {
MCSChannelId uint16 `struc:"little"`
ChannelCount uint16 `struc:"little,sizeof=ChannelIdArray"`
ChannelIdArray []uint16 `struc:"little"`
}
func NewServerNetworkData() *ServerNetworkData {
return &ServerNetworkData{}
}
func (d *ServerNetworkData) ScType() Message {
return SC_NET
}
func (d *ServerNetworkData) Unpack(r io.Reader) error {
return struc.Unpack(r, d)
}
type CertData interface {
GetPublicKey() (*rsa.PublicKey, error)
Verify() bool
Unpack(io.Reader) error
}
type ServerCertificate struct {
DwVersion uint32
CertData CertData
}
func (sc *ServerCertificate) Unpack(r io.Reader) error {
sc.DwVersion, _ = core.ReadUInt32LE(r)
var cd CertData
switch CertificateType(sc.DwVersion & 0x7fffffff) {
case CERT_CHAIN_VERSION_1:
glog.Debug("ProprietaryServerCertificate")
cd = &ProprietaryServerCertificate{}
case CERT_CHAIN_VERSION_2:
glog.Debug("X509CertificateChain")
cd = &X509CertificateChain{}
default:
glog.Error("Unsupported version:", sc.DwVersion&0x7fffffff)
return errors.New("Unsupported version")
}
if cd != nil {
err := cd.Unpack(r)
if err != nil {
glog.Error("Unpack:", err)
return err
}
}
sc.CertData = cd
return nil
}
type ServerSecurityData struct {
EncryptionMethod uint32 `struc:"little"`
EncryptionLevel uint32 `struc:"little"`
ServerRandomLen uint32 //0x00000020
ServerCertLen uint32
ServerRandom []byte
ServerCertificate ServerCertificate
}
func NewServerSecurityData() *ServerSecurityData {
return &ServerSecurityData{
0, 0, 0x00000020, 0, []byte{}, ServerCertificate{}}
}
func (d *ServerSecurityData) ScType() Message {
return SC_SECURITY
}
func (s *ServerSecurityData) Unpack(r io.Reader) error {
s.EncryptionMethod, _ = core.ReadUInt32LE(r)
s.EncryptionLevel, _ = core.ReadUInt32LE(r)
if !(s.EncryptionMethod == 0 && s.EncryptionLevel == 0) {
s.ServerRandomLen, _ = core.ReadUInt32LE(r)
s.ServerCertLen, _ = core.ReadUInt32LE(r)
s.ServerRandom, _ = core.ReadBytes(int(s.ServerRandomLen), r)
var sc ServerCertificate
data, _ := core.ReadBytes(int(s.ServerCertLen), r)
rd := bytes.NewReader(data)
err := sc.Unpack(rd)
if err != nil {
return err
}
s.ServerCertificate = sc
}
return nil
}
func MakeConferenceCreateRequest(userData []byte) []byte {
buff := &bytes.Buffer{}
per.WriteChoice(0, buff) // 00
per.WriteObjectIdentifier(t124_02_98_oid, buff) // 05:00:14:7c:00:01
per.WriteLength(len(userData)+14, buff)
per.WriteChoice(0, buff) // 00
per.WriteSelection(0x08, buff) // 08
per.WriteNumericString("1", 1, buff) // 00 10
per.WritePadding(1, buff) // 00
per.WriteNumberOfSet(1, buff) // 01
per.WriteChoice(0xc0, buff) // c0
per.WriteOctetStream(h221_cs_key, 4, buff) // 00 44:75:63:61
per.WriteOctetStream(string(userData), 0, buff)
return buff.Bytes()
}
type ScData interface {
ScType() Message
Unpack(io.Reader) error
}
func ReadConferenceCreateResponse(data []byte) []interface{} {
ret := make([]interface{}, 0, 3)
r := bytes.NewReader(data)
per.ReadChoice(r)
if !per.ReadObjectIdentifier(r, t124_02_98_oid) {
glog.Error("NODE_RDP_PROTOCOL_T125_GCC_BAD_OBJECT_IDENTIFIER_T124")
return ret
}
per.ReadLength(r)
per.ReadChoice(r)
per.ReadInteger16(r)
per.ReadInteger(r)
per.ReadEnumerates(r)
per.ReadNumberOfSet(r)
per.ReadChoice(r)
if !per.ReadOctetStream(r, h221_sc_key, 4) {
glog.Error("NODE_RDP_PROTOCOL_T125_GCC_BAD_H221_SC_KEY")
return ret
}
ln, _ := per.ReadLength(r)
for ln > 0 {
t, _ := core.ReadUint16LE(r)
glog.Debugf("Message type 0x%x,ln:%v", t, ln)
l, _ := core.ReadUint16LE(r)
dataBytes, _ := core.ReadBytes(int(l)-4, r)
ln = ln - l
var d ScData
switch Message(t) {
case SC_CORE:
d = &ServerCoreData{}
case SC_SECURITY:
d = &ServerSecurityData{}
case SC_NET:
d = &ServerNetworkData{}
default:
glog.Error("Unknown type", t)
continue
}
if d != nil {
r := bytes.NewReader(dataBytes)
err := d.Unpack(r)
if err != nil {
glog.Warn("Unpack:", err)
}
ret = append(ret, d)
}
}
return ret
}
+585
View File
@@ -0,0 +1,585 @@
package t125
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"reflect"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/ber"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/gcc"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/t125/per"
)
// take idea from https://github.com/Madnikulin50/gordp
// Multiple Channel Service layer
type MCSMessage uint8
const (
MCS_TYPE_CONNECT_INITIAL MCSMessage = 0x65
MCS_TYPE_CONNECT_RESPONSE = 0x66
)
type MCSDomainPDU uint16
const (
ERECT_DOMAIN_REQUEST MCSDomainPDU = 1
DISCONNECT_PROVIDER_ULTIMATUM = 8
ATTACH_USER_REQUEST = 10
ATTACH_USER_CONFIRM = 11
CHANNEL_JOIN_REQUEST = 14
CHANNEL_JOIN_CONFIRM = 15
SEND_DATA_REQUEST = 25
SEND_DATA_INDICATION = 26
)
const (
MCS_GLOBAL_CHANNEL_ID uint16 = 1003
MCS_USERCHANNEL_BASE = 1001
)
const (
GLOBAL_CHANNEL_NAME = "global"
)
/**
* Format MCS PDULayer header packet
* @param mcsPdu {integer}
* @param options {integer}
* @returns {type.UInt8} headers
*/
func writeMCSPDUHeader(mcsPdu MCSDomainPDU, options uint8, w io.Writer) {
core.WriteUInt8((uint8(mcsPdu)<<2)|options, w)
}
func readMCSPDUHeader(options uint8, mcsPdu MCSDomainPDU) bool {
return (options >> 2) == uint8(mcsPdu)
}
type DomainParameters struct {
MaxChannelIds int
MaxUserIds int
MaxTokenIds int
NumPriorities int
MinThoughput int
MaxHeight int
MaxMCSPDUsize int
ProtocolVersion int
}
/**
* @see http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25
* @returns {asn1.univ.Sequence}
*/
func NewDomainParameters(
maxChannelIds int,
maxUserIds int,
maxTokenIds int,
numPriorities int,
minThoughput int,
maxHeight int,
maxMCSPDUsize int,
protocolVersion int) *DomainParameters {
return &DomainParameters{maxChannelIds, maxUserIds, maxTokenIds,
numPriorities, minThoughput, maxHeight, maxMCSPDUsize, protocolVersion}
}
func (d *DomainParameters) BER() []byte {
buff := &bytes.Buffer{}
ber.WriteInteger(d.MaxChannelIds, buff)
ber.WriteInteger(d.MaxUserIds, buff)
ber.WriteInteger(d.MaxTokenIds, buff)
ber.WriteInteger(1, buff)
ber.WriteInteger(0, buff)
ber.WriteInteger(1, buff)
ber.WriteInteger(d.MaxMCSPDUsize, buff)
ber.WriteInteger(2, buff)
return buff.Bytes()
}
func ReadDomainParameters(r io.Reader) (*DomainParameters, error) {
if !ber.ReadUniversalTag(ber.TAG_SEQUENCE, true, r) {
return nil, errors.New("bad BER tags")
}
d := &DomainParameters{}
ber.ReadLength(r)
d.MaxChannelIds, _ = ber.ReadInteger(r)
d.MaxUserIds, _ = ber.ReadInteger(r)
d.MaxTokenIds, _ = ber.ReadInteger(r)
ber.ReadInteger(r)
ber.ReadInteger(r)
ber.ReadInteger(r)
d.MaxMCSPDUsize, _ = ber.ReadInteger(r)
ber.ReadInteger(r)
return d, nil
}
/**
* @see http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25
* @param userData {Buffer}
* @returns {asn1.univ.Sequence}
*/
type ConnectInitial struct {
CallingDomainSelector []byte
CalledDomainSelector []byte
UpwardFlag bool
TargetParameters DomainParameters
MinimumParameters DomainParameters
MaximumParameters DomainParameters
UserData []byte
}
func NewConnectInitial(userData []byte) ConnectInitial {
return ConnectInitial{[]byte{0x1},
[]byte{0x1},
true,
*NewDomainParameters(34, 2, 0, 1, 0, 1, 0xffff, 2),
*NewDomainParameters(1, 1, 1, 1, 0, 1, 0x420, 2),
*NewDomainParameters(0xffff, 0xfc17, 0xffff, 1, 0, 1, 0xffff, 2),
userData}
}
func (c *ConnectInitial) BER() []byte {
buff := &bytes.Buffer{}
ber.WriteOctetstring(string(c.CallingDomainSelector), buff)
ber.WriteOctetstring(string(c.CalledDomainSelector), buff)
ber.WriteBoolean(c.UpwardFlag, buff)
ber.WriteEncodedDomainParams(c.TargetParameters.BER(), buff)
ber.WriteEncodedDomainParams(c.MinimumParameters.BER(), buff)
ber.WriteEncodedDomainParams(c.MaximumParameters.BER(), buff)
ber.WriteOctetstring(string(c.UserData), buff)
return buff.Bytes()
}
/**
* @see http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25
* @returns {asn1.univ.Sequence}
*/
type ConnectResponse struct {
result uint8
calledConnectId int
domainParameters *DomainParameters
userData []byte
}
func NewConnectResponse(userData []byte) *ConnectResponse {
return &ConnectResponse{0,
0,
NewDomainParameters(22, 3, 0, 1, 0, 1, 0xfff8, 2),
userData}
}
func ReadConnectResponse(r io.Reader) (*ConnectResponse, error) {
c := &ConnectResponse{}
var err error
_, err = ber.ReadApplicationTag(MCS_TYPE_CONNECT_RESPONSE, r)
if err != nil {
return nil, err
}
c.result, err = ber.ReadEnumerated(r)
if err != nil {
return nil, err
}
c.calledConnectId, err = ber.ReadInteger(r)
c.domainParameters, err = ReadDomainParameters(r)
if err != nil {
return nil, err
}
if !ber.ReadUniversalTag(ber.TAG_OCTET_STRING, false, r) {
return nil, errors.New("invalid expected BER tag")
}
dataLen, _ := ber.ReadLength(r)
c.userData, err = core.ReadBytes(dataLen, r)
return c, err
}
type MCSChannelInfo struct {
ID uint16
Name string
}
type MCS struct {
emission.Emitter
transport core.Transport
recvOpCode MCSDomainPDU
sendOpCode MCSDomainPDU
channels []MCSChannelInfo
}
func NewMCS(t core.Transport, recvOpCode MCSDomainPDU, sendOpCode MCSDomainPDU) *MCS {
m := &MCS{
*emission.NewEmitter(),
t,
recvOpCode,
sendOpCode,
[]MCSChannelInfo{{MCS_GLOBAL_CHANNEL_ID, GLOBAL_CHANNEL_NAME}},
}
m.transport.On("close", func() {
m.Emit("close")
}).On("error", func(err error) {
m.Emit("error", err)
})
return m
}
func (x *MCS) Read(b []byte) (n int, err error) {
return x.transport.Read(b)
}
func (x *MCS) Write(b []byte) (n int, err error) {
return x.transport.Write(b)
}
func (m *MCS) Close() error {
return m.transport.Close()
}
type MCSClient struct {
*MCS
clientCoreData *gcc.ClientCoreData
clientNetworkData *gcc.ClientNetworkData
clientSecurityData *gcc.ClientSecurityData
serverCoreData *gcc.ServerCoreData
serverNetworkData *gcc.ServerNetworkData
serverSecurityData *gcc.ServerSecurityData
channelsConnected int
userId uint16
nbChannelRequested int
}
func NewMCSClient(t core.Transport) *MCSClient {
c := &MCSClient{
MCS: NewMCS(t, SEND_DATA_INDICATION, SEND_DATA_REQUEST),
clientCoreData: gcc.NewClientCoreData(),
clientNetworkData: gcc.NewClientNetworkData(),
clientSecurityData: gcc.NewClientSecurityData(),
userId: 1 + MCS_USERCHANNEL_BASE,
}
c.transport.On("connect", c.connect)
return c
}
func (c *MCSClient) SetClientCoreData(width, height uint16) {
c.clientCoreData.DesktopWidth = width
c.clientCoreData.DesktopHeight = height
}
//func (c *MCSClient) connect(selectedProtocol uint32) {
// glog.Debug("mcs client on connect", selectedProtocol)
// c.clientCoreData.ServerSelectedProtocol = selectedProtocol
//
// // sendConnectInitial
// userDataBuff := bytes.Buffer{}
// userDataBuff.Write(c.clientCoreData.Pack())
// userDataBuff.Write(c.clientNetworkData.Pack())
// userDataBuff.Write(c.clientSecurityData.Pack())
//
// ccReq := gcc.MakeConferenceCreateRequest(userDataBuff.Bytes())
// connectInitial := NewConnectInitial(ccReq)
// connectInitialBerEncoded := connectInitial.BER()
//
// dataBuff := &bytes.Buffer{}
// ber.WriteApplicationTag(uint8(MCS_TYPE_CONNECT_INITIAL), len(connectInitialBerEncoded), dataBuff)
// dataBuff.Write(connectInitialBerEncoded)
//
// _, err := c.transport.Write(dataBuff.Bytes())
// if err != nil {
// c.Emit("error", errors.New(fmt.Sprintf("mcs sendConnectInitial write error %v", err)))
// return
// }
// glog.Debug("mcs wait for data event")
// c.transport.Once("data", c.recvConnectResponse)
//}
func (c *MCSClient) connect(selectedProtocol uint32) {
glog.Debug("mcs client on connect", selectedProtocol)
c.clientCoreData.ServerSelectedProtocol = selectedProtocol
glog.Debugf("clientCoreData:%+v", c.clientCoreData)
glog.Debugf("clientNetworkData:%+v", c.clientNetworkData)
glog.Debugf("clientSecurityData:%+v", c.clientSecurityData)
// sendConnectclientCoreDataInitial
userDataBuff := bytes.Buffer{}
userDataBuff.Write(c.clientCoreData.Pack())
userDataBuff.Write(c.clientNetworkData.Pack())
userDataBuff.Write(c.clientSecurityData.Pack())
ccReq := gcc.MakeConferenceCreateRequest(userDataBuff.Bytes())
connectInitial := NewConnectInitial(ccReq)
connectInitialBerEncoded := connectInitial.BER()
dataBuff := &bytes.Buffer{}
ber.WriteApplicationTag(uint8(MCS_TYPE_CONNECT_INITIAL), len(connectInitialBerEncoded), dataBuff)
dataBuff.Write(connectInitialBerEncoded)
_, err := c.transport.Write(dataBuff.Bytes())
if err != nil {
c.Emit("error", errors.New(fmt.Sprintf("mcs sendConnectInitial write error %v", err)))
return
}
glog.Debug("mcs wait for data event")
c.transport.Once("data", c.recvConnectResponse)
}
func (c *MCSClient) recvConnectResponse(s []byte) {
glog.Debug("mcs recvConnectResponse", hex.EncodeToString(s))
cResp, err := ReadConnectResponse(bytes.NewReader(s))
if err != nil {
c.Emit("error", errors.New(fmt.Sprintf("ReadConnectResponse %v", err)))
return
}
// record server gcc block
serverSettings := gcc.ReadConferenceCreateResponse(cResp.userData)
for _, v := range serverSettings {
switch v.(type) {
case *gcc.ServerSecurityData:
c.serverSecurityData = v.(*gcc.ServerSecurityData)
case *gcc.ServerCoreData:
c.serverCoreData = v.(*gcc.ServerCoreData)
case *gcc.ServerNetworkData:
c.serverNetworkData = v.(*gcc.ServerNetworkData)
default:
err := errors.New(fmt.Sprintf("unhandle server gcc block %v", reflect.TypeOf(v)))
glog.Error(err)
c.Emit("error", err)
return
}
}
glog.Debugf("serverSecurityData: %+v", c.serverSecurityData)
glog.Debugf("serverCoreData: %+v", c.serverCoreData)
glog.Info("version", c.serverCoreData.RdpVersion, c.serverCoreData.ClientRequestedProtocol)
glog.Debugf("serverNetworkData: %+v", c.serverNetworkData)
glog.Debug("mcs sendErectDomainRequest")
c.sendErectDomainRequest()
glog.Debug("mcs sendAttachUserRequest")
c.sendAttachUserRequest()
c.transport.Once("data", c.recvAttachUserConfirm)
}
func (c *MCSClient) sendErectDomainRequest() {
buff := &bytes.Buffer{}
writeMCSPDUHeader(ERECT_DOMAIN_REQUEST, 0, buff)
per.WriteInteger(0, buff)
per.WriteInteger(0, buff)
c.transport.Write(buff.Bytes())
}
func (c *MCSClient) sendAttachUserRequest() {
buff := &bytes.Buffer{}
writeMCSPDUHeader(ATTACH_USER_REQUEST, 0, buff)
c.transport.Write(buff.Bytes())
}
func (c *MCSClient) recvAttachUserConfirm(s []byte) {
glog.Debug("mcs recvAttachUserConfirm", hex.EncodeToString(s))
r := bytes.NewReader(s)
option, err := core.ReadUInt8(r)
if err != nil {
c.Emit("error", err)
return
}
if !readMCSPDUHeader(option, ATTACH_USER_CONFIRM) {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_BAD_HEADER"))
return
}
e, err := per.ReadEnumerates(r)
if err != nil {
c.Emit("error", err)
return
}
if e != 0 {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_SERVER_REJECT_USER'"))
return
}
userId, _ := per.ReadInteger16(r)
userId += MCS_USERCHANNEL_BASE
c.userId = userId
c.channels = append(c.channels, MCSChannelInfo{userId, "user"})
c.connectChannels()
}
func (c *MCSClient) connectChannels() {
glog.Debug("mcs connectChannels:", c.channelsConnected, ":", len(c.channels))
if c.channelsConnected == len(c.channels) && c.serverNetworkData != nil {
if c.nbChannelRequested < int(c.serverNetworkData.ChannelCount) {
//static virtual channel
chanId := c.serverNetworkData.ChannelIdArray[c.nbChannelRequested]
c.nbChannelRequested++
c.sendChannelJoinRequest(chanId)
c.transport.Once("data", c.recvChannelJoinConfirm)
return
}
c.transport.On("data", c.recvData)
// send client and sever gcc informations callback to sec
clientData := make([]interface{}, 0)
clientData = append(clientData, c.clientCoreData)
clientData = append(clientData, c.clientSecurityData)
clientData = append(clientData, c.clientNetworkData)
serverData := make([]interface{}, 0)
serverData = append(serverData, c.serverCoreData)
serverData = append(serverData, c.serverSecurityData)
glog.Debug("msc connectChannels callback to sec")
c.Emit("connect", clientData, serverData, c.userId, c.channels)
return
}
// sendChannelJoinRequest
glog.Debug("sendChannelJoinRequest:", c.channels[c.channelsConnected].Name)
c.sendChannelJoinRequest(c.channels[c.channelsConnected].ID)
c.transport.Once("data", c.recvChannelJoinConfirm)
}
func (c *MCSClient) sendChannelJoinRequest(channelId uint16) {
glog.Debug("mcs sendChannelJoinRequest", channelId)
buff := &bytes.Buffer{}
writeMCSPDUHeader(CHANNEL_JOIN_REQUEST, 0, buff)
per.WriteInteger16(c.userId-MCS_USERCHANNEL_BASE, buff)
per.WriteInteger16(channelId, buff)
c.transport.Write(buff.Bytes())
}
func (c *MCSClient) recvData(s []byte) {
glog.Debug("msc on data recvData:", hex.EncodeToString(s))
r := bytes.NewReader(s)
option, err := core.ReadUInt8(r)
if err != nil {
c.Emit("error", err)
return
}
if readMCSPDUHeader(option, DISCONNECT_PROVIDER_ULTIMATUM) {
c.Emit("error", errors.New("MCS DISCONNECT_PROVIDER_ULTIMATUM"))
c.transport.Close()
return
} else if !readMCSPDUHeader(option, c.recvOpCode) {
c.Emit("error", errors.New("Invalid expected MCS opcode receive data"))
return
}
userId, _ := per.ReadInteger16(r)
userId += MCS_USERCHANNEL_BASE
channelId, _ := per.ReadInteger16(r)
per.ReadEnumerates(r)
size, _ := per.ReadLength(r)
// channel ID doesn't match a requested layer
found := false
channelName := ""
for _, channel := range c.channels {
if channel.ID == channelId {
found = true
channelName = channel.Name
break
}
}
if !found {
glog.Error("mcs receive data for an unconnected layer")
return
}
left, err := core.ReadBytes(int(size), r)
if err != nil {
c.Emit("error", errors.New(fmt.Sprintf("mcs recvData get data error %v", err)))
return
}
glog.Debugf("mcs emit channel<%s>:%v", channelName, left)
c.Emit("sec", channelName, left)
}
func (c *MCSClient) recvChannelJoinConfirm(s []byte) {
glog.Debug("mcs recvChannelJoinConfirm", hex.EncodeToString(s))
r := bytes.NewReader(s)
option, err := core.ReadUInt8(r)
if err != nil {
c.Emit("error", err)
return
}
if !readMCSPDUHeader(option, CHANNEL_JOIN_CONFIRM) {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_WAIT_CHANNEL_JOIN_CONFIRM"))
return
}
confirm, _ := per.ReadEnumerates(r)
userId, _ := per.ReadInteger16(r)
userId += MCS_USERCHANNEL_BASE
if c.userId != userId {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_INVALID_USER_ID"))
return
}
channelId, _ := per.ReadInteger16(r)
if (confirm != 0) && (channelId == uint16(MCS_GLOBAL_CHANNEL_ID) || channelId == c.userId) {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_SERVER_MUST_CONFIRM_STATIC_CHANNEL"))
return
}
glog.Debug("Confirm channelId:", channelId)
if confirm == 0 && c.serverNetworkData != nil {
for i := 0; i < int(c.serverNetworkData.ChannelCount); i++ {
if channelId == c.serverNetworkData.ChannelIdArray[i] {
var t MCSChannelInfo
t.ID = channelId
t.Name = string(c.clientNetworkData.ChannelDefArray[i].Name[:])
c.channels = append(c.channels, t)
}
}
}
c.channelsConnected++
c.connectChannels()
}
func (c *MCSClient) Pack(data []byte, channelId uint16) []byte {
buff := &bytes.Buffer{}
writeMCSPDUHeader(c.sendOpCode, 0, buff)
per.WriteInteger16(c.userId-MCS_USERCHANNEL_BASE, buff)
per.WriteInteger16(channelId, buff)
core.WriteUInt8(0x70, buff)
per.WriteLength(len(data), buff)
core.WriteBytes(data, buff)
glog.Debug("MCSClient write", channelId, ":", hex.EncodeToString(buff.Bytes()))
return buff.Bytes()
}
func (c *MCSClient) Write(data []byte) (n int, err error) {
data = c.Pack(data, c.channels[0].ID)
return c.transport.Write(data)
}
func (c *MCSClient) SendToChannel(channel string, data []byte) (n int, err error) {
channelId := c.channels[0].ID
for _, ch := range c.channels {
if channel == ch.Name {
channelId = ch.ID
break
}
}
data = c.Pack(data, channelId)
return c.transport.Write(data)
}
+574
View File
@@ -0,0 +1,574 @@
package t125
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"reflect"
"github.com/xxx/wscan/mylib/grdp/plugin/rail"
"github.com/xxx/wscan/mylib/grdp/plugin/drdynvc"
"github.com/xxx/wscan/mylib/grdp/core"
"github.com/xxx/wscan/mylib/grdp/emission"
"github.com/xxx/wscan/mylib/grdp/glog"
"github.com/xxx/wscan/mylib/grdp/protocol/t125/ber"
"github.com/xxx/wscan/mylib/grdp/protocol/t125/gcc"
"github.com/xxx/wscan/mylib/grdp/protocol/t125/per"
)
// take idea from https://github.com/Madnikulin50/gordp
// Multiple Channel Service layer
type MCSMessage uint8
const (
MCS_TYPE_CONNECT_INITIAL MCSMessage = 0x65
MCS_TYPE_CONNECT_RESPONSE = 0x66
)
type MCSDomainPDU uint16
const (
ERECT_DOMAIN_REQUEST MCSDomainPDU = 1
DISCONNECT_PROVIDER_ULTIMATUM = 8
ATTACH_USER_REQUEST = 10
ATTACH_USER_CONFIRM = 11
CHANNEL_JOIN_REQUEST = 14
CHANNEL_JOIN_CONFIRM = 15
SEND_DATA_REQUEST = 25
SEND_DATA_INDICATION = 26
)
const (
MCS_GLOBAL_CHANNEL_ID uint16 = 1003
MCS_USERCHANNEL_BASE = 1001
)
const (
GLOBAL_CHANNEL_NAME = "global"
)
/**
* Format MCS PDULayer header packet
* @param mcsPdu {integer}
* @param options {integer}
* @returns {type.UInt8} headers
*/
func writeMCSPDUHeader(mcsPdu MCSDomainPDU, options uint8, w io.Writer) {
core.WriteUInt8((uint8(mcsPdu)<<2)|options, w)
}
func readMCSPDUHeader(options uint8, mcsPdu MCSDomainPDU) bool {
return (options >> 2) == uint8(mcsPdu)
}
type DomainParameters struct {
MaxChannelIds int
MaxUserIds int
MaxTokenIds int
NumPriorities int
MinThoughput int
MaxHeight int
MaxMCSPDUsize int
ProtocolVersion int
}
/**
* @see http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25
* @returns {asn1.univ.Sequence}
*/
func NewDomainParameters(
maxChannelIds int,
maxUserIds int,
maxTokenIds int,
numPriorities int,
minThoughput int,
maxHeight int,
maxMCSPDUsize int,
protocolVersion int) *DomainParameters {
return &DomainParameters{maxChannelIds, maxUserIds, maxTokenIds,
numPriorities, minThoughput, maxHeight, maxMCSPDUsize, protocolVersion}
}
func (d *DomainParameters) BER() []byte {
buff := &bytes.Buffer{}
ber.WriteInteger(d.MaxChannelIds, buff)
ber.WriteInteger(d.MaxUserIds, buff)
ber.WriteInteger(d.MaxTokenIds, buff)
ber.WriteInteger(1, buff)
ber.WriteInteger(0, buff)
ber.WriteInteger(1, buff)
ber.WriteInteger(d.MaxMCSPDUsize, buff)
ber.WriteInteger(2, buff)
return buff.Bytes()
}
func ReadDomainParameters(r io.Reader) (*DomainParameters, error) {
if !ber.ReadUniversalTag(ber.TAG_SEQUENCE, true, r) {
return nil, errors.New("bad BER tags")
}
d := &DomainParameters{}
ber.ReadLength(r)
d.MaxChannelIds, _ = ber.ReadInteger(r)
d.MaxUserIds, _ = ber.ReadInteger(r)
d.MaxTokenIds, _ = ber.ReadInteger(r)
ber.ReadInteger(r)
ber.ReadInteger(r)
ber.ReadInteger(r)
d.MaxMCSPDUsize, _ = ber.ReadInteger(r)
ber.ReadInteger(r)
return d, nil
}
/**
* @see http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25
* @param userData {Buffer}
* @returns {asn1.univ.Sequence}
*/
type ConnectInitial struct {
CallingDomainSelector []byte
CalledDomainSelector []byte
UpwardFlag bool
TargetParameters DomainParameters
MinimumParameters DomainParameters
MaximumParameters DomainParameters
UserData []byte
}
func NewConnectInitial(userData []byte) ConnectInitial {
return ConnectInitial{[]byte{0x1},
[]byte{0x1},
true,
*NewDomainParameters(34, 2, 0, 1, 0, 1, 0xffff, 2),
*NewDomainParameters(1, 1, 1, 1, 0, 1, 0x420, 2),
*NewDomainParameters(0xffff, 0xfc17, 0xffff, 1, 0, 1, 0xffff, 2),
userData}
}
func (c *ConnectInitial) BER() []byte {
buff := &bytes.Buffer{}
ber.WriteOctetstring(string(c.CallingDomainSelector), buff)
ber.WriteOctetstring(string(c.CalledDomainSelector), buff)
ber.WriteBoolean(c.UpwardFlag, buff)
ber.WriteEncodedDomainParams(c.TargetParameters.BER(), buff)
ber.WriteEncodedDomainParams(c.MinimumParameters.BER(), buff)
ber.WriteEncodedDomainParams(c.MaximumParameters.BER(), buff)
ber.WriteOctetstring(string(c.UserData), buff)
return buff.Bytes()
}
/**
* @see http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25
* @returns {asn1.univ.Sequence}
*/
type ConnectResponse struct {
result uint8
calledConnectId int
domainParameters *DomainParameters
userData []byte
}
func NewConnectResponse(userData []byte) *ConnectResponse {
return &ConnectResponse{0,
0,
NewDomainParameters(22, 3, 0, 1, 0, 1, 0xfff8, 2),
userData}
}
func ReadConnectResponse(r io.Reader) (*ConnectResponse, error) {
c := &ConnectResponse{}
var err error
_, err = ber.ReadApplicationTag(MCS_TYPE_CONNECT_RESPONSE, r)
if err != nil {
return nil, err
}
c.result, err = ber.ReadEnumerated(r)
if err != nil {
return nil, err
}
c.calledConnectId, err = ber.ReadInteger(r)
c.domainParameters, err = ReadDomainParameters(r)
if err != nil {
return nil, err
}
if !ber.ReadUniversalTag(ber.TAG_OCTET_STRING, false, r) {
return nil, errors.New("invalid expected BER tag")
}
dataLen, _ := ber.ReadLength(r)
c.userData, err = core.ReadBytes(dataLen, r)
return c, err
}
type MCSChannelInfo struct {
ID uint16
Name string
}
type MCS struct {
emission.Emitter
transport core.Transport
recvOpCode MCSDomainPDU
sendOpCode MCSDomainPDU
channels []MCSChannelInfo
}
func NewMCS(t core.Transport, recvOpCode MCSDomainPDU, sendOpCode MCSDomainPDU) *MCS {
m := &MCS{
*emission.NewEmitter(),
t,
recvOpCode,
sendOpCode,
[]MCSChannelInfo{{MCS_GLOBAL_CHANNEL_ID, GLOBAL_CHANNEL_NAME}},
}
m.transport.On("close", func() {
m.Emit("close")
}).On("error", func(err error) {
m.Emit("error", err)
})
return m
}
func (x *MCS) Read(b []byte) (n int, err error) {
return x.transport.Read(b)
}
func (x *MCS) Write(b []byte) (n int, err error) {
return x.transport.Write(b)
}
func (m *MCS) Close() error {
return m.transport.Close()
}
type MCSClient struct {
*MCS
clientCoreData *gcc.ClientCoreData
clientNetworkData *gcc.ClientNetworkData
clientSecurityData *gcc.ClientSecurityData
serverCoreData *gcc.ServerCoreData
serverNetworkData *gcc.ServerNetworkData
serverSecurityData *gcc.ServerSecurityData
channelsConnected int
userId uint16
nbChannelRequested int
}
func NewMCSClient(t core.Transport) *MCSClient {
c := &MCSClient{
MCS: NewMCS(t, SEND_DATA_INDICATION, SEND_DATA_REQUEST),
clientCoreData: gcc.NewClientCoreData(),
clientNetworkData: gcc.NewClientNetworkData(),
clientSecurityData: gcc.NewClientSecurityData(),
userId: 1 + MCS_USERCHANNEL_BASE,
}
c.transport.On("connect", c.connect)
return c
}
func (c *MCSClient) SetClientDesktop(width, height uint16) {
c.clientCoreData.DesktopWidth = width
c.clientCoreData.DesktopHeight = height
}
func (c *MCSClient) SetClientDynvcProtocol() {
c.clientCoreData.EarlyCapabilityFlags = gcc.RNS_UD_CS_SUPPORT_DYNVC_GFX_PROTOCOL
c.clientNetworkData.AddVirtualChannel(drdynvc.ChannelName, drdynvc.ChannelOption)
}
func (c *MCSClient) SetClientRemoteProgram() {
c.clientNetworkData.AddVirtualChannel(rail.ChannelName, rail.ChannelOption)
}
func (c *MCSClient) SetClientCliprdr() {
//c.clientNetworkData.AddVirtualChannel(cliprdr.ChannelName, cliprdr.ChannelOption)
}
func (c *MCSClient) connect(selectedProtocol uint32) {
glog.Debug("mcs client on connect", selectedProtocol)
c.clientCoreData.ServerSelectedProtocol = selectedProtocol
glog.Debugf("clientCoreData:%+v", c.clientCoreData)
glog.Debugf("clientNetworkData:%+v", c.clientNetworkData)
glog.Debugf("clientSecurityData:%+v", c.clientSecurityData)
// sendConnectclientCoreDataInitial
userDataBuff := bytes.Buffer{}
userDataBuff.Write(c.clientCoreData.Pack())
userDataBuff.Write(c.clientNetworkData.Pack())
userDataBuff.Write(c.clientSecurityData.Pack())
ccReq := gcc.MakeConferenceCreateRequest(userDataBuff.Bytes())
connectInitial := NewConnectInitial(ccReq)
connectInitialBerEncoded := connectInitial.BER()
dataBuff := &bytes.Buffer{}
ber.WriteApplicationTag(uint8(MCS_TYPE_CONNECT_INITIAL), len(connectInitialBerEncoded), dataBuff)
dataBuff.Write(connectInitialBerEncoded)
_, err := c.transport.Write(dataBuff.Bytes())
if err != nil {
c.Emit("error", errors.New(fmt.Sprintf("mcs sendConnectInitial write error %v", err)))
return
}
glog.Debug("mcs wait for data event")
c.transport.Once("data", c.recvConnectResponse)
}
func (c *MCSClient) recvConnectResponse(s []byte) {
glog.Trace("mcs recvConnectResponse", hex.EncodeToString(s))
cResp, err := ReadConnectResponse(bytes.NewReader(s))
if err != nil {
c.Emit("error", errors.New(fmt.Sprintf("ReadConnectResponse %v", err)))
return
}
// record server gcc block
serverSettings := gcc.ReadConferenceCreateResponse(cResp.userData)
for _, v := range serverSettings {
switch v.(type) {
case *gcc.ServerSecurityData:
c.serverSecurityData = v.(*gcc.ServerSecurityData)
case *gcc.ServerCoreData:
c.serverCoreData = v.(*gcc.ServerCoreData)
case *gcc.ServerNetworkData:
c.serverNetworkData = v.(*gcc.ServerNetworkData)
default:
err := errors.New(fmt.Sprintf("unhandle server gcc block %v", reflect.TypeOf(v)))
glog.Error(err)
c.Emit("error", err)
return
}
}
glog.Debugf("serverSecurityData: %+v", c.serverSecurityData)
glog.Debugf("serverCoreData: %+v", c.serverCoreData)
glog.Debugf("serverNetworkData: %+v", c.serverNetworkData)
glog.Debug("mcs sendErectDomainRequest")
c.sendErectDomainRequest()
glog.Debug("mcs sendAttachUserRequest")
c.sendAttachUserRequest()
c.transport.Once("data", c.recvAttachUserConfirm)
}
func (c *MCSClient) sendErectDomainRequest() {
buff := &bytes.Buffer{}
writeMCSPDUHeader(ERECT_DOMAIN_REQUEST, 0, buff)
per.WriteInteger(0, buff)
per.WriteInteger(0, buff)
c.transport.Write(buff.Bytes())
}
func (c *MCSClient) sendAttachUserRequest() {
buff := &bytes.Buffer{}
writeMCSPDUHeader(ATTACH_USER_REQUEST, 0, buff)
c.transport.Write(buff.Bytes())
}
func (c *MCSClient) recvAttachUserConfirm(s []byte) {
glog.Debug("mcs recvAttachUserConfirm", hex.EncodeToString(s))
r := bytes.NewReader(s)
option, err := core.ReadUInt8(r)
if err != nil {
c.Emit("error", err)
return
}
if !readMCSPDUHeader(option, ATTACH_USER_CONFIRM) {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_BAD_HEADER"))
return
}
e, err := per.ReadEnumerates(r)
if err != nil {
c.Emit("error", err)
return
}
if e != 0 {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_SERVER_REJECT_USER'"))
return
}
userId, _ := per.ReadInteger16(r)
userId += MCS_USERCHANNEL_BASE
c.userId = userId
c.channels = append(c.channels, MCSChannelInfo{userId, "user"})
c.connectChannels()
}
func (c *MCSClient) connectChannels() {
glog.Debug("mcs connectChannels:", c.channelsConnected, ":", len(c.channels))
if c.channelsConnected == len(c.channels) {
if c.nbChannelRequested < int(c.serverNetworkData.ChannelCount) {
//static virtual channel
chanId := c.serverNetworkData.ChannelIdArray[c.nbChannelRequested]
c.nbChannelRequested++
c.sendChannelJoinRequest(chanId)
c.transport.Once("data", c.recvChannelJoinConfirm)
return
}
c.transport.On("data", c.recvData)
// send client and sever gcc informations callback to sec
clientData := make([]interface{}, 0)
clientData = append(clientData, c.clientCoreData)
clientData = append(clientData, c.clientSecurityData)
clientData = append(clientData, c.clientNetworkData)
serverData := make([]interface{}, 0)
serverData = append(serverData, c.serverCoreData)
serverData = append(serverData, c.serverSecurityData)
glog.Debug("msc connectChannels callback to sec")
c.Emit("connect", clientData, serverData, c.userId, c.channels)
return
}
// sendChannelJoinRequest
glog.Debug("sendChannelJoinRequest:", c.channels[c.channelsConnected].Name)
c.sendChannelJoinRequest(c.channels[c.channelsConnected].ID)
c.transport.Once("data", c.recvChannelJoinConfirm)
}
func (c *MCSClient) sendChannelJoinRequest(channelId uint16) {
glog.Debug("mcs sendChannelJoinRequest", channelId)
buff := &bytes.Buffer{}
writeMCSPDUHeader(CHANNEL_JOIN_REQUEST, 0, buff)
per.WriteInteger16(c.userId-MCS_USERCHANNEL_BASE, buff)
per.WriteInteger16(channelId, buff)
c.transport.Write(buff.Bytes())
}
func (c *MCSClient) recvData(s []byte) {
glog.Trace("msc on data recvData:", hex.EncodeToString(s))
r := bytes.NewReader(s)
option, err := core.ReadUInt8(r)
if err != nil {
c.Emit("error", err)
return
}
if readMCSPDUHeader(option, DISCONNECT_PROVIDER_ULTIMATUM) {
c.Emit("error", errors.New("MCS DISCONNECT_PROVIDER_ULTIMATUM"))
c.transport.Close()
return
} else if !readMCSPDUHeader(option, c.recvOpCode) {
c.Emit("error", errors.New("Invalid expected MCS opcode receive data"))
return
}
userId, _ := per.ReadInteger16(r)
userId += MCS_USERCHANNEL_BASE
channelId, _ := per.ReadInteger16(r)
per.ReadEnumerates(r)
size, _ := per.ReadLength(r)
// channel ID doesn't match a requested layer
found := false
channelName := ""
for _, channel := range c.channels {
if channel.ID == channelId {
found = true
channelName = channel.Name
break
}
}
if !found {
glog.Error("mcs receive data for an unconnected layer")
return
}
left, err := core.ReadBytes(int(size), r)
if err != nil {
c.Emit("error", errors.New(fmt.Sprintf("mcs recvData get data error %v", err)))
return
}
glog.Debugf("mcs emit channel<%s>", channelName)
c.Emit("sec", channelName, left)
}
func (c *MCSClient) recvChannelJoinConfirm(s []byte) {
glog.Debug("mcs recvChannelJoinConfirm", hex.EncodeToString(s))
r := bytes.NewReader(s)
option, err := core.ReadUInt8(r)
if err != nil {
c.Emit("error", err)
return
}
if !readMCSPDUHeader(option, CHANNEL_JOIN_CONFIRM) {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_WAIT_CHANNEL_JOIN_CONFIRM"))
return
}
confirm, _ := per.ReadEnumerates(r)
userId, _ := per.ReadInteger16(r)
userId += MCS_USERCHANNEL_BASE
if c.userId != userId {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_INVALID_USER_ID"))
return
}
channelId, _ := per.ReadInteger16(r)
if (confirm != 0) && (channelId == uint16(MCS_GLOBAL_CHANNEL_ID) || channelId == c.userId) {
c.Emit("error", errors.New("NODE_RDP_PROTOCOL_T125_MCS_SERVER_MUST_CONFIRM_STATIC_CHANNEL"))
return
}
glog.Debug("Confirm channelId:", channelId)
if confirm == 0 {
for i := 0; i < int(c.serverNetworkData.ChannelCount); i++ {
if channelId == c.serverNetworkData.ChannelIdArray[i] {
var t MCSChannelInfo
t.ID = channelId
t.Name = string(c.clientNetworkData.ChannelDefArray[i].Name[:])
c.channels = append(c.channels, t)
}
}
}
c.channelsConnected++
c.connectChannels()
}
func (c *MCSClient) Pack(data []byte, channelId uint16) []byte {
buff := &bytes.Buffer{}
writeMCSPDUHeader(c.sendOpCode, 0, buff)
per.WriteInteger16(c.userId-MCS_USERCHANNEL_BASE, buff)
per.WriteInteger16(channelId, buff)
core.WriteUInt8(0x70, buff)
per.WriteLength(len(data), buff)
core.WriteBytes(data, buff)
glog.Trace("MCSClient write", channelId, ":", hex.EncodeToString(buff.Bytes()))
return buff.Bytes()
}
func (c *MCSClient) Write(data []byte) (n int, err error) {
data = c.Pack(data, c.channels[0].ID)
return c.transport.Write(data)
}
func (c *MCSClient) SendToChannel(channel string, data []byte) (n int, err error) {
channelId := c.channels[0].ID
for _, ch := range c.channels {
if channel == ch.Name {
channelId = ch.ID
break
}
}
data = c.Pack(data, channelId)
return c.transport.Write(data)
}
+203
View File
@@ -0,0 +1,203 @@
package per
import (
"bytes"
"io"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/core"
)
func ReadEnumerates(r io.Reader) (uint8, error) {
return core.ReadUInt8(r)
}
func WriteInteger(n int, w io.Writer) {
if n <= 0xff {
WriteLength(1, w)
core.WriteUInt8(uint8(n), w)
} else if n <= 0xffff {
WriteLength(2, w)
core.WriteUInt16BE(uint16(n), w)
} else {
WriteLength(4, w)
core.WriteUInt32BE(uint32(n), w)
}
}
func ReadInteger16(r io.Reader) (uint16, error) {
return core.ReadUint16BE(r)
}
func WriteInteger16(value uint16, w io.Writer) {
core.WriteUInt16BE(value, w)
}
/**
* @param choice {integer}
* @returns {type.UInt8} choice per encoded
*/
func WriteChoice(choice uint8, w io.Writer) {
core.WriteUInt8(choice, w)
}
/**
* @param value {raw} value to convert to per format
* @returns type objects per encoding value
*/
func WriteLength(value int, w io.Writer) {
if value > 0x7f {
core.WriteUInt16BE(uint16(value|0x8000), w)
} else {
core.WriteUInt8(uint8(value), w)
}
}
func ReadLength(r io.Reader) (uint16, error) {
b, err := core.ReadUInt8(r)
if err != nil {
return 0, nil
}
var size uint16
if b&0x80 > 0 {
b = b &^ 0x80
size = uint16(b) << 8
left, _ := core.ReadUInt8(r)
size += uint16(left)
} else {
size = uint16(b)
}
return size, nil
}
/**
* @param oid {array} oid to write
* @returns {type.Component} per encoded object identifier
*/
func WriteObjectIdentifier(oid []byte, w io.Writer) {
core.WriteUInt8(5, w)
core.WriteByte((oid[0]<<4)&(oid[1]&0x0f), w)
core.WriteByte(oid[2], w)
core.WriteByte(oid[3], w)
core.WriteByte(oid[4], w)
core.WriteByte(oid[5], w)
}
/**
* @param selection {integer}
* @returns {type.UInt8} per encoded selection
*/
func WriteSelection(selection uint8, w io.Writer) {
core.WriteUInt8(selection, w)
}
func WriteNumericString(s string, minValue int, w io.Writer) {
length := len(s)
mLength := minValue
if length >= minValue {
mLength = length - minValue
}
buff := &bytes.Buffer{}
for i := 0; i < length; i += 2 {
c1 := int(s[i])
c2 := 0x30
if i+1 < length {
c2 = int(s[i+1])
}
c1 = (c1 - 0x30) % 10
c2 = (c2 - 0x30) % 10
core.WriteUInt8(uint8((c1<<4)|c2), buff)
}
WriteLength(mLength, w)
w.Write(buff.Bytes())
}
func WritePadding(length int, w io.Writer) {
b := make([]byte, length)
w.Write(b)
}
func WriteNumberOfSet(n int, w io.Writer) {
core.WriteUInt8(uint8(n), w)
}
/**
* @param oStr {String}
* @param minValue {integer} default 0
* @returns {type.Component} per encoded octet stream
*/
func WriteOctetStream(oStr string, minValue int, w io.Writer) {
length := len(oStr)
mlength := minValue
if length-minValue >= 0 {
mlength = length - minValue
}
WriteLength(mlength, w)
w.Write([]byte(oStr)[:length])
}
func ReadChoice(r io.Reader) uint8 {
choice, _ := core.ReadUInt8(r)
return choice
}
func ReadNumberOfSet(r io.Reader) uint8 {
choice, _ := core.ReadUInt8(r)
return choice
}
func ReadInteger(r io.Reader) uint32 {
size, _ := ReadLength(r)
switch size {
case 1:
ret, _ := core.ReadUInt8(r)
return uint32(ret)
case 2:
ret, _ := core.ReadUint16BE(r)
return uint32(ret)
case 4:
ret, _ := core.ReadUInt32BE(r)
return ret
default:
glog.Info("ReadInteger")
}
return 0
}
func ReadObjectIdentifier(r io.Reader, oid []byte) bool {
size, _ := ReadLength(r)
if size != 5 {
return false
}
a_oid := []byte{0, 0, 0, 0, 0, 0}
t12, _ := core.ReadByte(r)
a_oid[0] = t12 >> 4
a_oid[1] = t12 & 0x0f
a_oid[2], _ = core.ReadByte(r)
a_oid[3], _ = core.ReadByte(r)
a_oid[4], _ = core.ReadByte(r)
a_oid[5], _ = core.ReadByte(r)
for i, _ := range oid {
if oid[i] != a_oid[i] {
return false
}
}
return true
}
func ReadOctetStream(r io.Reader, s string, min int) bool {
ln, _ := ReadLength(r)
size := int(ln) + min
if size != len(s) {
return false
}
for i := 0; i < size; i++ {
b, _ := core.ReadByte(r)
if b != s[i] {
return false
}
}
return true
}
+444
View File
@@ -0,0 +1,444 @@
package tpkt
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"reflect"
"strings"
"time"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/nla"
)
// take idea from https://github.com/Madnikulin50/gordp
/**
* Type of tpkt packet
* Fastpath is use to shortcut RDP stack
* @see http://msdn.microsoft.com/en-us/library/cc240621.aspx
* @see http://msdn.microsoft.com/en-us/library/cc240589.aspx
*/
const (
FASTPATH_ACTION_FASTPATH = 0x0
FASTPATH_ACTION_X224 = 0x3
)
/**
* TPKT layer of rdp stack
*/
type TPKT struct {
emission.Emitter
Conn *core.SocketLayer
ntlm *nla.NTLMv2
secFlag byte
lastShortLength int
fastPathListener core.FastPathListener
ntlmSec *nla.NTLMv2Security
}
var OsVersion = map[string]string{
"3.10.511": "Windows NT 3.1",
"3.50.807": "Windows NT 3.5",
"3.10.528": "Windows NT 3.1, Service Pack 3",
"3.51.1057": "Windows NT 3.51",
"4.00.950": "Windows 95",
"4.0.1381": "Windows NT 4.0",
"4.10.1998": "Windows 98",
"4.10.2222": "Windows 98 Second Edition (SE)",
"5.0.2195": "Windows 2000",
"4.90.3000": "Windows Me",
"5.1.2600": "Windows XP/Windows XP, Service Pack 3",
"5.1.2600.1105": "Windows XP, Service Pack 1",
"5.2.3790": "Windows Server 2003/Windows Server 2003 R2/Windows Server 2003, Service Pack 2",
"5.1.2600.2180": "Windows XP, Service Pack 2",
"5.2.3790.1180": "Windows Server 2003, Service Pack 1",
"6.0.6000": "Windows Vista",
"5.2.4500": "Windows Home Server",
"6.0.6001": "Windows Vista, Service Pack 1/Windows Server 2008",
"6.0.6002": "Windows Vista, Service Pack 2/Windows Server 2008, Service Pack 2",
"6.1.7600": "Windows 7/Windows Server 2008 R2",
"6.1.7601": "Windows 7, Service Pack 1/Windows Server 2008 R2, Service Pack 1",
"6.1.8400": "Windows Home Server 2011",
"6.2.9200": "Windows Server 2012/Windows 8",
"6.3.9600": "Windows 8.1/Windows Server 2012 R2",
"10.0.10240": "Windows 10, Version 1507",
"10.0.10586": "Windows 10, Version 1511",
"10.0.14393": "Windows 10, Version 1607/Windows Server 2016, Version 1607",
"10.0.15063": "Windows 10, Version 1703",
"10.0.16299": "Windows 10, Version 1709",
"10.0.17134": "Windows 10, Version 1803",
"10.0.17763": "Windows Server 2019, Version 1809/Windows 10, Version 1809",
"6.0.6003": "Windows Server 2008, Service Pack 2, Rollup KB4489887",
"10.0.18362": "Windows 10, Version 1903",
"10.0.18363": "Windows 10, Version 1909/Windows Server, Version 1909",
"10.0.19041": "Windows 10, Version 2004/Windows Server, Version 2004",
"10.0.19042": "Windows 10, Version 20H2/Windows Server, Version 20H2",
"10.0.19043": "Windows 10, Version 21H1",
"10.0.20348": "Windows Server 2022",
"10.0.22000": "Windows 11, Version 21H2",
"10.0.19044": "Windows 10, Version 21H2",
}
func New(s *core.SocketLayer, ntlm *nla.NTLMv2) *TPKT {
t := &TPKT{
Emitter: *emission.NewEmitter(),
Conn: s,
secFlag: 0,
ntlm: ntlm}
core.StartReadBytes(2, s, t.recvHeader)
return t
}
func (t *TPKT) StartTLS() error {
return t.Conn.StartTLS()
}
func (t *TPKT) StartNLA() error {
err := t.StartTLS()
if err != nil {
glog.Info("start tls failed", err)
return err
}
req := nla.EncodeDERTRequest([]nla.Message{t.ntlm.GetNegotiateMessage()}, nil, nil)
_, err = t.Conn.Write(req)
if err != nil {
glog.Info("send NegotiateMessage", err)
return err
}
resp := make([]byte, 1024)
n, err := t.Conn.Read(resp)
if err != nil {
return fmt.Errorf("read %s", err)
} else {
glog.Debug("StartNLA Read success")
}
return t.recvChallenge(resp[:n])
}
func (t *TPKT) recvChallenge(data []byte) error {
//own add
glog.Debug("start recv challenge......")
info := make(map[string]any)
type NTLMChallenge struct {
Signature [8]byte
MessageType uint32
TargetNameLen uint16
TargetNameMaxLen uint16
TargetNameBufferOffset uint32
NegotiateFlags uint32
ServerChallenge uint64
Reserved uint64
TargetInfoLen uint16
TargetInfoMaxLen uint16
TargetInfoBufferOffset uint32
Version [8]byte
// Payload (variable)
}
var challengeLen = 56
challengeStartOffset := bytes.Index(data, []byte{'N', 'T', 'L', 'M', 'S', 'S', 'P', 0})
if challengeStartOffset == -1 {
}
if len(data) < challengeStartOffset+challengeLen {
return nil
}
var responseData NTLMChallenge
response := data[challengeStartOffset:]
responseBuf := bytes.NewBuffer(response)
err := binary.Read(responseBuf, binary.LittleEndian, &responseData)
if err != nil {
return err
}
// Check if valid NTLM challenge response message structure
if responseData.MessageType != 0x00000002 ||
responseData.Reserved != 0 ||
!reflect.DeepEqual(responseData.Version[4:], []byte{0, 0, 0, 0xF}) {
return nil
}
// Parse: Version
type version struct {
MajorVersion byte
MinorVersion byte
BuildNumber uint16
}
var versionData version
versionBuf := bytes.NewBuffer(responseData.Version[:4])
err = binary.Read(versionBuf, binary.LittleEndian, &versionData)
if err != nil {
return err
}
ProductVersion := fmt.Sprintf("%d.%d.%d", versionData.MajorVersion,
versionData.MinorVersion,
versionData.BuildNumber)
glog.Debug("get product version: Windows", ProductVersion)
info["ProductVersion"] = ProductVersion
v, ok := OsVersion[ProductVersion]
if ok {
info["OsVerion"] = v
glog.Debug("get os version:", v)
} else {
if versionData.BuildNumber >= 22000 {
info["OsVerion"] = fmt.Sprintf("Windows 11, version:%s", ProductVersion)
} else {
info["OsVerion"] = fmt.Sprintf("Windows %s", ProductVersion)
}
}
// Parse: TargetName
targetNameLen := int(responseData.TargetNameLen)
if targetNameLen > 0 {
startIdx := int(responseData.TargetNameBufferOffset)
endIdx := startIdx + targetNameLen
targetName := strings.ReplaceAll(string(response[startIdx:endIdx]), "\x00", "")
info["TargetName"] = targetName
glog.Debug("target Name = ", targetName)
}
// Parse: TargetInfo
AvIDMap := map[uint16]string{
1: "NetBIOSComputerName",
2: "NetBIOSDomainName",
3: "FQDN", // DNS Computer Name
4: "DNSDomainName",
5: "DNSTreeName",
7: "Timestamp",
9: "MsvAvTargetName",
}
type AVPair struct {
AvID uint16
AvLen uint16
// Value (variable)
}
var avPairLen = 4
targetInfoLen := int(responseData.TargetInfoLen)
if targetInfoLen > 0 {
startIdx := int(responseData.TargetInfoBufferOffset)
if startIdx+targetInfoLen > len(response) {
return fmt.Errorf("Invalid TargetInfoLen value")
}
var avPair AVPair
avPairBuf := bytes.NewBuffer(response[startIdx : startIdx+avPairLen])
err = binary.Read(avPairBuf, binary.LittleEndian, &avPair)
if err != nil {
return err
}
currIdx := startIdx
for avPair.AvID != 0 {
if field, exists := AvIDMap[avPair.AvID]; exists {
var value string
r := response[currIdx+avPairLen : currIdx+avPairLen+int(avPair.AvLen)]
if avPair.AvID == 7 {
unixStamp := binary.LittleEndian.Uint64(r)/10000000 - 11644473600
tm := time.Unix(int64(unixStamp), 0)
value = tm.Format("2006-01-02 15:04:05")
} else {
value = strings.ReplaceAll(string(r), "\x00", "")
}
info[field] = value
}
currIdx += avPairLen + int(avPair.AvLen)
if currIdx+avPairLen > startIdx+targetInfoLen {
return fmt.Errorf("Invalid AV_PAIR list")
}
avPairBuf = bytes.NewBuffer(response[currIdx : currIdx+avPairLen])
err = binary.Read(avPairBuf, binary.LittleEndian, &avPair)
if err != nil {
return err
}
}
}
glog.Info("get os info by NLA done !")
glog.Info("=======================================")
for key, value := range info {
glog.Info(key, ":", value)
}
glog.Info("=======================================")
//判断是否存在windows域
if netBiosDomainName, exists := info["NetBIOSDomainName"]; exists {
if netBiosComputerName, exists := info["NetBIOSComputerName"]; exists {
if netBiosDomainName == netBiosComputerName {
info["DNSDomainName"], info["NetBIOSDomainName"] = "WORKGROUP", "WORKGROUP"
//delete(info, "FQDN")
} else {
}
}
}
t.Emit("os_info", info)
// end
glog.Trace("recvChallenge", hex.EncodeToString(data))
tsreq, err := nla.DecodeDERTRequest(data)
if err != nil {
glog.Info("DecodeDERTRequest", err)
return err
}
glog.Debugf("tsreq:%+v", tsreq)
// get pubkey
pubkey, err := t.Conn.TlsPubKey()
glog.Debugf("pubkey=%+v", pubkey)
authMsg, ntlmSec := t.ntlm.GetAuthenticateMessage(tsreq.NegoTokens[0].Data)
t.ntlmSec = ntlmSec
encryptPubkey := ntlmSec.GssEncrypt(pubkey)
req := nla.EncodeDERTRequest([]nla.Message{authMsg}, nil, encryptPubkey)
_, err = t.Conn.Write(req)
if err != nil {
glog.Info("send AuthenticateMessage", err)
return err
}
resp := make([]byte, 1024)
n, err := t.Conn.Read(resp)
if err != nil {
glog.Error("Read:", err)
return fmt.Errorf("read %s", err)
} else {
glog.Debug("recvChallenge Read success")
}
return t.recvPubKeyInc(resp[:n])
}
func (t *TPKT) recvPubKeyInc(data []byte) error {
glog.Trace("recvPubKeyInc", hex.EncodeToString(data))
tsreq, err := nla.DecodeDERTRequest(data)
if err != nil {
glog.Info("DecodeDERTRequest", err)
return err
}
glog.Trace("PubKeyAuth:", tsreq.PubKeyAuth)
//ignore
//pubkey := t.ntlmSec.GssDecrypt([]byte(tsreq.PubKeyAuth))
domain, username, password := t.ntlm.GetEncodedCredentials()
credentials := nla.EncodeDERTCredentials(domain, username, password)
authInfo := t.ntlmSec.GssEncrypt(credentials)
req := nla.EncodeDERTRequest(nil, authInfo, nil)
_, err = t.Conn.Write(req)
if err != nil {
glog.Info("send AuthenticateMessage", err)
return err
}
return nil
}
func (t *TPKT) Read(b []byte) (n int, err error) {
return t.Conn.Read(b)
}
func (t *TPKT) Write(data []byte) (n int, err error) {
buff := &bytes.Buffer{}
core.WriteUInt8(FASTPATH_ACTION_X224, buff)
core.WriteUInt8(0, buff)
core.WriteUInt16BE(uint16(len(data)+4), buff)
buff.Write(data)
glog.Trace("tpkt Write", hex.EncodeToString(buff.Bytes()))
return t.Conn.Write(buff.Bytes())
}
func (t *TPKT) Close() error {
return t.Conn.Close()
}
func (t *TPKT) SetFastPathListener(f core.FastPathListener) {
t.fastPathListener = f
}
func (t *TPKT) SendFastPath(secFlag byte, data []byte) (n int, err error) {
buff := &bytes.Buffer{}
core.WriteUInt8(FASTPATH_ACTION_FASTPATH|((secFlag&0x3)<<6), buff)
core.WriteUInt16BE(uint16(len(data)+3)|0x8000, buff)
buff.Write(data)
glog.Trace("TPTK SendFastPath", hex.EncodeToString(buff.Bytes()))
return t.Conn.Write(buff.Bytes())
}
func (t *TPKT) recvHeader(s []byte, err error) {
glog.Trace("tpkt recvHeader", hex.EncodeToString(s), err)
if err != nil {
t.Emit("error", err)
return
}
r := bytes.NewReader(s)
version, _ := core.ReadUInt8(r)
if version == FASTPATH_ACTION_X224 {
glog.Debug("tptk recvHeader FASTPATH_ACTION_X224, wait for recvExtendedHeader")
core.StartReadBytes(2, t.Conn, t.recvExtendedHeader)
} else {
glog.Debug("[-] !!!! version is not FASTPATH_ACTION_X224, version=", version)
t.secFlag = (version >> 6) & 0x3
length, _ := core.ReadUInt8(r)
t.lastShortLength = int(length)
glog.Debug("last read len:", length)
if t.lastShortLength&0x80 != 0 {
core.StartReadBytes(1, t.Conn, t.recvExtendedFastPathHeader)
} else {
//core.StartReadBytes(1, t.Conn, t.recvExtendedFastPathHeader)
if t.lastShortLength >= 2 {
core.StartReadBytes(t.lastShortLength-2, t.Conn, t.recvFastPath)
} else {
glog.Debug("lastShortLength = 0")
}
}
}
}
func (t *TPKT) recvExtendedHeader(s []byte, err error) {
glog.Trace("tpkt recvExtendedHeader", hex.EncodeToString(s), err)
if err != nil {
return
}
r := bytes.NewReader(s)
size, _ := core.ReadUint16BE(r)
glog.Debug("tpkt wait recvData:", size)
core.StartReadBytes(int(size-4), t.Conn, t.recvData)
}
func (t *TPKT) recvData(s []byte, err error) {
glog.Trace("tpkt recvData", hex.EncodeToString(s), err)
if err != nil {
return
}
t.Emit("data", s)
core.StartReadBytes(2, t.Conn, t.recvHeader)
}
func (t *TPKT) recvExtendedFastPathHeader(s []byte, err error) {
glog.Trace("tpkt recvExtendedFastPathHeader", hex.EncodeToString(s))
r := bytes.NewReader(s)
rightPart, err := core.ReadUInt8(r)
if err != nil {
glog.Error("TPTK recvExtendedFastPathHeader", err)
return
}
leftPart := t.lastShortLength & ^0x80
packetSize := (leftPart << 8) + int(rightPart)
if packetSize == 0 {
fmt.Println("get packetSize,rightPart=", packetSize, rightPart)
t.Emit("close")
} else {
core.StartReadBytes(packetSize-3, t.Conn, t.recvFastPath)
}
}
func (t *TPKT) recvFastPath(s []byte, err error) {
glog.Trace("tpkt recvFastPath")
if err != nil {
return
}
t.fastPathListener.RecvFastPath(t.secFlag, s)
core.StartReadBytes(2, t.Conn, t.recvHeader)
}
+424
View File
@@ -0,0 +1,424 @@
package x224
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"github.com/shadow1ng/fscan/mylib/grdp/glog"
"github.com/lunixbochs/struc"
"github.com/shadow1ng/fscan/mylib/grdp/core"
"github.com/shadow1ng/fscan/mylib/grdp/emission"
"github.com/shadow1ng/fscan/mylib/grdp/protocol/tpkt"
)
// take idea from https://github.com/Madnikulin50/gordp
/**
* Message type present in X224 packet header
*/
type MessageType byte
const (
TPDU_CONNECTION_REQUEST MessageType = 0xE0
TPDU_CONNECTION_CONFIRM = 0xD0
TPDU_DISCONNECT_REQUEST = 0x80
TPDU_DATA = 0xF0
TPDU_ERROR = 0x70
)
/**
* Type of negotiation present in negotiation packet
*/
type NegotiationType byte
const (
TYPE_RDP_NEG_REQ NegotiationType = 0x01
TYPE_RDP_NEG_RSP = 0x02
TYPE_RDP_NEG_FAILURE = 0x03
)
/**
* Protocols available for x224 layer
*/
const (
PROTOCOL_RDP uint32 = 0x00000000
PROTOCOL_SSL = 0x00000001
PROTOCOL_HYBRID = 0x00000002
PROTOCOL_HYBRID_EX = 0x00000008
)
/**
* Use to negotiate security layer of RDP stack
* In node-rdpjs only ssl is available
* @param opt {object} component type options
* @see request -> http://msdn.microsoft.com/en-us/library/cc240500.aspx
* @see response -> http://msdn.microsoft.com/en-us/library/cc240506.aspx
* @see failure ->http://msdn.microsoft.com/en-us/library/cc240507.aspx
*/
type Negotiation struct {
Type NegotiationType `struc:"byte"`
Flag uint8 `struc:"uint8"`
Length uint16 `struc:"little"`
Result uint32 `struc:"little"`
}
func NewNegotiation() *Negotiation {
return &Negotiation{0, 0, 0x0008 /*constant*/, PROTOCOL_RDP}
}
const (
//The server requires that the client support Enhanced RDP Security (section 5.4) with either TLS 1.0, 1.1 or 1.2 (section 5.4.5.1) or CredSSP (section 5.4.5.2). If only CredSSP was requested then the server only supports TLS.
SSL_REQUIRED_BY_SERVER = 0x00000001
//The server is configured to only use Standard RDP Security mechanisms (section 5.3) and does not support any External Security Protocols (section 5.4.5).
SSL_NOT_ALLOWED_BY_SERVER = 0x00000002
//The server does not possess a valid authentication certificate and cannot initialize the External Security Protocol Provider (section 5.4.5).
SSL_CERT_NOT_ON_SERVER = 0x00000003
//The list of requested security protocols is not consistent with the current security protocol in effect. This error is only possible when the Direct Approach (sections 5.4.2.2 and 1.3.1.2) is used and an External Security Protocol (section 5.4.5) is already being used.
INCONSISTENT_FLAGS = 0x00000004
//The server requires that the client support Enhanced RDP Security (section 5.4) with CredSSP (section 5.4.5.2).
HYBRID_REQUIRED_BY_SERVER = 0x00000005
//The server requires that the client support Enhanced RDP Security (section 5.4) with TLS 1.0, 1.1 or 1.2 (section 5.4.5.1) and certificate-based client authentication.<4>
SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER = 0x00000006
)
/**
* X224 client connection request
* @param opt {object} component type options
* @see http://msdn.microsoft.com/en-us/library/cc240470.aspx
*/
type ClientConnectionRequestPDU struct {
Len uint8
Code MessageType
Padding1 uint16
Padding2 uint16
Padding3 uint8
Cookie []byte
requestedProtocol uint32
ProtocolNeg *Negotiation
}
func NewClientConnectionRequestPDU(cookie []byte, requestedProtocol uint32) *ClientConnectionRequestPDU {
x := ClientConnectionRequestPDU{0, TPDU_CONNECTION_REQUEST, 0, 0, 0,
cookie, requestedProtocol, NewNegotiation()}
x.Len = 6
if len(cookie) > 0 {
x.Len += uint8(len(cookie) + 2)
}
if x.requestedProtocol > PROTOCOL_RDP {
x.Len += 8
}
return &x
}
func (x *ClientConnectionRequestPDU) Serialize() []byte {
buff := &bytes.Buffer{}
core.WriteUInt8(x.Len, buff)
core.WriteUInt8(uint8(x.Code), buff)
core.WriteUInt16BE(x.Padding1, buff)
core.WriteUInt16BE(x.Padding2, buff)
core.WriteUInt8(x.Padding3, buff)
if len(x.Cookie) > 0 {
buff.Write(x.Cookie)
core.WriteUInt8(0x0D, buff)
core.WriteUInt8(0x0A, buff)
}
if x.requestedProtocol > PROTOCOL_RDP {
struc.Pack(buff, x.ProtocolNeg)
}
return buff.Bytes()
}
/**
* X224 Server connection confirm
* @param opt {object} component type options
* @see http://msdn.microsoft.com/en-us/library/cc240506.aspx
*/
type ServerConnectionConfirm struct {
Len uint8
Code MessageType
Padding1 uint16
Padding2 uint16
Padding3 uint8
ProtocolNeg *Negotiation
}
/**
* Header of each data message from x224 layer
* @returns {type.Component}
*/
type DataHeader struct {
Header uint8 `struc:"little"`
MessageType MessageType `struc:"uint8"`
Separator uint8 `struc:"little"`
}
func NewDataHeader() *DataHeader {
return &DataHeader{2, TPDU_DATA /* constant */, 0x80 /*constant*/}
}
/**
* Common X224 Automata
* @param presentation {Layer} presentation layer
*/
type X224 struct {
emission.Emitter
transport core.Transport
requestedProtocol uint32
selectedProtocol uint32
dataHeader *DataHeader
}
func New(t core.Transport) *X224 {
x := &X224{
*emission.NewEmitter(),
t,
PROTOCOL_RDP | PROTOCOL_SSL | PROTOCOL_HYBRID,
PROTOCOL_SSL,
NewDataHeader(),
}
t.On("close", func() {
x.Emit("close")
}).On("error", func(err error) {
x.Emit("error", err)
})
return x
}
func (x *X224) ServerChooseProtocol() uint32 {
return x.selectedProtocol
}
func (x *X224) Read(b []byte) (n int, err error) {
return x.transport.Read(b)
}
func (x *X224) Write(b []byte) (n int, err error) {
buff := &bytes.Buffer{}
err = struc.Pack(buff, x.dataHeader)
if err != nil {
return 0, err
}
buff.Write(b)
glog.Trace("x224 write:", hex.EncodeToString(buff.Bytes()))
return x.transport.Write(buff.Bytes())
}
func (x *X224) Close() error {
return x.transport.Close()
}
func (x *X224) SetRequestedProtocol(p uint32) {
x.requestedProtocol = p
}
func (x *X224) Connect() error {
if x.transport == nil {
return errors.New("no transport")
}
cookie := "Cookie: mstshash=bob"
message := NewClientConnectionRequestPDU([]byte(cookie), x.requestedProtocol)
message.ProtocolNeg.Type = TYPE_RDP_NEG_REQ
message.ProtocolNeg.Result = uint32(x.requestedProtocol)
glog.Debug("x224 sendConnectionRequest", hex.EncodeToString(message.Serialize()))
_, err := x.transport.Write(message.Serialize())
x.transport.Once("data", x.recvConnectionConfirm)
return err
}
func (x *X224) recvConnectionConfirm(s []byte) {
/*
在Windows的远程桌面协议(RDP)交互过程中,NLA是指网络级别身份验证(Network Level Authentication)。NLA是一种用于增强远程桌面连接安全性的机制。在启用了NLA的情况下,客户端必须在建立RDP会话之前通过网络级别的身份验证,这样可以防止未经授权的用户连接到远程桌面服务器。
NLA的优点
提高安全性:在建立RDP会话之前进行身份验证,确保只有经过验证的用户才能连接。
减少资源消耗:因为身份验证是在连接建立之前完成的,可以减少未授权用户消耗的系统资源。
RDP协议中的不同连接类型
RDP协议有几种不同的连接类型,它们在使用NLA方面有所不同:
PROTOCOL_RDP:标准的RDP连接方式。这是最早期的RDP连接类型,不使用任何额外的安全层。
PROTOCOL_SSL:使用SSL/TLS加密的RDP连接方式。这种方式可以增强连接的安全性。
PROTOCOL_HYBRID:混合连接方式,通常指的是使用NLA和TLS结合的连接方式。它先进行网络级别的身份验证(NLA),然后使用TLS加密传输数据。
PROTOCOL_HYBRID_EX:这是PROTOCOL_HYBRID的扩展版本,可能包含额外的安全特性或增强功能,具体细节通常会在相关文档中描述。
NLA与不同连接类型的关系
PROTOCOL_RDP:不使用NLA,因为这是最基本的连接方式。
PROTOCOL_SSL:可以与NLA结合使用。首先通过NLA进行身份验证,然后使用SSL/TLS加密数据传输。
PROTOCOL_HYBRID:使用NLA进行身份验证,然后通过TLS加密数据传输。因此,NLA在这种连接类型中是必需的。
PROTOCOL_HYBRID_EX:作为PROTOCOL_HYBRID的扩展版本,也可以使用NLA进行身份验证,并结合其他安全增强特性。
总的来说,除了最基本的PROTOCOL_RDP之外,其他连接类型(PROTOCOL_SSL、PROTOCOL_HYBRID、PROTOCOL_HYBRID_EX)都可以使用或要求使用NLA来提高连接的安全性。
*/
/*
总体而言,较早的Windows版本(如Windows 2000、Windows XP、Windows Server 2003等)默认使用基本的RDP协议(PROTOCOL_RDP),而现代的Windows版本(如Windows 7及之后的版本)默认启用网络级别身份验证(NLA)并支持SSL/TLS加密,以提高连接的安全性。具体的默认协议如下:
Windows 2000、Windows XP、Windows Server 2003 PROTOCOL_RDP
Windows Vista、Windows Server 2008 PROTOCOL_RDPNLA可配置)
Windows 7、Windows Server 2008 R2 PROTOCOL_HYBRID(默认启用NLA
Windows 8、Windows Server 2012 PROTOCOL_HYBRID(默认启用NLA
Windows 8.1、Windows Server 2012 R2 PROTOCOL_HYBRID(默认启用NLA
Windows 10、Windows Server 2016 PROTOCOL_HYBRID(默认启用NLA
Windows 101809及以上版本)、Windows Server 2019PROTOCOL_HYBRID(默认启用NLA
Windows 11、Windows Server 2022 PROTOCOL_HYBRID(默认启用NLA
*/
glog.Debug("x224 recvConnectionConfirm ", hex.EncodeToString(s))
r := bytes.NewReader(s)
ln, _ := core.ReadUInt8(r)
if ln > 6 {
message := &ServerConnectionConfirm{}
if err := struc.Unpack(bytes.NewReader(s), message); err != nil {
glog.Error("ReadServerConnectionConfirm err", err)
return
}
glog.Debugf("message: %+v", *message.ProtocolNeg)
if message.ProtocolNeg.Type == TYPE_RDP_NEG_FAILURE {
glog.Error(fmt.Sprintf("NODE_RDP_PROTOCOL_X224_NEG_FAILURE with code: %d,see https://msdn.microsoft.com/en-us/library/cc240507.aspx",
message.ProtocolNeg.Result))
//only use Standard RDP Security mechanisms
if message.ProtocolNeg.Result == 2 {
glog.Info("Only use Standard RDP Security mechanisms, Reconnect with Standard RDP")
}
switch message.ProtocolNeg.Result {
case SSL_REQUIRED_BY_SERVER:
// mean need use PROTOCOL_SSL
glog.Info("The server requires that the client support Enhanced RDP Security")
x.Emit("reconnect", PROTOCOL_SSL)
case SSL_NOT_ALLOWED_BY_SERVER:
// mean need to use PROTOCOL_RDP only
glog.Info("The server is configured to only use Standard RDP Security mechanisms")
x.Emit("reconnect", PROTOCOL_RDP)
case SSL_CERT_NOT_ON_SERVER:
glog.Info("The server does not possess a valid authentication certificate and cannot initialize the External Security Protocol Provider")
case INCONSISTENT_FLAGS:
glog.Info("The list of requested security protocols is not consistent with the current security protocol in effect. This error is only possible when the Direct Approach")
case HYBRID_REQUIRED_BY_SERVER:
glog.Info("The server requires that the client support Enhanced RDP Security (section 5.4) with CredSSP (section 5.4.5.2).")
x.Emit("reconnect", PROTOCOL_HYBRID)
case SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER:
glog.Info("The server requires that the client support Enhanced RDP Security (section 5.4) with TLS 1.0, 1.1 or 1.2 (section 5.4.5.1) and certificate-based client authentication.<4>")
x.Emit("reconnect", PROTOCOL_SSL)
////The server requires that the client support Enhanced RDP Security (section 5.4) with either TLS 1.0, 1.1 or 1.2 (section 5.4.5.1) or CredSSP (section 5.4.5.2). If only CredSSP was requested then the server only supports TLS.
// SSL_REQUIRED_BY_SERVER = 0x00000001
//
// //The server is configured to only use Standard RDP Security mechanisms (section 5.3) and does not support any External Security Protocols (section 5.4.5).
// SSL_NOT_ALLOWED_BY_SERVER = 0x00000002
//
// //The server does not possess a valid authentication certificate and cannot initialize the External Security Protocol Provider (section 5.4.5).
// SSL_CERT_NOT_ON_SERVER = 0x00000003
//
// //The list of requested security protocols is not consistent with the current security protocol in effect. This error is only possible when the Direct Approach (sections 5.4.2.2 and 1.3.1.2) is used and an External Security Protocol (section 5.4.5) is already being used.
// INCONSISTENT_FLAGS = 0x00000004
//
// //The server requires that the client support Enhanced RDP Security (section 5.4) with CredSSP (section 5.4.5.2).
// HYBRID_REQUIRED_BY_SERVER = 0x00000005
//
// //The server requires that the client support Enhanced RDP Security (section 5.4) with TLS 1.0, 1.1 or 1.2 (section 5.4.5.1) and certificate-based client authentication.<4>
// SSL_WITH_USER_AUTH_REQUIRED_BY_SERVER = 0x00000006
}
x.Close()
return
}
if message.ProtocolNeg.Type == TYPE_RDP_NEG_RSP {
glog.Info("TYPE_RDP_NEG_RSP", message.ProtocolNeg.Result)
x.selectedProtocol = message.ProtocolNeg.Result
}
} else {
x.selectedProtocol = PROTOCOL_RDP
}
serverChooseProtocol := "other not support protocol"
switch x.selectedProtocol {
case PROTOCOL_RDP:
serverChooseProtocol = "PROTOCOL_RDP"
x.Emit("more_timeout")
case PROTOCOL_SSL:
serverChooseProtocol = "PROTOCOL_SSL"
case PROTOCOL_HYBRID:
serverChooseProtocol = "PROTOCOL_HYBRID"
case PROTOCOL_HYBRID_EX:
serverChooseProtocol = "PROTOCOL_HYBRID_EX"
}
glog.Info("Server choose protocol:", serverChooseProtocol)
//if x.selectedProtocol == PROTOCOL_HYBRID_EX {
// glog.Error("NODE_RDP_PROTOCOL_HYBRID_EX_NOT_SUPPORTED")
// return
//}
if x.selectedProtocol == PROTOCOL_HYBRID_EX {
glog.Info("*** NLA Security selected ***")
err := x.transport.(*tpkt.TPKT).StartNLA()
glog.Debug("nla end, err?:", err)
if err != nil {
x.transport.Emit("close")
glog.Error("start NLA failed:", err)
return
}
x.Emit("connect", uint32(x.selectedProtocol))
return
}
x.transport.On("data", x.recvData)
if x.selectedProtocol == PROTOCOL_RDP {
glog.Info("*** RDP security selected ***")
x.Emit("connect", x.selectedProtocol)
return
}
if x.selectedProtocol == PROTOCOL_SSL {
glog.Info("*** SSL security selected ***")
err := x.transport.(*tpkt.TPKT).StartTLS()
if err != nil {
glog.Error("start tls failed:", err)
return
}
x.Emit("connect", x.selectedProtocol)
return
}
if x.selectedProtocol == PROTOCOL_HYBRID {
glog.Info("*** NLA Security selected ***")
err := x.transport.(*tpkt.TPKT).StartNLA()
glog.Debug("nla end, err?:", err)
if err != nil {
glog.Error("start NLA failed:", err)
return
}
x.Emit("connect", x.selectedProtocol)
return
}
}
func (x *X224) recvData(s []byte) {
glog.Trace("x224 recvData", hex.EncodeToString(s), "emit data")
// x224 header takes 3 bytes
x.Emit("data", s[3:])
}