Unverified Commit 6ce46ff2 authored by Eric_Lee's avatar Eric_Lee Committed by GitHub

Merge pull request #191 from jumpserver/dev

Dev
parents a108f384 7a81c174
......@@ -25,6 +25,7 @@ RUN chmod 755 ./entrypoint.sh \
&& apk update \
&& apk add -U tzdata \
&& apk add curl \
&& apk add mysql-client \
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& apk del tzdata \
......
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
......@@ -49,143 +49,200 @@ msgstr ""
#. i18n.T
#: pkg/handler/banner.go:52
msgid "refresh your assets and nodes"
msgid "display the databases that you have permission"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:53
msgid "print help"
msgid "refresh your assets and nodes"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:54
msgid "print help"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:55
msgid "exit"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:89
#: pkg/handler/banner.go:90
msgid "ID"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:90
#: pkg/handler/banner.go:91
msgid "hostname"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:91
#: pkg/handler/banner.go:92
msgid "IP"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:92
#: pkg/handler/banner.go:93
msgid "comment"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:93
#: pkg/handler/banner.go:94
msgid "Page: %d, Count: %d, Total Page: %d, Total Count: %d"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:94
#: pkg/handler/banner.go:95
msgid "No Assets"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:95
#: pkg/handler/banner.go:96
msgid ""
"Enter ID number directly login the asset, multiple search use // + field, "
"such as: //16"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:96
#: pkg/handler/banner.go:97
msgid "Page up: b\tPage down: n"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:97
#: pkg/handler/banner.go:98
msgid "Node: [ ID.Name(Asset amount) ]"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:98
#: pkg/handler/banner.go:99
msgid "Tips: Enter g+NodeID to display the host under the node, such as g1"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:99
#: pkg/handler/banner.go:100
msgid "Refresh done"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:100
#: pkg/handler/banner.go:101
msgid "Tips: Enter system user ID and directly login the asset [ %s(%s) ]"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:101
#: pkg/handler/banner.go:102
msgid "Back: B/b"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:102
#: pkg/handler/banner.go:103
msgid "Name"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:103
#: pkg/handler/banner.go:104
msgid "Username"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:104
#: pkg/handler/banner.go:105
msgid "all"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:105
#: pkg/handler/banner.go:106
msgid "Search: %s"
msgstr ""
#. i18n.T
#: pkg/proxy/parser.go:130
#: pkg/handler/banner.go:107
msgid "DBType"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:108
msgid "DB Name"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:109
msgid "No Databases"
msgstr ""
#. i18n.T
#: pkg/handler/banner.go:110
msgid ""
"Enter ID number directly login the database, multiple search use // + field, "
"such as: //16"
msgstr ""
#. i18n.T
#: pkg/proxy/dbproxy.go:112
msgid "Database connecting to %s %.1f"
msgstr ""
#. i18n.T
#: pkg/proxy/dbproxy.go:131
msgid "System user <%s> and database <%s> protocol are inconsistent."
msgstr ""
#. i18n.T
#: pkg/proxy/dbproxy.go:137
msgid "Database %s protocol client not installed."
msgstr ""
#. i18n.T
#: pkg/proxy/dbswitch.go:148
msgid "Database connect idle more than %d minutes, disconnect"
msgstr ""
#. i18n.T
#: pkg/proxy/dbswitch.go:155
msgid "Database connection terminated by administrator"
msgstr ""
#. i18n.T
#: pkg/proxy/parser.go:140
msgid "Command `%s` is forbidden"
msgstr ""
#. i18n.T
#: pkg/proxy/proxy.go:143
#: pkg/proxy/proxy.go:146
msgid "Reuse SSH connections (%s@%s) [Number of connections: %d]"
msgstr ""
#. i18n.T
#: pkg/proxy/proxy.go:161
#: pkg/proxy/proxy.go:164
msgid "Connecting to %s@%s %.1f"
msgstr ""
#. i18n.T
#: pkg/proxy/proxy.go:180
#: pkg/proxy/proxy.go:183
msgid "System user <%s> and asset <%s> protocol are inconsistent."
msgstr ""
#. i18n.T
#: pkg/proxy/proxy.go:186
#: pkg/proxy/proxy.go:189
msgid ""
"Terminal only support protocol ssh/telnet, please use web terminal to access"
msgstr ""
#. i18n.T
#: pkg/proxy/sessmanager.go:67
#: pkg/proxy/sessmanager.go:75
msgid "Connect with api server failed"
msgstr ""
#. i18n.T
#: pkg/proxy/switch.go:168
#: pkg/proxy/sessmanager.go:117
msgid "Create database session failed"
msgstr ""
#. i18n.T
#: pkg/proxy/switch.go:173
msgid "Connect idle more than %d minutes, disconnect"
msgstr ""
#. i18n.T
#: pkg/proxy/switch.go:175
#: pkg/proxy/switch.go:180
msgid "Terminated by administrator"
msgstr ""
No preview for this file type
......@@ -51,51 +51,57 @@ msgstr "显示您有权限的节点"
#. i18n.T
#: pkg/handler/banner.go:52
#, fuzzy
msgid "display the databases that you have permission"
msgstr "显示您有权限的数据库"
#. i18n.T
#: pkg/handler/banner.go:53
msgid "refresh your assets and nodes"
msgstr "刷新最新的机器和节点信息"
#. i18n.T
#: pkg/handler/banner.go:53
#: pkg/handler/banner.go:54
msgid "print help"
msgstr "显示帮助"
#. i18n.T
#: pkg/handler/banner.go:54
#: pkg/handler/banner.go:55
msgid "exit"
msgstr "退出"
#. i18n.T
#: pkg/handler/banner.go:89
#: pkg/handler/banner.go:90
msgid "ID"
msgstr "ID"
#. i18n.T
#: pkg/handler/banner.go:90
#: pkg/handler/banner.go:91
msgid "hostname"
msgstr "主机名"
#. i18n.T
#: pkg/handler/banner.go:91
#: pkg/handler/banner.go:92
msgid "IP"
msgstr "IP"
#. i18n.T
#: pkg/handler/banner.go:92
#: pkg/handler/banner.go:93
msgid "comment"
msgstr "备注"
#. i18n.T
#: pkg/handler/banner.go:93
#: pkg/handler/banner.go:94
msgid "Page: %d, Count: %d, Total Page: %d, Total Count: %d"
msgstr "页码:%d,每页行数:%d,总页数:%d,总数量:%d"
#. i18n.T
#: pkg/handler/banner.go:94
#: pkg/handler/banner.go:95
msgid "No Assets"
msgstr "没有资产"
#. i18n.T
#: pkg/handler/banner.go:95
#: pkg/handler/banner.go:96
#, fuzzy
msgid ""
"Enter ID number directly login the asset, multiple search use // + field, "
......@@ -103,28 +109,28 @@ msgid ""
msgstr "提示:输入资产ID直接登录,二级搜索使用 // + 字段,如://192"
#. i18n.T
#: pkg/handler/banner.go:96
#: pkg/handler/banner.go:97
#, fuzzy
msgid "Page up: b\tPage down: n"
msgstr "上一页:b 下一页:n"
#. i18n.T
#: pkg/handler/banner.go:97
#: pkg/handler/banner.go:98
msgid "Node: [ ID.Name(Asset amount) ]"
msgstr "节点:[ ID.名称(资产数量) ]"
#. i18n.T
#: pkg/handler/banner.go:98
#: pkg/handler/banner.go:99
msgid "Tips: Enter g+NodeID to display the host under the node, such as g1"
msgstr "提示:输入 g+节点ID 显示节点下主机,如: g1"
#. i18n.T
#: pkg/handler/banner.go:99
#: pkg/handler/banner.go:100
msgid "Refresh done"
msgstr "刷新完成"
#. i18n.T
#: pkg/handler/banner.go:100
#: pkg/handler/banner.go:101
#, fuzzy
msgid "Tips: Enter system user ID and directly login the asset [ %s(%s) ]"
msgstr ""
......@@ -132,69 +138,127 @@ msgstr ""
"提示:输入系统用户ID,登录资产[ %s(%s) ]\n"
#. i18n.T
#: pkg/handler/banner.go:101
#: pkg/handler/banner.go:102
msgid "Back: B/b"
msgstr "返回:B/b"
#. i18n.T
#: pkg/handler/banner.go:102
#: pkg/handler/banner.go:103
msgid "Name"
msgstr "名称"
#. i18n.T
#: pkg/handler/banner.go:103
#: pkg/handler/banner.go:104
#, fuzzy
msgid "Username"
msgstr "用户名"
#. i18n.T
#: pkg/handler/banner.go:104
#: pkg/handler/banner.go:105
msgid "all"
msgstr "所有"
#. i18n.T
#: pkg/handler/banner.go:105
#: pkg/handler/banner.go:106
#, fuzzy
msgid "Search: %s"
msgstr "搜索: %s"
#. i18n.T
#: pkg/proxy/parser.go:130
#: pkg/handler/banner.go:107
msgid "DBType"
msgstr "数据库类型"
#. i18n.T
#: pkg/handler/banner.go:108
#, fuzzy
msgid "DB Name"
msgstr "数据库名称"
#. i18n.T
#: pkg/handler/banner.go:109
msgid "No Databases"
msgstr "无数据库"
#. i18n.T
#: pkg/handler/banner.go:110
#, fuzzy
msgid ""
"Enter ID number directly login the database, multiple search use // + field, "
"such as: //16"
msgstr "提示:输入数据库ID直接登录,二级搜索使用 // + 字段,如://192"
#. i18n.T
#: pkg/proxy/dbproxy.go:112
#, fuzzy
msgid "Database connecting to %s %.1f"
msgstr "连接数据库 %s %.1f"
#. i18n.T
#: pkg/proxy/dbproxy.go:131
#, fuzzy
msgid "System user <%s> and database <%s> protocol are inconsistent."
msgstr "系统用户<%s>和资产<%s>协议不一致"
#. i18n.T
#: pkg/proxy/dbproxy.go:137
msgid "Database %s protocol client not installed."
msgstr "%s 协议的数据库客户端未安装"
#. i18n.T
#: pkg/proxy/dbswitch.go:148
#, fuzzy
msgid "Database connect idle more than %d minutes, disconnect"
msgstr "数据库连接空闲时间超过 %d 分钟,断开连接"
#. i18n.T
#: pkg/proxy/dbswitch.go:155
#, fuzzy
msgid "Database connection terminated by administrator"
msgstr "管理员中断数据库连接"
#. i18n.T
#: pkg/proxy/parser.go:140
msgid "Command `%s` is forbidden"
msgstr "命令 `%s` 是被禁止的 ..."
#. i18n.T
#: pkg/proxy/proxy.go:143
#: pkg/proxy/proxy.go:146
msgid "Reuse SSH connections (%s@%s) [Number of connections: %d]"
msgstr "复用SSH连接(%s@%s)[连接数量: %d]"
#. i18n.T
#: pkg/proxy/proxy.go:161
#: pkg/proxy/proxy.go:164
msgid "Connecting to %s@%s %.1f"
msgstr "开始连接到 %s@%s %.1f"
#. i18n.T
#: pkg/proxy/proxy.go:180
#: pkg/proxy/proxy.go:183
msgid "System user <%s> and asset <%s> protocol are inconsistent."
msgstr "系统用户<%s>和资产<%s>协议不一致"
#. i18n.T
#: pkg/proxy/proxy.go:186
#: pkg/proxy/proxy.go:189
msgid ""
"Terminal only support protocol ssh/telnet, please use web terminal to access"
msgstr "终端仅支持ssh/telnet协议,请使用web终端登录"
#. i18n.T
#: pkg/proxy/sessmanager.go:67
#: pkg/proxy/sessmanager.go:75
msgid "Connect with api server failed"
msgstr "连接API服务失败"
#. i18n.T
#: pkg/proxy/switch.go:168
#: pkg/proxy/sessmanager.go:117
msgid "Create database session failed"
msgstr "创建数据库会话失败"
#. i18n.T
#: pkg/proxy/switch.go:173
msgid "Connect idle more than %d minutes, disconnect"
msgstr "空闲时间超过%d分钟,断开连接"
#. i18n.T
#: pkg/proxy/switch.go:175
#: pkg/proxy/switch.go:180
msgid "Terminated by administrator"
msgstr "管理员中断连接"
......@@ -19695,49 +19695,49 @@ $.fn.elfindersearchbutton = function(cmd) {
});
})
.one('open', function() {
opts = (fm.api < 2.1)? null : $('<div class="ui-front ui-widget ui-widget-content elfinder-button-menu elfinder-button-search-menu ui-corner-all"/>')
.append(
$('<div class="buttonset"/>')
.append(
$('<input id="'+id('SearchFromCwd')+'" name="serchfrom" type="radio" checked="checked"/><label for="'+id('SearchFromCwd')+'">'+fm.i18n('btnCwd')+'</label>'),
$('<input id="'+id('SearchFromVol')+'" name="serchfrom" type="radio"/><label for="'+id('SearchFromVol')+'">'+fm.i18n('btnVolume')+'</label>'),
$('<input id="'+id('SearchFromAll')+'" name="serchfrom" type="radio"/><label for="'+id('SearchFromAll')+'">'+fm.i18n('btnAll')+'</label>')
),
$('<div class="buttonset elfinder-search-type"/>')
.append(
$('<input id="'+id('SearchName')+'" name="serchcol" type="radio" checked="checked" value="SearchName"/><label for="'+id('SearchName')+'">'+fm.i18n('btnFileName')+'</label>')
)
)
.hide()
.appendTo(fm.getUI());
if (opts) {
if (sTypes) {
typeSet = opts.find('.elfinder-search-type');
$.each(cmd.options.searchTypes, function(i, v) {
typeSet.append($('<input id="'+id(i)+'" name="serchcol" type="radio" value="'+fm.escape(i)+'"/><label for="'+id(i)+'">'+fm.i18n(v.name)+'</label>'));
});
}
opts.find('div.buttonset').buttonset();
$('#'+id('SearchFromAll')).next('label').attr('title', fm.i18n('searchTarget', fm.i18n('btnAll')));
if (sTypes) {
$.each(sTypes, function(i, v) {
if (v.title) {
$('#'+id(i)).next('label').attr('title', fm.i18n(v.title));
}
});
}
opts.on('mousedown', 'div.buttonset', function(e){
e.stopPropagation();
opts.data('infocus', true);
})
.on('click', 'input', function(e) {
e.stopPropagation();
$.trim(input.val())? search() : input.trigger('focus');
})
.on('close', function() {
input.trigger('blur');
});
}
// opts = (fm.api < 2.1)? null : $('<div class="ui-front ui-widget ui-widget-content elfinder-button-menu elfinder-button-search-menu ui-corner-all"/>')
// .append(
// $('<div class="buttonset"/>')
// .append(
// $('<input id="'+id('SearchFromCwd')+'" name="serchfrom" type="radio" checked="checked"/><label for="'+id('SearchFromCwd')+'">'+fm.i18n('btnCwd')+'</label>'),
// $('<input id="'+id('SearchFromVol')+'" name="serchfrom" type="radio"/><label for="'+id('SearchFromVol')+'">'+fm.i18n('btnVolume')+'</label>'),
// $('<input id="'+id('SearchFromAll')+'" name="serchfrom" type="radio"/><label for="'+id('SearchFromAll')+'">'+fm.i18n('btnAll')+'</label>')
// ),
// $('<div class="buttonset elfinder-search-type"/>')
// .append(
// $('<input id="'+id('SearchName')+'" name="serchcol" type="radio" checked="checked" value="SearchName"/><label for="'+id('SearchName')+'">'+fm.i18n('btnFileName')+'</label>')
// )
// )
// .hide()
// .appendTo(fm.getUI());
// if (opts) {
// if (sTypes) {
// typeSet = opts.find('.elfinder-search-type');
// $.each(cmd.options.searchTypes, function(i, v) {
// typeSet.append($('<input id="'+id(i)+'" name="serchcol" type="radio" value="'+fm.escape(i)+'"/><label for="'+id(i)+'">'+fm.i18n(v.name)+'</label>'));
// });
// }
// opts.find('div.buttonset').buttonset();
// $('#'+id('SearchFromAll')).next('label').attr('title', fm.i18n('searchTarget', fm.i18n('btnAll')));
// if (sTypes) {
// $.each(sTypes, function(i, v) {
// if (v.title) {
// $('#'+id(i)).next('label').attr('title', fm.i18n(v.title));
// }
// });
// }
// opts.on('mousedown', 'div.buttonset', function(e){
// e.stopPropagation();
// opts.data('infocus', true);
// })
// .on('click', 'input', function(e) {
// e.stopPropagation();
// $.trim(input.val())? search() : input.trigger('focus');
// })
// .on('close', function() {
// input.trigger('blur');
// });
// }
})
.bind('searchend', function() {
input.val('');
......
......@@ -51,7 +51,10 @@
['copy', 'cut', 'paste'],
['rm'],
['rename'],
['view']
['view'],
{{if eq . "_"}}
['search']
{{end}}
],
cwd : {oldSchool: true}
},
......
......@@ -6,12 +6,13 @@ require (
github.com/Azure/azure-pipeline-go v0.1.9 // indirect
github.com/Azure/azure-storage-blob-go v0.6.0
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/LeeEirc/elfinder v0.0.8
github.com/LeeEirc/elfinder v0.0.11
github.com/aliyun/aliyun-oss-go-sdk v1.9.8
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 // indirect
github.com/aws/aws-sdk-go v1.19.46
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
github.com/elastic/go-elasticsearch v0.0.0
github.com/creack/pty v1.1.9
github.com/elastic/go-elasticsearch/v6 v6.8.5
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect
github.com/gliderlabs/ssh v0.2.3-0.20190711180243-866d0ddf7991
github.com/gorilla/mux v1.7.2
......
......@@ -5,8 +5,8 @@ github.com/Azure/azure-storage-blob-go v0.6.0 h1:SEATKb3LIHcaSIX+E6/K4kJpwfuozFE
github.com/Azure/azure-storage-blob-go v0.6.0/go.mod h1:oGfmITT1V6x//CswqY2gtAHND+xIP64/qL7a5QJix0Y=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/LeeEirc/elfinder v0.0.8 h1:y1BSXvtRve6WwMiSYyynY+oEbH+rWMuScoZ1YU67H4E=
github.com/LeeEirc/elfinder v0.0.8/go.mod h1:d1bMAAydkZSBxSN/EuQjBg6B0xcPP3boHuYEpzEHYTs=
github.com/LeeEirc/elfinder v0.0.11 h1:LP+53Q0V2WhxTqR720X7B8rkkX2YDq47dSIGLR1xA9s=
github.com/LeeEirc/elfinder v0.0.11/go.mod h1:d1bMAAydkZSBxSN/EuQjBg6B0xcPP3boHuYEpzEHYTs=
github.com/LeeEirc/sftp v1.10.2 h1:SGpj84RbStlwH+ThXYUsxtxtbzAzpUY8z5gQN4p12OI=
github.com/LeeEirc/sftp v1.10.2/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
github.com/aliyun/aliyun-oss-go-sdk v1.9.8 h1:BOflvK0Zs/zGmoabyFIzTg5c3kguktWTXEwewwbuba0=
......@@ -17,11 +17,13 @@ github.com/aws/aws-sdk-go v1.19.46 h1:lRqljzjkGmEeiawkw4z1QgtCnU/S5Jw8lNeUuvmydU
github.com/aws/aws-sdk-go v1.19.46/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f h1:ZNv7On9kyUzm7fvRZumSyy/IUiSC7AzL0I1jKKtwooA=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc=
github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elastic/go-elasticsearch v0.0.0 h1:Pd5fqOuBxKxv83b0+xOAJDAkziWYwFinWnBO0y+TZaA=
github.com/elastic/go-elasticsearch v0.0.0/go.mod h1:TkBSJBuTyFdBnrNqoPc54FN0vKf5c04IdM4zuStJ7xg=
github.com/elastic/go-elasticsearch/v6 v6.8.5 h1:U2HtkBseC1FNBmDr0TR2tKltL6FxoY+niDAlj5M8TK8=
github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/go-playground/form v3.1.4+incompatible h1:lvKiHVxE2WvzDIoyMnWcjyiBxKt2+uFJyZcPYWsLnjI=
......
......@@ -49,9 +49,10 @@ func Initial() {
{id: 2, instruct: i18n.T("/ + IP, Hostname, Comment"), helpText: i18n.T("to search, such as: /192.168")},
{id: 3, instruct: "p", helpText: i18n.T("display the host you have permission")},
{id: 4, instruct: "g", helpText: i18n.T("display the node that you have permission")},
{id: 5, instruct: "r", helpText: i18n.T("refresh your assets and nodes")},
{id: 6, instruct: "h", helpText: i18n.T("print help")},
{id: 7, instruct: "q", helpText: i18n.T("exit")},
{id: 5, instruct: "d", helpText: i18n.T("display the databases that you have permission")},
{id: 6, instruct: "r", helpText: i18n.T("refresh your assets and nodes")},
{id: 7, instruct: "h", helpText: i18n.T("print help")},
{id: 8, instruct: "q", helpText: i18n.T("exit")},
}
}
......@@ -103,6 +104,10 @@ func getI18nFromMap(name string) string {
"Username": i18n.T("Username"),
"All": i18n.T("all"),
"SearchTip": i18n.T("Search: %s"),
"DBType": i18n.T("DBType"),
"DBName": i18n.T("DB Name"),
"NoDatabases": i18n.T("No Databases"),
"DBLoginTip": i18n.T("Enter ID number directly login the database, multiple search use // + field, such as: //16"),
}
})
return i18nMap[name]
......
package handler
import (
"strings"
"sync"
"github.com/jumpserver/koko/pkg/model"
)
type DatabasePaginator interface {
Paginator
RetrievePageData(pageIndex int) []model.Database
SearchAsset(key string) []model.Database
SearchAgain(key string) []model.Database
Name() string
SearchKeys() []string
}
func NewLocalDatabasePaginator(data [] model.Database, pageSize int) DatabasePaginator {
p := localDatabasePaginator{
allData: data,
currentData: data,
pageSize: pageSize,
currentOffset: 0,
currentPage: 1,
search: make([]string, 0, 4),
lock: new(sync.RWMutex),
}
return &p
}
type localDatabasePaginator struct {
allData []model.Database
currentData []model.Database
currentPage int
pageSize int
totalPage int
currentOffset int
search []string
lock *sync.RWMutex
currentResult []model.Database
}
func (l *localDatabasePaginator) Name() string {
return "local"
}
func (l *localDatabasePaginator) SearchKeys() []string {
return l.search
}
func (l *localDatabasePaginator) HasPrev() bool {
l.lock.RLock()
defer l.lock.RUnlock()
return l.currentPage > 1
}
func (l *localDatabasePaginator) HasNext() bool {
l.lock.RLock()
defer l.lock.RUnlock()
return l.currentPage < l.totalPage
}
func (l *localDatabasePaginator) CurrentPage() int {
l.lock.RLock()
defer l.lock.RUnlock()
return l.currentPage
}
func (l *localDatabasePaginator) TotalCount() int {
l.lock.RLock()
defer l.lock.RUnlock()
return len(l.currentData)
}
func (l *localDatabasePaginator) TotalPage() int {
l.lock.RLock()
defer l.lock.RUnlock()
return l.totalPage
}
func (l *localDatabasePaginator) PageSize() int {
l.lock.RLock()
defer l.lock.RUnlock()
return l.pageSize
}
func (l *localDatabasePaginator) SetPageSize(size int) {
if size <= 0 {
size = len(l.currentData)
}
l.lock.Lock()
defer l.lock.Unlock()
if l.pageSize == size {
return
}
l.pageSize = size
}
func (l *localDatabasePaginator) RetrievePageData(pageIndex int) []model.Database {
l.lock.Lock()
defer l.lock.Unlock()
return l.retrievePageData(pageIndex)
}
func (l *localDatabasePaginator) SearchAsset(key string) []model.Database {
l.lock.Lock()
defer l.lock.Unlock()
l.search = l.search[:0]
l.search = append(l.search, key)
l.currentData = searchFromLocalDBs(l.allData, key)
l.currentPage = 1
l.currentOffset = 0
return l.retrievePageData(1)
}
func (l *localDatabasePaginator) SearchAgain(key string) []model.Database {
l.lock.Lock()
defer l.lock.Unlock()
l.currentData = searchFromLocalDBs(l.currentData, key)
l.search = append(l.search, key)
l.currentPage = 1
l.currentOffset = 0
return l.retrievePageData(1)
}
func (l *localDatabasePaginator) retrievePageData(pageIndex int) []model.Database {
offsetPage := pageIndex - l.currentPage
totalOffset := offsetPage * l.pageSize
l.currentOffset += totalOffset
switch {
case l.currentOffset <= 0:
l.currentOffset = 0
case l.currentOffset >= len(l.currentData):
l.currentOffset = len(l.currentData)
case l.pageSize >= len(l.currentData):
l.currentOffset = 0
}
end := l.currentOffset + l.pageSize
if end >= len(l.currentData) {
end = len(l.currentData)
}
l.currentResult = l.currentData[l.currentOffset:end]
l.updatePageInfo()
return l.currentResult
}
func (l *localDatabasePaginator) updatePageInfo() {
pageSize := l.pageSize
totalCount := len(l.currentData)
switch totalCount % pageSize {
case 0:
l.totalPage = totalCount / pageSize
default:
l.totalPage = (totalCount / pageSize) + 1
}
offset := l.currentOffset + len(l.currentResult)
switch offset % pageSize {
case 0:
l.currentPage = offset / pageSize
default:
l.currentPage = (offset / pageSize) + 1
}
}
func searchFromLocalDBs(dbs []model.Database, key string) []model.Database {
displayDBs := make([]model.Database, 0, len(dbs))
key = strings.ToLower(key)
for _, db := range dbs {
contents := []string{strings.ToLower(db.Name),strings.ToLower(db.DBName),
strings.ToLower(db.Host), strings.ToLower(db.Comment)}
if isSubstring(contents, key) {
displayDBs = append(displayDBs, db)
}
}
return displayDBs
}
......@@ -10,6 +10,8 @@ import (
"github.com/jumpserver/koko/pkg/config"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/proxy"
"github.com/jumpserver/koko/pkg/service"
"github.com/jumpserver/koko/pkg/utils"
)
......@@ -32,20 +34,34 @@ func (h *interactiveHandler) Dispatch() {
h.movePrePage()
break
}
if h.dbPaginator != nil {
h.moveDBPrePage()
break
}
if ok := h.searchOrProxy(line); ok {
continue
}
case "d":
h.assetPaginator = nil
h.dbPaginator = h.getDatabasePaginator()
h.currentDBData = h.dbPaginator.RetrievePageData(1)
case "n":
if h.assetPaginator != nil {
h.moveNextPage()
break
}
if h.dbPaginator != nil {
h.moveDBNextPage()
break
}
if ok := h.searchOrProxy(line); ok {
continue
}
case "":
if h.assetPaginator != nil {
h.moveNextPage()
} else if h.dbPaginator != nil {
h.moveDBNextPage()
} else {
h.resetPaginator()
}
......@@ -96,11 +112,19 @@ func (h *interactiveHandler) Dispatch() {
}
}
}
h.displayPageAssets()
if h.dbPaginator != nil {
h.displayPageDatabase()
}
if h.assetPaginator != nil {
h.displayPageAssets()
}
}
}
func (h *interactiveHandler) resetPaginator() {
h.dbPaginator = nil
h.currentDBData = nil
h.assetPaginator = h.getAssetPaginator()
h.currentData = h.assetPaginator.RetrievePageData(1)
}
......@@ -210,6 +234,26 @@ func (h *interactiveHandler) searchAssets(key string) []model.Asset {
}
func (h *interactiveHandler) searchOrProxy(key string) bool {
if h.dbPaginator != nil {
if indexNum, err := strconv.Atoi(key); err == nil && len(h.currentDBData) > 0 {
if indexNum > 0 && indexNum <= len(h.currentDBData) {
dbSelected := h.currentDBData[indexNum-1]
h.ProxyDB(dbSelected)
h.dbPaginator = nil
h.currentDBData = nil
return true
}
}
if data := h.dbPaginator.SearchAsset(key); len(data) == 1 {
h.ProxyDB(data[0])
h.dbPaginator = nil
h.currentDBData = nil
return true
} else {
h.currentDBData = data
}
return false
}
if indexNum, err := strconv.Atoi(key); err == nil && len(h.currentSortedData) > 0 {
if indexNum > 0 && indexNum <= len(h.currentSortedData) {
assetSelect := h.currentSortedData[indexNum-1]
......@@ -231,10 +275,16 @@ func (h *interactiveHandler) searchOrProxy(key string) bool {
}
func (h *interactiveHandler) searchAssetAndDisplay(key string) {
h.currentDBData = nil
h.dbPaginator = nil
h.currentData = h.searchAssets(key)
}
func (h *interactiveHandler) searchAssetsAgain(key string) {
if h.dbPaginator != nil {
h.currentDBData = h.dbPaginator.SearchAgain(key)
return
}
if h.assetPaginator == nil {
h.assetPaginator = h.getAssetPaginator()
h.currentData = h.assetPaginator.SearchAsset(key)
......@@ -279,3 +329,189 @@ func (h *interactiveHandler) getAssetPaginator() AssetPaginator {
func (h *interactiveHandler) getNodeAssetPaginator(node model.Node) AssetPaginator {
return NewNodeAssetPaginator(*h.user, node, getPageSize(h.term))
}
func (h *interactiveHandler) getDatabasePaginator() DatabasePaginator {
dbs := service.GetUserDatabases(h.user.ID)
return NewLocalDatabasePaginator(dbs, getPageSize(h.term))
}
func (h *interactiveHandler) displayPageDatabase() {
if len(h.currentDBData) == 0 {
_, _ = h.term.Write([]byte(getI18nFromMap("NoDatabases") + "\n\r"))
h.dbPaginator = nil
return
}
Labels := []string{getI18nFromMap("ID"), getI18nFromMap("Name"),
getI18nFromMap("IP"), getI18nFromMap("DBType"),
getI18nFromMap("DBName"),getI18nFromMap("Comment")}
fields := []string{"ID", "name", "IP", "DBType","DBName", "comment"}
data := make([]map[string]string, len(h.currentDBData))
for i, j := range h.currentDBData {
row := make(map[string]string)
row["ID"] = strconv.Itoa(i + 1)
row["name"] = j.Name
row["IP"] = j.Host
row["DBType"] = j.DBType
row["DBName"] = j.DBName
comments := make([]string, 0)
for _, item := range strings.Split(strings.TrimSpace(j.Comment), "\r\n") {
if strings.TrimSpace(item) == "" {
continue
}
comments = append(comments, strings.ReplaceAll(strings.TrimSpace(item), " ", ","))
}
row["comment"] = strings.Join(comments, "|")
data[i] = row
}
w, _ := h.term.GetSize()
currentPage := h.dbPaginator.CurrentPage()
pageSize := h.dbPaginator.PageSize()
totalPage := h.dbPaginator.TotalPage()
totalCount := h.dbPaginator.TotalCount()
caption := fmt.Sprintf(getI18nFromMap("AssetTableCaption"),
currentPage, pageSize, totalPage, totalCount)
caption = utils.WrapperString(caption, utils.Green)
table := common.WrapperTable{
Fields: fields,
Labels: Labels,
FieldsSize: map[string][3]int{
"ID": {0, 0, 5},
"name": {0, 8, 0},
"IP": {0, 15, 40},
"DBType": {0, 8, 0},
"DBName": {0, 8, 0},
"comment": {0, 0, 0},
},
Data: data,
TotalSize: w,
Caption: caption,
TruncPolicy: common.TruncMiddle,
}
table.Initial()
header := getI18nFromMap("All")
keys := h.dbPaginator.SearchKeys()
switch h.dbPaginator.Name() {
case "local", "remote":
if len(keys) != 0 {
header = strings.Join(keys, " ")
}
default:
header = fmt.Sprintf("%s %s", h.dbPaginator.Name(), strings.Join(keys, " "))
}
searchHeader := fmt.Sprintf(getI18nFromMap("SearchTip"), header)
actionTip := fmt.Sprintf("%s %s", getI18nFromMap("DBLoginTip"), getI18nFromMap("PageActionTip"))
_, _ = h.term.Write([]byte(utils.CharClear))
_, _ = h.term.Write([]byte(table.Display()))
utils.IgnoreErrWriteString(h.term, utils.WrapperString(actionTip, utils.Green))
utils.IgnoreErrWriteString(h.term, utils.CharNewLine)
utils.IgnoreErrWriteString(h.term, utils.WrapperString(searchHeader, utils.Green))
utils.IgnoreErrWriteString(h.term, utils.CharNewLine)
}
func (h *interactiveHandler) moveDBPrePage() {
if h.dbPaginator == nil || !h.dbPaginator.HasPrev() {
return
}
h.dbPaginator.SetPageSize(getPageSize(h.term))
prePage := h.dbPaginator.CurrentPage() - 1
h.currentDBData = h.dbPaginator.RetrievePageData(prePage)
}
func (h *interactiveHandler) moveDBNextPage() {
if h.dbPaginator == nil || !h.dbPaginator.HasNext() {
return
}
h.dbPaginator.SetPageSize(getPageSize(h.term))
prePage := h.dbPaginator.CurrentPage() + 1
h.currentDBData = h.dbPaginator.RetrievePageData(prePage)
}
func (h *interactiveHandler) ProxyDB(dbSelect model.Database) {
systemUsers := service.GetUserDatabaseSystemUsers(h.user.ID, dbSelect.ID)
systemUserSelect, ok := h.chooseDBSystemUser(dbSelect, systemUsers)
if !ok {
return
}
p := proxy.DBProxyServer{
UserConn: h.sess,
User: h.user,
Database: &dbSelect,
SystemUser: &systemUserSelect,
}
h.pauseWatchWinSize()
p.Proxy()
logger.Infof("Request %s: database %s proxy end", h.sess.Uuid, dbSelect.Name)
h.resumeWatchWinSize()
}
func (h *interactiveHandler) chooseDBSystemUser(dbAsset model.Database,
systemUsers []model.SystemUser) (systemUser model.SystemUser, ok bool) {
length := len(systemUsers)
switch length {
case 0:
return model.SystemUser{}, false
case 1:
return systemUsers[0], true
default:
}
displaySystemUsers := selectHighestPrioritySystemUsers(systemUsers)
if len(displaySystemUsers) == 1 {
return displaySystemUsers[0], true
}
Labels := []string{getI18nFromMap("ID"), getI18nFromMap("Name"), getI18nFromMap("Username")}
fields := []string{"ID", "Name", "Username"}
data := make([]map[string]string, len(displaySystemUsers))
for i, j := range displaySystemUsers {
row := make(map[string]string)
row["ID"] = strconv.Itoa(i + 1)
row["Name"] = j.Name
row["Username"] = j.Username
data[i] = row
}
w, _ := h.term.GetSize()
table := common.WrapperTable{
Fields: fields,
Labels: Labels,
FieldsSize: map[string][3]int{
"ID": {0, 0, 5},
"Name": {0, 8, 0},
"Username": {0, 10, 0},
},
Data: data,
TotalSize: w,
TruncPolicy: common.TruncMiddle,
}
table.Initial()
h.term.SetPrompt("ID> ")
defer h.term.SetPrompt("Opt> ")
selectUserTip := fmt.Sprintf(getI18nFromMap("SelectUserTip"), dbAsset.Name, dbAsset.Host)
for {
utils.IgnoreErrWriteString(h.term, table.Display())
utils.IgnoreErrWriteString(h.term, selectUserTip)
utils.IgnoreErrWriteString(h.term, getI18nFromMap("BackTip"))
utils.IgnoreErrWriteString(h.term, "\r\n")
line, err := h.term.ReadLine()
if err != nil {
return
}
line = strings.TrimSpace(line)
switch strings.ToLower(line) {
case "q", "b", "quit", "exit", "back":
return
}
if num, err := strconv.Atoi(line); err == nil {
if num > 0 && num <= len(displaySystemUsers) {
return displaySystemUsers[num-1], true
}
}
}
}
......@@ -68,6 +68,9 @@ type interactiveHandler struct {
currentData []model.Asset
assetPaginator AssetPaginator
dbPaginator DatabasePaginator
currentDBData []model.Database
}
func (h *interactiveHandler) Initial() {
......@@ -207,6 +210,7 @@ func (h *interactiveHandler) refreshAssetsAndNodesData() {
logger.Error("refresh Assets Nodes err:", err)
}
h.assetPaginator = nil
h.dbPaginator = nil
}
func (h *interactiveHandler) loadUserNodes(cachePolicy string) {
......@@ -238,6 +242,7 @@ func (h *interactiveHandler) Proxy(ctx context.Context) {
h.pauseWatchWinSize()
p.Proxy()
h.resumeWatchWinSize()
logger.Infof("Request %s: asset %s proxy end", h.sess.Uuid, h.assetSelect.Hostname)
}
func ConstructAssetNodeTree(assetNodes []model.Node) treeprint.Tree {
......@@ -335,4 +340,4 @@ func getPageSize(term *utils.Terminal) int {
pageSize = 1
}
return pageSize
}
\ No newline at end of file
}
......@@ -14,7 +14,6 @@ import (
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/service"
"github.com/jumpserver/koko/pkg/srvconn"
)
......@@ -46,12 +45,11 @@ func SftpHandler(sess ssh.Session) {
}
func NewSFTPHandler(user *model.User, addr string) *sftpHandler {
assets := service.GetUserAllAssets(user.ID)
return &sftpHandler{srvconn.NewUserSFTP(user, addr, assets...)}
return &sftpHandler{srvconn.NewUserSftpConn(user, addr)}
}
type sftpHandler struct {
*srvconn.UserSftp
*srvconn.UserSftpConn
}
func (fs *sftpHandler) Filelist(r *sftp.Request) (sftp.ListerAt, error) {
......@@ -122,7 +120,7 @@ func (fs *sftpHandler) Fileread(r *sftp.Request) (io.ReaderAt, error) {
}
func (fs *sftpHandler) Close() {
fs.UserSftp.Close()
fs.UserSftpConn.Close()
}
type listerat []os.FileInfo
......
package httpd
type HostMsg struct {
Uuid string `json:"uuid"`
UserID string `json:"userid"`
Secret string `json:"secret"`
Size []int `json:"size"`
Uuid string `json:"uuid"`
UserID string `json:"userid"`
Secret string `json:"secret"`
Size []int `json:"size"`
HostType string `json:"type"`
}
type ResizeMsg struct {
......
......@@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"
"sync"
"time"
"github.com/LeeEirc/elfinder"
"github.com/pkg/sftp"
......@@ -18,26 +19,24 @@ import (
)
func NewUserVolume(user *model.User, addr, hostId string) *UserVolume {
var assets []model.Asset
var userSftp *srvconn.UserSftpConn
homename := "Home"
basePath := "/"
switch hostId {
case "":
assets = service.GetUserAllAssets(user.ID)
userSftp = srvconn.NewUserSftpConn(user, addr)
default:
assets = service.GetUserAssetByID(user.ID, hostId)
assets := service.GetUserAssetByID(user.ID, hostId)
if len(assets) == 1 {
homename = assets[0].Hostname
if assets[0].OrgID != "" {
homename = fmt.Sprintf("%s.%s", assets[0].Hostname, assets[0].OrgName)
}
basePath = filepath.Join("/", homename)
}
userSftp = srvconn.NewUserSftpConnWithAssets(user, addr, assets...)
}
rawID := fmt.Sprintf("%s@%s", user.Username, addr)
uVolume := &UserVolume{
Uuid: elfinder.GenerateID(rawID),
UserSftp: srvconn.NewUserSFTP(user, addr, assets...),
UserSftp: userSftp,
Homename: homename,
basePath: basePath,
chunkFilesMap: make(map[int]*sftp.File),
......@@ -47,8 +46,8 @@ func NewUserVolume(user *model.User, addr, hostId string) *UserVolume {
}
type UserVolume struct {
Uuid string
*srvconn.UserSftp
Uuid string
UserSftp *srvconn.UserSftpConn
Homename string
basePath string
......@@ -66,7 +65,7 @@ func (u *UserVolume) Info(path string) (elfinder.FileDir, error) {
if path == "/" {
return u.RootFileDir(), nil
}
originFileInfo, err := u.Stat(filepath.Join(u.basePath, path))
originFileInfo, err := u.UserSftp.Stat(filepath.Join(u.basePath, path))
if err != nil {
return rest, err
}
......@@ -300,22 +299,44 @@ func (u *UserVolume) Paste(dir, filename, suffix string, reader io.ReadCloser) (
func (u *UserVolume) RootFileDir() elfinder.FileDir {
logger.Debug("Root File Dir")
fInfo, _ := u.UserSftp.Stat(u.basePath)
var (
size int64
)
tz := time.Now().UnixNano()
if fInfo, err := u.UserSftp.Stat(u.basePath); err == nil {
size = fInfo.Size()
tz = fInfo.ModTime().Unix()
}
var rest elfinder.FileDir
rest.Name = u.Homename
rest.Hash = hashPath(u.Uuid, "/")
rest.Size = fInfo.Size()
rest.Size = size
rest.Volumeid = u.Uuid
rest.Mime = "directory"
rest.Dirs = 1
rest.Read, rest.Write = 1, 1
rest.Locked = 1
rest.Ts = fInfo.ModTime().Unix()
rest.Ts = tz
return rest
}
func (u *UserVolume) Close() {
u.UserSftp.Close()
logger.Infof("User %s's volume close", u.UserSftp.User.Name)
}
func (u *UserVolume) Search(path, key string, mimes ...string) (res []elfinder.FileDir, err error) {
originFileInfolist, err := u.UserSftp.Search(key)
if err != nil {
return nil, err
}
res = make([]elfinder.FileDir, 0, len(originFileInfolist))
searchPath := fmt.Sprintf("/%s", srvconn.SearchFolderName)
for i := 0; i < len(originFileInfolist); i++ {
res = append(res, NewElfinderFileInfo(u.Uuid, searchPath, originFileInfolist[i]))
}
return
}
func NewElfinderFileInfo(id, dirPath string, originFileInfo os.FileInfo) elfinder.FileDir {
......
......@@ -20,6 +20,10 @@ import (
"github.com/jumpserver/koko/pkg/service"
)
type proxyServer interface {
Proxy()
}
func OnPingHandler(c *neffos.NSConn, msg neffos.Message) error {
c.Emit("pong", []byte(""))
return nil
......@@ -106,18 +110,32 @@ func OnHostHandler(c *neffos.NSConn, msg neffos.Message) (err error) {
emitMsg := RoomMsg{roomID, secret}
roomMsg, _ := json.Marshal(emitMsg)
c.Emit("room", roomMsg)
var databaseAsset model.Database
var asset model.Asset
asset := service.GetAsset(assetID)
systemUser := service.GetSystemUser(systemUserID)
if message.HostType == "database" {
databaseAsset = service.GetDatabase(assetID)
if databaseAsset.ID == "" || systemUser.ID == "" {
msg := "No database id or system user id found, exit"
logger.Info(msg)
dataMsg := DataMsg{Room: roomID, Data: msg}
c.Emit("data", neffos.Marshal(dataMsg))
return
}
if asset.ID == "" || systemUser.ID == "" {
msg := "No asset id or system user id found, exit"
logger.Debug(msg)
dataMsg := DataMsg{Room: roomID, Data: msg}
c.Emit("data", neffos.Marshal(dataMsg))
return
logger.Infof("Web terminal want to connect database: %s", databaseAsset.Name)
} else {
asset = service.GetAsset(assetID)
if asset.ID == "" || systemUser.ID == "" {
msg := "No asset id or system user id found, exit"
logger.Debug(msg)
dataMsg := DataMsg{Room: roomID, Data: msg}
c.Emit("data", neffos.Marshal(dataMsg))
return
}
logger.Infof("Web terminal want to connect host: %s", asset.Hostname)
}
logger.Debug("Web terminal want to connect host: ", asset.Hostname)
currentUser, ok := cc.Get("currentUser").(*model.User)
if !ok {
err = errors.New("not found current user")
......@@ -149,9 +167,20 @@ func OnHostHandler(c *neffos.NSConn, msg neffos.Message) (err error) {
client.WinChan <- win
clients.AddClient(roomID, client)
conns.AddClient(cc.ID(), roomID)
proxySrv := proxy.ProxyServer{
UserConn: client, User: currentUser,
Asset: &asset, SystemUser: &systemUser,
var proxySrv proxyServer
if message.HostType == "database" {
proxySrv = &proxy.DBProxyServer{
UserConn: client,
User: currentUser,
Database: &databaseAsset,
SystemUser: &systemUser,
}
} else {
proxySrv = &proxy.ProxyServer{
UserConn: client, User: currentUser,
Asset: &asset, SystemUser: &systemUser,
}
}
go func() {
defer logger.Infof("Request %s: Web ssh end proxy process", client.Uuid)
......
......@@ -16,7 +16,7 @@ import (
"github.com/jumpserver/koko/pkg/sshd"
)
const Version = "1.5.5"
const Version = "1.5.6"
type Coco struct {
}
......
......@@ -90,7 +90,6 @@ type Asset struct {
IP string `json:"ip"`
Os string `json:"os"`
Domain string `json:"domain"`
Platform string `json:"platform"`
Comment string `json:"comment"`
Protocols []string `json:"protocols,omitempty"`
OrgID string `json:"org_id"`
......
package model
import "fmt"
type Database struct {
ID string `json:"id"`
Name string `json:"name"`
DBType string `json:"type"`
Host string `json:"host"`
Port int `json:"port"`
DBName string `json:"database"`
OrgID string `json:"org_id"`
Comment string `json:"comment"`
}
func (db Database) String() string {
return fmt.Sprintf("%s://%s:%d/%s", db.DBType, db.Host, db.Port, db.DBName)
}
package model
import "encoding/json"
type NodeTreeList []NodeTreeAsset
type NodeTreeAsset struct {
ID string `json:"id"`
Name string `json:"name"`
Title string `json:"title"`
Pid string `json:"pId"`
IsParent bool `json:"isParent"`
Meta map[string]interface{} `json:"meta"`
}
func ConvertMetaToNode(body []byte) (node Node, err error) {
err = json.Unmarshal(body, &node)
return
}
func ConvertMetaToAsset(body []byte) (asset Asset, err error) {
err = json.Unmarshal(body, &asset)
return
}
package proxy
import (
"bytes"
"sync"
"github.com/jumpserver/koko/pkg/logger"
)
const (
DBInputParserName = "DB Input parser"
DBOutputParserName = "DB Output parser"
)
func newDBParser(id string) DBParser {
dbParser := DBParser{
id: id,
}
dbParser.initial()
return dbParser
}
type DBParser struct {
id string
userOutputChan chan []byte
srvOutputChan chan []byte
cmdRecordChan chan [2]string
inputInitial bool
inputPreState bool
inputState bool
once *sync.Once
lock *sync.RWMutex
command string
output string
cmdInputParser *CmdParser
cmdOutputParser *CmdParser
closed chan struct{}
}
func (p *DBParser) initial() {
p.once = new(sync.Once)
p.lock = new(sync.RWMutex)
p.cmdInputParser = NewCmdParser(p.id, DBInputParserName)
p.cmdOutputParser = NewCmdParser(p.id, DBOutputParserName)
p.closed = make(chan struct{})
p.cmdRecordChan = make(chan [2]string, 1024)
}
// ParseStream 解析数据流
func (p *DBParser) ParseStream(userInChan, srvInChan <-chan []byte) (userOut, srvOut <-chan []byte) {
p.userOutputChan = make(chan []byte, 1)
p.srvOutputChan = make(chan []byte, 1)
logger.Infof("DB Session %s: Parser start", p.id)
go func() {
defer func() {
// 会话结束,结算命令结果
p.sendCommandRecord()
close(p.cmdRecordChan)
close(p.userOutputChan)
close(p.srvOutputChan)
_ = p.cmdOutputParser.Close()
_ = p.cmdInputParser.Close()
logger.Infof("DB Session %s: Parser routine done", p.id)
}()
for {
select {
case <-p.closed:
return
case b, ok := <-userInChan:
if !ok {
return
}
b = p.ParseUserInput(b)
select {
case <-p.closed:
return
case p.userOutputChan <- b:
}
case b, ok := <-srvInChan:
if !ok {
return
}
b = p.ParseServerOutput(b)
select {
case <-p.closed:
return
case p.srvOutputChan <- b:
}
}
}
}()
return p.userOutputChan, p.srvOutputChan
}
// parseInputState 切换用户输入状态, 并结算命令和结果
func (p *DBParser) parseInputState(b []byte) []byte {
p.inputPreState = p.inputState
if bytes.Contains(b, charEnter) {
// 连续输入enter key, 结算上一条可能存在的命令结果
p.sendCommandRecord()
p.inputState = false
// 用户输入了Enter,开始结算命令
p.parseCmdInput()
} else {
p.inputState = true
// 用户又开始输入,并上次不处于输入状态,开始结算上次命令的结果
if !p.inputPreState {
p.sendCommandRecord()
}
}
return b
}
// parseCmdInput 解析命令的输入
func (p *DBParser) parseCmdInput() {
p.command = p.cmdInputParser.Parse()
}
// parseCmdOutput 解析命令输出
func (p *DBParser) parseCmdOutput() {
p.output = p.cmdOutputParser.Parse()
}
// ParseUserInput 解析用户的输入
func (p *DBParser) ParseUserInput(b []byte) []byte {
p.lock.Lock()
defer p.lock.Unlock()
p.once.Do(func() {
p.inputInitial = true
})
nb := p.parseInputState(b)
return nb
}
// splitCmdStream 将服务器输出流分离到命令buffer和命令输出buffer
func (p *DBParser) splitCmdStream(b []byte) {
if !p.inputInitial {
return
}
if p.inputState {
_, _ = p.cmdInputParser.WriteData(b)
return
}
_, _ = p.cmdOutputParser.WriteData(b)
}
// ParseServerOutput 解析服务器输出
func (p *DBParser) ParseServerOutput(b []byte) []byte {
p.lock.Lock()
defer p.lock.Unlock()
p.splitCmdStream(b)
return b
}
// Close 关闭parser
func (p *DBParser) Close() {
select {
case <-p.closed:
return
default:
close(p.closed)
}
}
func (p *DBParser) sendCommandRecord() {
if p.command != "" {
p.parseCmdOutput()
p.cmdRecordChan <- [2]string{p.command, p.output}
p.command = ""
p.output = ""
}
}
package proxy
import (
"fmt"
"strings"
"time"
"github.com/jumpserver/koko/pkg/config"
"github.com/jumpserver/koko/pkg/i18n"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/service"
"github.com/jumpserver/koko/pkg/srvconn"
"github.com/jumpserver/koko/pkg/utils"
)
type DBProxyServer struct {
UserConn UserConnection
User *model.User
Database *model.Database
SystemUser *model.SystemUser
}
func (p *DBProxyServer) getAuthOrManualSet() error {
needManualSet := false
if p.SystemUser.LoginMode == model.LoginModeManual {
needManualSet = true
logger.Debugf("Database %s login mode is: %s", p.Database.Name, model.LoginModeManual)
}
if p.SystemUser.Password == "" {
needManualSet = true
logger.Debugf("Database %s neither has password", p.Database.Name)
}
if needManualSet {
term := utils.NewTerminal(p.UserConn, "password: ")
line, err := term.ReadPassword(fmt.Sprintf("%s's password: ", p.SystemUser.Username))
if err != nil {
logger.Errorf("Get password from user err %s", err.Error())
return err
}
p.SystemUser.Password = line
logger.Debug("Get password from user input: ", line)
}
return nil
}
func (p *DBProxyServer) getUsernameIfNeed() (err error) {
if p.SystemUser.Username == "" {
var username string
term := utils.NewTerminal(p.UserConn, "username: ")
for {
username, err = term.ReadLine()
if err != nil {
return err
}
username = strings.TrimSpace(username)
if username != "" {
break
}
}
p.SystemUser.Username = username
logger.Debug("Get username from user input: ", username)
}
return
}
func (p *DBProxyServer) checkProtocolMatch() bool {
return strings.ToLower(p.Database.DBType) == strings.ToLower(p.SystemUser.Protocol)
}
func (p *DBProxyServer) checkProtocolClientInstalled() bool {
switch strings.ToLower(p.Database.DBType) {
case "mysql":
return utils.IsInstalledMysqlClient()
}
return false
}
// validatePermission 检查是否有权限连接
func (p *DBProxyServer) validatePermission() bool {
return true
}
// getSSHConn 获取ssh连接
func (p *DBProxyServer) getMysqlConn() (srvConn *srvconn.ServerMysqlConnection, err error) {
srvConn = srvconn.NewMysqlServer(
srvconn.SqlHost(p.Database.Host),
srvconn.SqlPort(p.Database.Port),
srvconn.SqlUsername(p.SystemUser.Username),
srvconn.SqlPassword(p.SystemUser.Password),
srvconn.SqlDBName(p.Database.DBName),
)
err = srvConn.Connect()
return
}
// getServerConn 获取获取server连接
func (p *DBProxyServer) getServerConn() (srvConn srvconn.ServerConnection, err error) {
done := make(chan struct{})
defer func() {
utils.IgnoreErrWriteString(p.UserConn, "\r\n")
close(done)
}()
go p.sendConnectingMsg(done, config.GetConf().SSHTimeout*time.Second)
return p.getMysqlConn()
}
// sendConnectingMsg 发送连接信息
func (p *DBProxyServer) sendConnectingMsg(done chan struct{}, delayDuration time.Duration) {
delay := 0.0
msg := fmt.Sprintf(i18n.T("Database connecting to %s %.1f"), p.Database, delay)
utils.IgnoreErrWriteString(p.UserConn, msg)
for int(delay) < int(delayDuration/time.Second) {
select {
case <-done:
return
default:
delayS := fmt.Sprintf("%.1f", delay)
data := strings.Repeat("\x08", len(delayS)) + delayS
utils.IgnoreErrWriteString(p.UserConn, data)
time.Sleep(100 * time.Millisecond)
delay += 0.1
}
}
}
// preCheckRequisite 检查是否满足条件
func (p *DBProxyServer) preCheckRequisite() (ok bool) {
if !p.checkProtocolMatch() {
msg := utils.WrapperWarn(i18n.T("System user <%s> and database <%s> protocol are inconsistent."))
msg = fmt.Sprintf(msg, p.SystemUser.Username, p.Database.DBType)
utils.IgnoreErrWriteString(p.UserConn, msg)
return
}
if !p.checkProtocolClientInstalled() {
msg := utils.WrapperWarn(i18n.T("Database %s protocol client not installed."))
msg = fmt.Sprintf(msg, p.Database.DBType)
utils.IgnoreErrWriteString(p.UserConn, msg)
return
}
if !p.validatePermission() {
msg := fmt.Sprintf("You don't have permission login %s", p.Database.Name)
utils.IgnoreErrWriteString(p.UserConn, msg)
return
}
if err := p.checkRequiredAuth(); err != nil {
msg := fmt.Sprintf("You get database %s auth info err: %s", p.Database.Name, err)
utils.IgnoreErrWriteString(p.UserConn, msg)
return
}
return true
}
func (p *DBProxyServer) checkRequiredAuth() error {
info := service.GetSystemUserDatabaseAuthInfo(p.SystemUser.ID)
p.SystemUser.Password = info.Password
if err := p.getUsernameIfNeed(); err != nil {
logger.Errorf("Get database %s auth username err: %s", p.Database.Name, err)
return err
}
if err := p.getAuthOrManualSet(); err != nil {
logger.Errorf("Get database %s auth password err: %s", p.Database.Name, err)
return err
}
return nil
}
// sendConnectErrorMsg 发送连接错误消息
func (p *DBProxyServer) sendConnectErrorMsg(err error) {
msg := fmt.Sprintf("Connect database %s error: %s\r\n", p.Database.Host, err)
utils.IgnoreErrWriteString(p.UserConn, msg)
logger.Error(msg)
}
// Proxy 代理
func (p *DBProxyServer) Proxy() {
if !p.preCheckRequisite() {
logger.Error("Check requisite failed")
return
}
// 创建Session
sw, err := CreateDBSession(p)
if err != nil {
logger.Error("Create database Session failed")
return
}
defer RemoveDBSession(sw)
srvConn, err := p.getServerConn()
// 连接后端服务器失败
if err != nil {
logger.Errorf("Create database server conn failed: %s", err)
p.sendConnectErrorMsg(err)
return
}
if err = sw.Bridge(p.UserConn, srvConn); err != nil {
logger.Errorf("DB Session %s bridge end: %s", sw.ID, err)
}
}
package proxy
import (
"context"
"fmt"
"io"
"strings"
"time"
uuid "github.com/satori/go.uuid"
"github.com/jumpserver/koko/pkg/common"
"github.com/jumpserver/koko/pkg/config"
"github.com/jumpserver/koko/pkg/i18n"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/srvconn"
"github.com/jumpserver/koko/pkg/utils"
)
type DBSwitchSession struct {
ID string
p *DBProxyServer
DateStart string
DateEnd string
finished bool
MaxIdleTime time.Duration
ctx context.Context
cancel context.CancelFunc
}
func (s *DBSwitchSession) Initial() {
s.ID = uuid.NewV4().String()
s.DateStart = common.CurrentUTCTime()
s.MaxIdleTime = config.GetConf().MaxIdleTime
s.ctx, s.cancel = context.WithCancel(context.Background())
}
func (s *DBSwitchSession) Terminate() {
select {
case <-s.ctx.Done():
return
default:
}
s.cancel()
logger.Infof("DBSession %s: receive terminate from admin", s.ID)
}
func (s *DBSwitchSession) SessionID() string {
return s.ID
}
func (s *DBSwitchSession) recordCommand(cmdRecordChan chan [2]string) {
// 命令记录
cmdRecorder := NewCommandRecorder(s.ID)
for command := range cmdRecordChan {
if command[0] == "" {
continue
}
cmd := s.generateCommandResult(command)
cmdRecorder.Record(cmd)
}
// 关闭命令记录
cmdRecorder.End()
}
func (s *DBSwitchSession) generateCommandResult(command [2]string) *model.Command {
var input string
var output string
if len(command[0]) > 128 {
input = command[0][:128]
} else {
input = command[0]
}
i := strings.LastIndexByte(command[1], '\r')
if i <= 0 {
output = command[1]
} else if i > 0 && i < 1024 {
output = command[1][:i]
} else {
output = command[1][:1024]
}
return &model.Command{
SessionID: s.ID,
OrgID: s.p.Database.OrgID,
Input: input,
Output: output,
User: fmt.Sprintf("%s (%s)", s.p.User.Name, s.p.User.Username),
Server: s.p.Database.Name,
SystemUser: s.p.SystemUser.Username,
Timestamp: time.Now().Unix(),
}
}
// postBridge 桥接结束以后执行操作
func (s *DBSwitchSession) postBridge() {
s.DateEnd = common.CurrentUTCTime()
s.finished = true
}
// Bridge 桥接两个链接
func (s *DBSwitchSession) Bridge(userConn UserConnection, srvConn srvconn.ServerConnection) (err error) {
var (
parser DBParser
replayRecorder ReplyRecorder
userInChan chan []byte
srvInChan chan []byte
done chan struct{}
)
parser = newDBParser(s.ID)
replayRecorder = NewReplyRecord(s.ID)
userInChan = make(chan []byte, 1)
srvInChan = make(chan []byte, 1)
done = make(chan struct{})
userOutChan, srvOutChan := parser.ParseStream(userInChan, srvInChan)
defer func() {
close(done)
_ = userConn.Close()
_ = srvConn.Close()
// 关闭parser
parser.Close()
// 关闭录像
replayRecorder.End()
s.postBridge()
}()
go s.recordCommand(parser.cmdRecordChan)
go s.LoopReadFromSrv(done, srvConn, srvInChan)
go s.LoopReadFromUser(done, userConn, userInChan)
winCh := userConn.WinCh()
maxIdleTime := s.MaxIdleTime * time.Minute
lastActiveTime := time.Now()
tick := time.NewTicker(30 * time.Second)
defer tick.Stop()
for {
select {
// 检测是否超过最大空闲时间
case <-tick.C:
now := time.Now()
outTime := lastActiveTime.Add(maxIdleTime)
if !now.After(outTime) {
continue
}
msg := fmt.Sprintf(i18n.T("Database connect idle more than %d minutes, disconnect"), s.MaxIdleTime)
logger.Infof("DB Session idle more than %d minutes, disconnect: %s", s.MaxIdleTime, s.ID)
msg = utils.WrapperWarn(msg)
utils.IgnoreErrWriteString(userConn, "\n\r"+msg)
return
// 手动结束
case <-s.ctx.Done():
msg := i18n.T("Database connection terminated by administrator")
msg = utils.WrapperWarn(msg)
logger.Infof("DBSession %s: %s", s.ID, msg)
utils.IgnoreErrWriteString(userConn, "\n\r"+msg)
return
// 监控窗口大小变化
case win, ok := <-winCh:
if !ok {
return
}
_ = srvConn.SetWinSize(win.Height, win.Width)
logger.Debugf("Window server change: %d*%d", win.Height, win.Width)
// 经过parse处理的server数据,发给user
case p, ok := <-srvOutChan:
if !ok {
return
}
nw, _ := userConn.Write(p)
replayRecorder.Record(p[:nw])
// 经过parse处理的user数据,发给server
case p, ok := <-userOutChan:
if !ok {
return
}
_, err = srvConn.Write(p)
}
lastActiveTime = time.Now()
}
}
func (s *DBSwitchSession) MapData() map[string]interface{} {
var dataEnd interface{}
if s.DateEnd != "" {
dataEnd = s.DateEnd
}
return map[string]interface{}{
"id": s.ID,
"user": fmt.Sprintf("%s (%s)", s.p.User.Name, s.p.User.Username),
"asset": s.p.Database.Name,
"org_id": s.p.Database.OrgID,
"login_from": s.p.UserConn.LoginFrom(),
"system_user": s.p.SystemUser.Username,
"protocol": s.p.SystemUser.Protocol,
"remote_addr": s.p.UserConn.RemoteAddr(),
"is_finished": s.finished,
"date_start": s.DateStart,
"date_end": dataEnd,
"user_id": s.p.User.ID,
"asset_id": s.p.Database.ID,
"system_user_id": s.p.SystemUser.ID,
}
}
func (s *DBSwitchSession) LoopReadFromUser(done chan struct{}, userConn UserConnection, inChan chan<- []byte) {
defer logger.Infof("DB Session %s: read from user done", s.ID)
s.LoopRead(done, userConn, inChan)
}
func (s *DBSwitchSession) LoopReadFromSrv(done chan struct{}, srvConn srvconn.ServerConnection, inChan chan<- []byte) {
defer logger.Infof("DB Session %s: read from srv done", s.ID)
s.LoopRead(done, srvConn, inChan)
}
func (s *DBSwitchSession) LoopRead(done chan struct{}, read io.Reader, inChan chan<- []byte) {
loop:
for {
buf := make([]byte, 1024)
nr, err := read.Read(buf)
if nr > 0 {
select {
case <-done:
logger.Debug("DB session reader loop break done.")
break loop
case inChan <- buf[:nr]:
}
}
if err != nil {
break
}
}
close(inChan)
}
......@@ -116,7 +116,10 @@ func (p *ProxyServer) getSSHConn() (srvConn *srvconn.ServerSSHConnection, err er
func (p *ProxyServer) getTelnetConn() (srvConn *srvconn.ServerTelnetConnection, err error) {
conf := config.GetConf()
cusString := conf.TelnetRegex
pattern, _ := regexp.Compile(cusString)
pattern, err := regexp.Compile(cusString)
if err != nil {
logger.Errorf("telnet custom regex %s compile err: %s", cusString, err)
}
srvConn = &srvconn.ServerTelnetConnection{
User: p.User,
Asset: p.Asset,
......
......@@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch"
"github.com/elastic/go-elasticsearch/v6"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
......
......@@ -28,9 +28,10 @@ func (s S3ReplayStorage) Upload(gZipFilePath, target string) (err error) {
}
defer file.Close()
s3Config := &aws.Config{
Credentials: credentials.NewStaticCredentials(s.AccessKey, s.SecretKey, ""),
Endpoint: aws.String(s.Endpoint),
Region: aws.String(s.Region),
Credentials: credentials.NewStaticCredentials(s.AccessKey, s.SecretKey, ""),
Endpoint: aws.String(s.Endpoint),
Region: aws.String(s.Region),
S3ForcePathStyle: aws.Bool(true),
}
sess := session.Must(session.NewSession(s3Config))
......
......@@ -12,9 +12,14 @@ import (
"github.com/jumpserver/koko/pkg/utils"
)
var sessionMap = make(map[string]*SwitchSession)
var sessionMap = make(map[string]Session)
var lock = new(sync.RWMutex)
type Session interface {
SessionID() string
Terminate()
}
func HandleSessionTask(task model.TerminalTask) {
switch task.Name {
case "kill_session":
......@@ -50,20 +55,23 @@ func RemoveSession(sw *SwitchSession) {
lock.Lock()
defer lock.Unlock()
delete(sessionMap, sw.ID)
finishSession(sw)
data := sw.MapData()
finishSession(data)
logger.Infof("Session %s has finished", sw.ID)
}
func AddSession(sw *SwitchSession) {
func AddSession(sw Session) {
lock.Lock()
defer lock.Unlock()
sessionMap[sw.ID] = sw
sessionMap[sw.SessionID()] = sw
}
func CreateSession(p *ProxyServer) (sw *SwitchSession, err error) {
// 创建Session
sw = NewSwitchSession(p)
// Post到Api端
ok := postSession(sw)
data := sw.MapData()
ok := postSession(data)
msg := i18n.T("Connect with api server failed")
if !ok {
msg = utils.WrapperWarn(msg)
......@@ -84,8 +92,7 @@ func CreateSession(p *ProxyServer) (sw *SwitchSession, err error) {
return
}
func postSession(s *SwitchSession) bool {
data := s.MapData()
func postSession(data map[string]interface{}) bool {
for i := 0; i < 5; i++ {
if service.CreateSession(data) {
return true
......@@ -95,8 +102,33 @@ func postSession(s *SwitchSession) bool {
return false
}
func finishSession(s *SwitchSession) {
data := s.MapData()
func finishSession(data map[string]interface{}) {
service.FinishSession(data)
logger.Debugf("Session %s has finished", s.ID)
}
func CreateDBSession(p *DBProxyServer) (sw *DBSwitchSession, err error) {
// 创建Session
sw = &DBSwitchSession{
p: p,
}
sw.Initial()
data := sw.MapData()
ok := postSession(data)
msg := i18n.T("Create database session failed")
if !ok {
msg = utils.WrapperWarn(msg)
utils.IgnoreErrWriteString(p.UserConn, msg)
logger.Error(msg)
return sw, errors.New("create database session failed")
}
AddSession(sw)
return
}
func RemoveDBSession(sw *DBSwitchSession) {
lock.Lock()
defer lock.Unlock()
delete(sessionMap, sw.ID)
finishSession(sw.MapData())
logger.Infof("DB Session %s has finished", sw.ID)
}
......@@ -55,6 +55,11 @@ func (s *SwitchSession) Terminate() {
default:
}
s.cancel()
logger.Infof("Session %s: receive terminate from admin", s.ID)
}
func (s *SwitchSession) SessionID() string {
return s.ID
}
func (s *SwitchSession) recordCommand(cmdRecordChan chan [2]string) {
......@@ -175,6 +180,7 @@ func (s *SwitchSession) Bridge(userConn UserConnection, srvConn srvconn.ServerCo
case <-s.ctx.Done():
msg := i18n.T("Terminated by administrator")
msg = utils.WrapperWarn(msg)
logger.Infof("Session %s: %s", s.ID, msg)
utils.IgnoreErrWriteString(userConn, "\n\r"+msg)
return
// 监控窗口大小变化
......@@ -210,17 +216,20 @@ func (s *SwitchSession) MapData() map[string]interface{} {
dataEnd = s.DateEnd
}
return map[string]interface{}{
"id": s.ID,
"user": fmt.Sprintf("%s (%s)", s.p.User.Name, s.p.User.Username),
"asset": s.p.Asset.Hostname,
"org_id": s.p.Asset.OrgID,
"login_from": s.p.UserConn.LoginFrom(),
"system_user": s.p.SystemUser.Username,
"protocol": s.p.SystemUser.Protocol,
"remote_addr": s.p.UserConn.RemoteAddr(),
"is_finished": s.finished,
"date_start": s.DateStart,
"date_end": dataEnd,
"id": s.ID,
"user": fmt.Sprintf("%s (%s)", s.p.User.Name, s.p.User.Username),
"asset": s.p.Asset.Hostname,
"org_id": s.p.Asset.OrgID,
"login_from": s.p.UserConn.LoginFrom(),
"system_user": s.p.SystemUser.Username,
"protocol": s.p.SystemUser.Protocol,
"remote_addr": s.p.UserConn.RemoteAddr(),
"is_finished": s.finished,
"date_start": s.DateStart,
"date_end": dataEnd,
"user_id": s.p.User.ID,
"asset_id": s.p.Asset.ID,
"system_user_id": s.p.SystemUser.ID,
}
}
......
......@@ -27,42 +27,90 @@ func NewReplayStorage() ReplayStorage {
}
switch tp {
case "azure":
endpointSuffix := cf["ENDPOINT_SUFFIX"].(string)
var accountName string
var accountKey string
var containerName string
var endpointSuffix string
if value, ok := cf["ENDPOINT_SUFFIX"].(string); ok {
endpointSuffix = value
}
if value, ok := cf["ACCOUNT_NAME"].(string); ok {
accountName = value
}
if value, ok := cf["ACCOUNT_KEY"].(string); ok {
accountKey = value
}
if value, ok := cf["CONTAINER_NAME"].(string); ok {
containerName = value
}
if endpointSuffix == "" {
endpointSuffix = "core.chinacloudapi.cn"
}
return storage.AzureReplayStorage{
AccountName: cf["ACCOUNT_NAME"].(string),
AccountKey: cf["ACCOUNT_KEY"].(string),
ContainerName: cf["CONTAINER_NAME"].(string),
AccountName: accountName,
AccountKey: accountKey,
ContainerName: containerName,
EndpointSuffix: endpointSuffix,
}
case "oss":
var endpoint string
var bucket string
var accessKey string
var secretKey string
if value, ok := cf["ENDPOINT"].(string); ok {
endpoint = value
}
if value, ok := cf["BUCKET"].(string); ok {
bucket = value
}
if value, ok := cf["ACCESS_KEY"].(string); ok {
accessKey = value
}
if value, ok := cf["SECRET_KEY"].(string); ok {
secretKey = value
}
return storage.OSSReplayStorage{
Endpoint: cf["ENDPOINT"].(string),
Bucket: cf["BUCKET"].(string),
AccessKey: cf["ACCESS_KEY"].(string),
SecretKey: cf["SECRET_KEY"].(string),
Endpoint: endpoint,
Bucket: bucket,
AccessKey: accessKey,
SecretKey: secretKey,
}
case "s3":
var region string
var endpoint string
bucket := cf["BUCKET"].(string)
endpoint = cf["ENDPOINT"].(string)
var bucket string
var accessKey string
var secretKey string
if value, ok := cf["BUCKET"].(string); ok {
bucket = value
}
if value, ok := cf["ENDPOINT"].(string); ok {
endpoint = value
}
if value, ok := cf["REGION"].(string); ok {
region = value
}
if value, ok := cf["ACCESS_KEY"].(string); ok {
accessKey = value
}
if value, ok := cf["SECRET_KEY"].(string); ok {
secretKey = value
}
if region == "" && endpoint != "" {
endpointArray := strings.Split(endpoint, ".")
if len(endpointArray) >= 2 {
region = endpointArray[1]
}
}
if bucket == "" {
bucket = "jumpserver"
}
if cf["REGION"] != nil {
region = cf["REGION"].(string)
} else {
region = strings.Split(endpoint, ".")[1]
}
return storage.S3ReplayStorage{
Bucket: bucket,
Region: region,
AccessKey: cf["ACCESS_KEY"].(string),
SecretKey: cf["SECRET_KEY"].(string),
AccessKey: accessKey,
SecretKey: secretKey,
Endpoint: endpoint,
}
default:
......
package service
import (
"fmt"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
)
func GetUserDatabases(uid string) (res []model.Database) {
Url := fmt.Sprintf(DatabaseAPPURL, uid)
_, err := authClient.Get(Url, &res)
if err != nil {
logger.Errorf("Get User databases err: %s", err)
}
return
}
func GetUserDatabaseSystemUsers(userID, assetID string) (sysUsers []model.SystemUser) {
Url := fmt.Sprintf(UserDatabaseSystemUsersURL, userID, assetID)
_, err := authClient.Get(Url, &sysUsers)
if err != nil {
logger.Error("Get user asset system users error: ", err)
}
return
}
func GetSystemUserDatabaseAuthInfo(systemUserID string) (info model.SystemUserAuthInfo) {
Url := fmt.Sprintf(SystemUserAuthURL, systemUserID)
_, err := authClient.Get(Url, &info)
if err != nil {
logger.Errorf("Get system user %s auth info failed", systemUserID)
}
return
}
func GetDatabase(dbID string) (res model.Database) {
Url := fmt.Sprintf(DatabaseDetailURL, dbID)
_, err := authClient.Get(Url, &res)
if err != nil {
logger.Errorf("Get User databases err: %s", err)
}
return
}
\ No newline at end of file
......@@ -16,7 +16,7 @@ func GetUserAssets(userID string, pageSize, offset int, searches ...string) (res
paramsArray := make([]map[string]string, 0, len(searches)+2)
for i := 0; i < len(searches); i++ {
paramsArray = append(paramsArray, map[string]string{
"search": url.QueryEscape(searches[i]),
"search": searches[i],
})
}
params := map[string]string{
......@@ -165,3 +165,30 @@ func ValidateUserAssetPermission(userID, assetID, systemUserID, action string) b
return res.Msg
}
func GetUserNodeTreeWithAsset(userID, nodeID, cachePolicy string) (nodeTrees model.NodeTreeList) {
if cachePolicy == "" {
cachePolicy = "1"
}
payload := map[string]string{"cache_policy": cachePolicy}
if nodeID != "" {
payload["id"] = nodeID
}
Url := fmt.Sprintf(NodeTreeWithAssetURL, userID)
_, err := authClient.Get(Url, &nodeTrees, payload)
if err != nil {
logger.Error("Get user node tree error: ", err)
}
return
}
func SearchPermAsset(uid, key string) (res model.NodeTreeList, err error) {
Url := fmt.Sprintf(UserAssetsTreeURL, uid)
payload := map[string]string{"search": key}
_, err = authClient.Get(Url, &res, payload)
if err != nil {
logger.Error("Get user node tree error: ", err)
}
return
}
\ No newline at end of file
package service
const (
UserAuthURL = "/api/v1/authentication/auth/" // post 验证用户登陆
UserProfileURL = "/api/v1/users/profile/" // 获取当前用户的基本信息
UserListURL = "/api/v1/users/users/" // 用户列表地址
UserDetailURL = "/api/v1/users/users/%s/" // 获取用户信息
UserAuthOTPURL = "/api/v1/authentication/otp/auth/" // 验证OTP
TokenAssetURL = "/api/v1/authentication/connection-token/?token=%s" // Token name
SystemUserAssetAuthURL = "/api/v1/assets/system-users/%s/assets/%s/auth-info/" // 该系统用户对某资产的授权
......@@ -41,6 +39,18 @@ const (
// 1.5.5
const (
UserTokenAuthURL = "/api/v1/authentication/tokens/" // 用户登录验证
UserTokenAuthURL = "/api/v1/authentication/tokens/" // 用户登录验证
UserConfirmAuthURL = "/api/v1/authentication/login-confirm-ticket/status/"
NodeTreeWithAssetURL = "/api/v1/perms/users/%s/nodes/children-with-assets/tree/" // 资产树
DatabaseAPPURL = "/api/v1/perms/users/%s/database-apps/" //数据库app
UserDatabaseSystemUsersURL = "/api/v1/perms/users/%s/database-apps/%s/system-users/"
SystemUserAuthURL = "/api/v1/assets/system-users/%s/auth-info/"
UserAssetsTreeURL = "/api/v1/perms/users/%s/assets/tree/"
DatabaseDetailURL = "/api/v1/applications/database-apps/%s/"
)
......@@ -29,6 +29,20 @@ var (
"arcfour256", "arcfour128", "arcfour",
"aes128-cbc",
"3des-cbc"}
supportedKexAlgos = []string{
"diffie-hellman-group1-sha1",
"diffie-hellman-group14-sha1", "ecdh-sha2-nistp256", "ecdh-sha2-nistp521",
"ecdh-sha2-nistp384", "curve25519-sha256@libssh.org"}
supportedHostKeyAlgos = []string{
"ssh-rsa-cert-v01@openssh.com", "ssh-dss-cert-v01@openssh.com", "ecdsa-sha2-nistp256-cert-v01@openssh.com",
"ecdsa-sha2-nistp384-cert-v01@openssh.com", "ecdsa-sha2-nistp521-cert-v01@openssh.com",
"ssh-ed25519-cert-v01@openssh.com",
"ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521",
"ssh-rsa", "ssh-dss",
"ssh-ed25519",
}
)
type SSHClient struct {
......@@ -159,11 +173,12 @@ func (sc *SSHClientConfig) Config() (config *gossh.ClientConfig, err error) {
}
}
config = &gossh.ClientConfig{
User: sc.User,
Auth: authMethods,
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
Config: gossh.Config{Ciphers: supportedCiphers},
Timeout: sc.Timeout,
User: sc.User,
Auth: authMethods,
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
Config: gossh.Config{Ciphers: supportedCiphers, KeyExchanges: supportedKexAlgos},
Timeout: sc.Timeout,
HostKeyAlgorithms: supportedHostKeyAlgos,
}
return config, nil
}
......
package srvconn
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"strconv"
"sync"
"syscall"
"time"
"github.com/creack/pty"
"github.com/jumpserver/koko/pkg/logger"
)
const (
mysqlPrompt = "Enter password: "
)
func NewMysqlServer(ops ...SqlOption) *ServerMysqlConnection {
args := &SqlOptions{
Username: os.Getenv("USER"),
Password: os.Getenv("PASSWORD"),
Host: "127.0.0.1",
Port: 3306,
DBName: "",
}
for _, setter := range ops {
setter(args)
}
return &ServerMysqlConnection{options: args, onceClose: new(sync.Once)}
}
type ServerMysqlConnection struct {
options *SqlOptions
ptyFD *os.File
onceClose *sync.Once
cmd *exec.Cmd
}
func (dbconn *ServerMysqlConnection) Connect() (err error) {
dbconn.cmd = exec.Command("mysql", dbconn.options.CommandArgs()...)
nobody, err := user.Lookup("nobody")
if err != nil {
logger.Errorf("lookup nobody user err: %s", err)
return errors.New("nobody user does not exist")
}
dbconn.cmd.SysProcAttr = &syscall.SysProcAttr{}
uid, _ := strconv.Atoi(nobody.Uid)
gid, _ := strconv.Atoi(nobody.Gid)
dbconn.cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}
dbconn.ptyFD, err = pty.Start(dbconn.cmd)
if err != nil {
logger.Errorf("pty start err: %s", err)
return fmt.Errorf("start local pty err: %s", err)
}
prompt := [len(mysqlPrompt)]byte{}
nr, err := dbconn.ptyFD.Read(prompt[:])
if err != nil {
_ = dbconn.ptyFD.Close()
_ = dbconn.cmd.Process.Kill()
logger.Errorf("read mysql pty local fd err: %s", err)
return fmt.Errorf("mysql conn err: %s", err)
}
if !bytes.Equal(prompt[:nr], []byte(mysqlPrompt)) {
_ = dbconn.cmd.Process.Kill()
_ = dbconn.ptyFD.Close()
logger.Errorf("mysql login prompt characters did not match: %s", prompt[:nr])
return errors.New("failed login mysql")
}
// 输入密码, 登录mysql
_, err = dbconn.ptyFD.Write([]byte(dbconn.options.Password + "\r\n"))
if err != nil {
_ = dbconn.ptyFD.Close()
_ = dbconn.cmd.Process.Kill()
logger.Errorf("mysql local pty write err: %s", err)
return fmt.Errorf("mysql conn err: %s", err)
}
logger.Infof("Connect mysql database %s success ", dbconn.options.Host)
return
}
func (dbconn *ServerMysqlConnection) Read(p []byte) (int, error) {
if dbconn.ptyFD == nil {
return 0, fmt.Errorf("not connect init")
}
return dbconn.ptyFD.Read(p)
}
func (dbconn *ServerMysqlConnection) Write(p []byte) (int, error) {
if dbconn.ptyFD == nil {
return 0, fmt.Errorf("not connect init")
}
return dbconn.ptyFD.Write(p)
}
func (dbconn *ServerMysqlConnection) SetWinSize(w, h int) error {
if dbconn.ptyFD == nil {
return fmt.Errorf("not connect init")
}
win := pty.Winsize{
Rows: uint16(h),
Cols: uint16(w),
}
return pty.Setsize(dbconn.ptyFD, &win)
}
func (dbconn *ServerMysqlConnection) Close() (err error) {
dbconn.onceClose.Do(func() {
if dbconn.ptyFD == nil {
return
}
_ = dbconn.ptyFD.Close()
err = dbconn.cmd.Process.Kill()
})
return
}
func (dbconn *ServerMysqlConnection) Timeout() time.Duration {
return time.Duration(10) * time.Second
}
func (dbconn *ServerMysqlConnection) Protocol() string {
return "mysql"
}
type SqlOptions struct {
Username string
Password string
DBName string
Host string
Port int
}
func (opts *SqlOptions) CommandArgs() []string {
return []string{
fmt.Sprintf("--user=%s", opts.Username),
fmt.Sprintf("--host=%s", opts.Host),
fmt.Sprintf("--port=%d", opts.Port),
"--password",
opts.DBName,
}
}
type SqlOption func(*SqlOptions)
func SqlUsername(username string) SqlOption {
return func(args *SqlOptions) {
args.Username = username
}
}
func SqlPassword(password string) SqlOption {
return func(args *SqlOptions) {
args.Password = password
}
}
func SqlDBName(dbName string) SqlOption {
return func(args *SqlOptions) {
args.DBName = dbName
}
}
func SqlHost(host string) SqlOption {
return func(args *SqlOptions) {
args.Host = host
}
}
func SqlPort(port int) SqlOption {
return func(args *SqlOptions) {
args.Port = port
}
}
package srvconn
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"github.com/pkg/sftp"
"github.com/jumpserver/koko/pkg/common"
"github.com/jumpserver/koko/pkg/config"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/service"
)
func NewUserSFTP(user *model.User, addr string, assets ...model.Asset) *UserSftp {
u := UserSftp{
User: user, Addr: addr,
}
u.initial(assets)
return &u
}
type UserSftp struct {
type UserSftpConn struct {
User *model.User
Addr string
Dirs map[string]os.FileInfo
RootPath string
ShowHidden bool
ReuseConnection bool
Overtime time.Duration
hosts map[string]*HostnameDir // key hostname or hostname.orgName
sftpClients map[string]*SftpConn // key %s@%s suName hostName
modeTime time.Time
logChan chan *model.FTPLog
LogChan chan *model.FTPLog
}
closed chan struct{}
func (u *UserSftp) initial(assets []model.Asset) {
conf := config.GetConf()
u.RootPath = conf.SftpRoot
u.ShowHidden = conf.ShowHiddenFile
u.ReuseConnection = conf.ReuseConnection
u.Overtime = conf.SSHTimeout * time.Second
u.hosts = make(map[string]*HostnameDir)
u.sftpClients = make(map[string]*SftpConn)
u.LogChan = make(chan *model.FTPLog, 10)
for i := 0; i < len(assets); i++ {
if !assets[i].IsSupportProtocol("ssh") {
continue
}
key := assets[i].Hostname
if assets[i].OrgID != "" {
key = fmt.Sprintf("%s.%s", assets[i].Hostname, assets[i].OrgName)
}
u.hosts[key] = NewHostnameDir(&assets[i])
}
go u.LoopPushFTPLog()
searchDir *SearchResultDir
}
func (u *UserSftp) ReadDir(path string) (res []os.FileInfo, err error) {
req := u.ParsePath(path)
if req.host == "" {
return u.RootDirInfo()
}
host, ok := u.hosts[req.host]
if !ok {
return res, sftp.ErrSshFxNoSuchFile
func (u *UserSftpConn) ReadDir(path string) (res []os.FileInfo, err error) {
fi, restPath := u.ParsePath(path)
if rootDir, ok := fi.(*UserSftpConn); ok {
return rootDir.List()
}
if req.su == "" {
for _, su := range host.GetSystemUsers() {
res = append(res, NewFakeFile(su.Name, true))
}
return
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return res, sftp.ErrSshFxNoSuchFile
if nodeDir, ok := fi.(*NodeDir); ok {
return nodeDir.List()
}
if !u.validatePermission(su, model.ConnectAction) {
return res, sftp.ErrSshFxPermissionDenied
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.ReadDir(restPath)
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
return res, sftp.ErrSshFxPermissionDenied
}
logger.Debug("inter sftp read dir real path: ", realPath)
res, err = conn.client.ReadDir(realPath)
if !u.ShowHidden {
noHiddenFiles := make([]os.FileInfo, 0, len(res))
for i := 0; i < len(res); i++ {
if !strings.HasPrefix(res[i].Name(), ".") {
noHiddenFiles = append(noHiddenFiles, res[i])
}
}
return noHiddenFiles, err
}
return res, err
return nil, sftp.ErrSSHFxNoSuchFile
}
func (u *UserSftp) Stat(path string) (res os.FileInfo, err error) {
req := u.ParsePath(path)
if req.host == "" {
return u.Info()
}
host, ok := u.hosts[req.host]
if !ok {
return res, sftp.ErrSshFxNoSuchFile
func (u *UserSftpConn) Stat(path string) (res os.FileInfo, err error) {
fi, restPath := u.ParsePath(path)
if rootDir, ok := fi.(*UserSftpConn); ok {
return rootDir, nil
}
if req.su == "" {
res = NewFakeFile(req.host, true)
return
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return res, sftp.ErrSshFxNoSuchFile
if nodeDir, ok := fi.(*NodeDir); ok {
return nodeDir, nil
}
if !u.validatePermission(su, model.ConnectAction) {
return res, sftp.ErrSshFxPermissionDenied
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.Stat(restPath)
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
return res, sftp.ErrSshFxPermissionDenied
}
return conn.client.Stat(realPath)
return nil, sftp.ErrSSHFxNoSuchFile
}
func (u *UserSftp) ReadLink(path string) (res string, err error) {
req := u.ParsePath(path)
if req.host == "" {
return res, sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req.host]
if !ok {
return res, sftp.ErrSshFxPermissionDenied
}
if req.su == "" {
return res, sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return res, sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.ConnectAction) {
return res, sftp.ErrSshFxPermissionDenied
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
return res, sftp.ErrSshFxPermissionDenied
func (u *UserSftpConn) ReadLink(path string) (name string, err error) {
fi, restPath := u.ParsePath(path)
if _, ok := fi.(*UserSftpConn); ok && restPath == "" {
return "", sftp.ErrSshFxOpUnsupported
}
return conn.client.ReadLink(realPath)
}
func (u *UserSftp) RemoveDirectory(path string) error {
req := u.ParsePath(path)
if req.host == "" {
return sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req.host]
if !ok {
return sftp.ErrSshFxPermissionDenied
if _, ok := fi.(*NodeDir); ok {
return "", sftp.ErrSshFxOpUnsupported
}
if req.su == "" {
return sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return sftp.ErrSshFxNoSuchFile
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.ReadLink(restPath)
}
if !u.validatePermission(su, model.UploadAction) {
return sftp.ErrSshFxPermissionDenied
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
return sftp.ErrSshFxPermissionDenied
}
err := u.removeDirectoryAll(conn.client, realPath)
filename := realPath
isSuccess := false
operate := model.OperateRemoveDir
if err == nil {
isSuccess = true
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return err
return "", sftp.ErrSshFxOpUnsupported
}
func (u *UserSftp) removeDirectoryAll(conn *sftp.Client, path string) error {
var err error
var files []os.FileInfo
files, err = conn.ReadDir(path)
if err != nil {
return err
}
for _, item := range files {
realPath := filepath.Join(path, item.Name())
if item.IsDir() {
err = u.removeDirectoryAll(conn, realPath)
if err != nil {
return err
func (u *UserSftpConn) Rename(oldNamePath, newNamePath string) (err error) {
oldFi, oldRestPath := u.ParsePath(oldNamePath)
newFi, newRestPath := u.ParsePath(newNamePath)
if oldAssetDir, ok := oldFi.(*AssetDir); ok {
if newAssetDir, newOk := newFi.(*AssetDir); newOk {
if oldAssetDir == newAssetDir {
return oldAssetDir.Rename(oldRestPath, newRestPath)
}
continue
}
err = conn.Remove(realPath)
if err != nil {
return err
}
}
return conn.RemoveDirectory(path)
return sftp.ErrSshFxOpUnsupported
}
func (u *UserSftp) Remove(path string) error {
req := u.ParsePath(path)
if req.host == "" {
return sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req.host]
if !ok {
return sftp.ErrSshFxPermissionDenied
}
if req.su == "" {
return sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.UploadAction) {
func (u *UserSftpConn) RemoveDirectory(path string) (err error) {
fi, restPath := u.ParsePath(path)
if _, ok := fi.(*UserSftpConn); ok && restPath == "" {
return sftp.ErrSshFxPermissionDenied
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
if _, ok := fi.(*NodeDir); ok {
return sftp.ErrSshFxPermissionDenied
}
logger.Debug("remove file path", realPath)
err := conn.client.Remove(realPath)
filename := realPath
isSuccess := false
operate := model.OperateDelete
if err == nil {
isSuccess = true
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.RemoveDirectory(restPath)
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return err
return sftp.ErrSshFxPermissionDenied
}
func (u *UserSftp) MkdirAll(path string) error {
req := u.ParsePath(path)
if req.host == "" {
return sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req.host]
if !ok {
return sftp.ErrSshFxPermissionDenied
}
if req.su == "" {
return sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.UploadAction) {
func (u *UserSftpConn) Remove(path string) (err error) {
fi, restPath := u.ParsePath(path)
if _, ok := fi.(*UserSftpConn); ok && restPath == "" {
return sftp.ErrSshFxPermissionDenied
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
if _, ok := fi.(*NodeDir); ok {
return sftp.ErrSshFxPermissionDenied
}
err := conn.client.MkdirAll(realPath)
filename := realPath
isSuccess := false
operate := model.OperateMkdir
if err == nil {
isSuccess = true
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.Remove(restPath)
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return err
return sftp.ErrSshFxPermissionDenied
}
func (u *UserSftp) Rename(oldNamePath, newNamePath string) error {
req1 := u.ParsePath(oldNamePath)
req2 := u.ParsePath(newNamePath)
if req1.host == "" || req2.host == "" || req1.su == "" || req2.su == "" {
return sftp.ErrSshFxPermissionDenied
} else if req1.host != req2.host || req1.su != req2.su {
func (u *UserSftpConn) MkdirAll(path string) (err error) {
fi, restPath := u.ParsePath(path)
if _, ok := fi.(*UserSftpConn); ok && restPath == "" {
return sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req1.host]
if !ok {
return sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req1.su]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.UploadAction) {
return sftp.ErrSshFxPermissionDenied
}
conn1, oldRealPath := u.GetSFTPAndRealPath(req1)
conn2, newRealPath := u.GetSFTPAndRealPath(req2)
if conn1 != conn2 {
return sftp.ErrSshFxOpUnsupported
}
err := conn1.client.Rename(oldRealPath, newRealPath)
filename := fmt.Sprintf("%s=>%s", oldRealPath, newRealPath)
isSuccess := false
operate := model.OperateRename
if err == nil {
isSuccess = true
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return err
}
func (u *UserSftp) Symlink(oldNamePath, newNamePath string) error {
req1 := u.ParsePath(oldNamePath)
req2 := u.ParsePath(newNamePath)
if req1.host == "" || req2.host == "" || req1.su == "" || req2.su == "" {
return sftp.ErrSshFxPermissionDenied
} else if req1.host != req2.host || req1.su != req2.su {
return sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req1.host]
if !ok {
return sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req1.su]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.UploadAction) {
if _, ok := fi.(*NodeDir); ok {
return sftp.ErrSshFxPermissionDenied
}
conn1, oldRealPath := u.GetSFTPAndRealPath(req1)
conn2, newRealPath := u.GetSFTPAndRealPath(req2)
if conn1 != conn2 {
return sftp.ErrSshFxOpUnsupported
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.MkdirAll(restPath)
}
err := conn1.client.Symlink(oldRealPath, newRealPath)
return sftp.ErrSshFxPermissionDenied
}
filename := fmt.Sprintf("%s=>%s", oldRealPath, newRealPath)
isSuccess := false
operate := model.OperateSymlink
if err == nil {
isSuccess = true
func (u *UserSftpConn) Symlink(oldNamePath, newNamePath string) (err error) {
oldFi, oldRestPath := u.ParsePath(oldNamePath)
newFi, newRestPath := u.ParsePath(newNamePath)
if oldAssetDir, ok := oldFi.(*AssetDir); ok {
if newAssetDir, newOk := newFi.(*AssetDir); newOk {
if oldAssetDir == newAssetDir {
return oldAssetDir.Symlink(oldRestPath, newRestPath)
}
}
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return err
return sftp.ErrSshFxPermissionDenied
}
func (u *UserSftp) Create(path string) (*sftp.File, error) {
req := u.ParsePath(path)
if req.host == "" {
return nil, sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req.host]
if !ok {
return nil, sftp.ErrSshFxPermissionDenied
}
if req.su == "" {
return nil, sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return nil, sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.UploadAction) {
func (u *UserSftpConn) Create(path string) (*sftp.File, error) {
fi, restPath := u.ParsePath(path)
if _, ok := fi.(*UserSftpConn); ok {
return nil, sftp.ErrSshFxPermissionDenied
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
if _, ok := fi.(*NodeDir); ok {
return nil, sftp.ErrSshFxPermissionDenied
}
logger.Debug("create path:", realPath)
sf, err := conn.client.Create(realPath)
filename := realPath
isSuccess := false
operate := model.OperateUpload
if err == nil {
isSuccess = true
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.Create(restPath)
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return sf, err
return nil, sftp.ErrSshFxPermissionDenied
}
func (u *UserSftp) Open(path string) (*sftp.File, error) {
req := u.ParsePath(path)
if req.host == "" {
func (u *UserSftpConn) Open(path string) (*sftp.File, error) {
fi, restPath := u.ParsePath(path)
if _, ok := fi.(*UserSftpConn); ok {
return nil, sftp.ErrSshFxPermissionDenied
}
host, ok := u.hosts[req.host]
if !ok {
return nil, sftp.ErrSshFxPermissionDenied
}
if req.su == "" {
if _, ok := fi.(*NodeDir); ok {
return nil, sftp.ErrSshFxPermissionDenied
}
host.loadSystemUsers(u.User.ID)
su, ok := host.suMaps[req.su]
if !ok {
return nil, sftp.ErrSshFxNoSuchFile
}
if !u.validatePermission(su, model.DownloadAction) {
return nil, sftp.ErrSshFxPermissionDenied
if assetDir, ok := fi.(*AssetDir); ok {
return assetDir.Open(restPath)
}
conn, realPath := u.GetSFTPAndRealPath(req)
if conn == nil {
return nil, sftp.ErrSshFxPermissionDenied
return nil, sftp.ErrSshFxPermissionDenied
}
func (u *UserSftpConn) Close() {
for _, dir := range u.Dirs {
if nodeDir, ok := dir.(*NodeDir); ok {
nodeDir.close()
continue
}
if assetDir, ok := dir.(*AssetDir); ok {
assetDir.close()
continue
}
}
logger.Debug("Open path:", realPath)
sf, err := conn.client.Open(realPath)
filename := realPath
isSuccess := false
operate := model.OperateDownaload
if err == nil {
isSuccess = true
if u.searchDir != nil{
u.searchDir.close()
}
u.CreateFTPLog(host.asset, su, operate, filename, isSuccess)
return sf, err
close(u.closed)
}
func (u *UserSftpConn) Name() string {
return "/"
}
func (u *UserSftp) Info() (os.FileInfo, error) {
return NewFakeFile("/", true), nil
func (u *UserSftpConn) Size() int64 { return 0 }
func (u *UserSftpConn) Mode() os.FileMode {
return os.ModePerm | os.ModeDir
}
func (u *UserSftp) RootDirInfo() ([]os.FileInfo, error) {
hostDirs := make([]os.FileInfo, 0, len(u.hosts))
for key := range u.hosts {
hostDirs = append(hostDirs, NewFakeFile(key, true))
func (u *UserSftpConn) ModTime() time.Time { return u.modeTime }
func (u *UserSftpConn) IsDir() bool { return true }
func (u *UserSftpConn) Sys() interface{} {
return &syscall.Stat_t{Uid: 0, Gid: 0}
}
func (u *UserSftpConn) List() (res []os.FileInfo, err error) {
for _, item := range u.Dirs {
res = append(res, item)
}
sort.Sort(FileInfoList(hostDirs))
return hostDirs, nil
return
}
func (u *UserSftp) ParsePath(path string) (req requestMessage) {
data := strings.Split(strings.TrimPrefix(path, "/"), "/")
if len(data) == 0 {
func (u *UserSftpConn) ParsePath(path string) (fi os.FileInfo, restPath string) {
path = strings.TrimPrefix(path, "/")
data := strings.Split(path, "/")
if len(data) == 1 && data[0] == "" {
fi = u
return
}
host, pathArray := data[0], data[1:]
req.host = host
if suName, unique := u.HostHasUniqueSu(host); unique {
req.suUnique = true
req.su = suName
var dirs map[string]os.FileInfo
var ok bool
if data[0] == SearchFolderName {
dirs = u.searchDir.subDirs
data = data[1:]
} else {
if len(pathArray) == 0 {
req.su = ""
} else {
req.su, pathArray = pathArray[0], pathArray[1:]
dirs = u.Dirs
}
for i := 0; i < len(data); i++ {
fi, ok = dirs[data[i]]
if !ok {
restPath = strings.Join(data[i+1:], "/")
break
}
if nodeDir, ok := fi.(*NodeDir); ok {
nodeDir.loadNodeAsset(u)
dirs = nodeDir.subDirs
continue
}
if assetDir, ok := fi.(*AssetDir); ok {
assetDir.loadSystemUsers()
restPath = strings.Join(data[i+1:], "/")
break
}
}
req.dpath = strings.Join(pathArray, "/")
return
}
func (u *UserSftp) GetSFTPAndRealPath(req requestMessage) (conn *SftpConn, realPath string) {
if host, ok := u.hosts[req.host]; ok {
if su, ok := host.suMaps[req.su]; ok {
key := fmt.Sprintf("%s@%s", su.Name, req.host)
conn, ok := u.sftpClients[key]
if !ok {
var err error
conn, err = u.GetSftpClient(host.asset, su)
if err != nil {
logger.Info("Get Sftp Client err: ", err.Error())
return nil, ""
func (u *UserSftpConn) initial() {
nodeTrees := service.GetUserNodeTreeWithAsset(u.User.ID, "", "")
if u.Dirs == nil {
u.Dirs = map[string]os.FileInfo{}
}
u.searchDir = &SearchResultDir{
folderName: SearchFolderName,
modeTime: time.Now().UTC(),
subDirs: map[string]os.FileInfo{}}
for _, item := range nodeTrees {
if item.Pid != "" {
continue
}
typeName, ok := item.Meta["type"].(string)
if !ok {
continue
}
body, err := json.Marshal(item.Meta[typeName])
if err != nil {
logger.Errorf("Json Marshal err: %s", err)
continue
}
switch typeName {
case "node":
node, err := model.ConvertMetaToNode(body)
if err != nil {
logger.Errorf("convert to node err: %s", err)
continue
}
nodeDir := NewNodeDir(node)
folderName := nodeDir.folderName
for {
_, ok := u.Dirs[folderName]
if !ok {
break
}
u.sftpClients[key] = conn
folderName = fmt.Sprintf("%s_", folderName)
}
switch strings.ToLower(u.RootPath) {
case "home", "~", "":
realPath = filepath.Join(conn.HomeDirPath, strings.TrimPrefix(req.dpath, "/"))
default:
realPath = filepath.Join(u.RootPath, strings.TrimPrefix(req.dpath, "/"))
if folderName != nodeDir.folderName {
nodeDir.folderName = folderName
}
return conn, realPath
}
}
return
}
func (u *UserSftp) HostHasUniqueSu(hostKey string) (string, bool) {
if host, ok := u.hosts[hostKey]; ok {
host.loadSystemUsers(u.User.ID)
return host.HasUniqueSu()
}
return "", false
}
func (u *UserSftp) validatePermission(su *model.SystemUser, action string) bool {
for _, pemAction := range su.Actions {
if pemAction == action || pemAction == model.AllAction {
return true
u.Dirs[folderName] = &nodeDir
case "asset":
asset, err := model.ConvertMetaToAsset(body)
if err != nil {
logger.Errorf("convert to asset err: %s", err)
continue
}
if !asset.IsSupportProtocol("ssh") {
continue
}
assetDir := NewAssetDir(u.User, asset, u.Addr, u.logChan)
folderName := assetDir.folderName
for {
_, ok := u.Dirs[folderName]
if !ok {
break
}
folderName = fmt.Sprintf("%s_", folderName)
}
if folderName != assetDir.folderName {
assetDir.folderName = folderName
}
u.Dirs[folderName] = &assetDir
}
}
return false
}
func (u *UserSftp) CreateFTPLog(asset *model.Asset, su *model.SystemUser, operate, filename string, isSuccess bool) {
data := model.FTPLog{
User: fmt.Sprintf("%s (%s)", u.User.Name, u.User.Username),
Hostname: asset.Hostname,
OrgID: asset.OrgID,
SystemUser: su.Name,
RemoteAddr: u.Addr,
Operate: operate,
Path: filename,
DataStart: common.CurrentUTCTime(),
IsSuccess: isSuccess,
}
u.LogChan <- &data
}
func (u *UserSftp) LoopPushFTPLog() {
func (u *UserSftpConn) loopPushFTPLog() {
ftpLogList := make([]*model.FTPLog, 0, 1024)
dataChan := make(chan *model.FTPLog)
go u.SendFTPLog(dataChan)
defer close(dataChan)
tick := time.NewTicker(time.Second * 10)
maxRetry := 0
var err error
tick := time.NewTicker(time.Second * 20)
defer tick.Stop()
for {
select {
case <-u.closed:
if len(ftpLogList) == 0 {
return
}
case <-tick.C:
case logData, ok := <-u.LogChan:
if len(ftpLogList) == 0 {
continue
}
case logData, ok := <-u.logChan:
if !ok {
return
}
ftpLogList = append(ftpLogList, logData)
}
if len(ftpLogList) > 0 {
select {
case dataChan <- ftpLogList[len(ftpLogList)-1]:
ftpLogList = ftpLogList[:len(ftpLogList)-1]
default:
}
}
}
}
func (u *UserSftp) SendFTPLog(dataChan <-chan *model.FTPLog) {
for data := range dataChan {
for i := 0; i < 4; i++ {
err := service.PushFTPLog(data)
if err == nil {
break
}
logger.Errorf("Create FTP log err: %s", err.Error())
}
}
}
func (u *UserSftp) GetSftpClient(asset *model.Asset, sysUser *model.SystemUser) (conn *SftpConn, err error) {
var (
sshClient *SSHClient
ok bool
)
if u.ReuseConnection {
key := MakeReuseSSHClientKey(u.User, asset, sysUser)
switch sysUser.Username {
case "":
sshClient, ok = searchSSHClientFromCache(key)
if ok {
sysUser.Username = sshClient.username
}
default:
sshClient, ok = GetClientFromCache(key)
}
if !ok {
sshClient, err = NewClient(u.User, asset, sysUser, u.Overtime, u.ReuseConnection)
if err != nil {
logger.Errorf("Get new SSH client err: %s", err)
return
}
data := ftpLogList[len(ftpLogList)-1]
err = service.PushFTPLog(data)
if err == nil {
ftpLogList = ftpLogList[:len(ftpLogList)-1]
maxRetry = 0
continue
} else {
logger.Infof("Reuse connection for SFTP: %s->%s@%s. SSH client %p current ref: %d",
u.User.Username, sshClient.username, asset.IP, sshClient, sshClient.RefCount())
logger.Errorf("Create FTP log err: %s", err.Error())
}
} else {
sshClient, err = NewClient(u.User, asset, sysUser, u.Overtime, u.ReuseConnection)
if err != nil {
logger.Errorf("Get new SSH client err: %s", err)
return
if maxRetry > 5 {
ftpLogList = ftpLogList[1:]
}
maxRetry++
}
}
sftpClient, err := sftp.NewClient(sshClient.client)
if err != nil {
logger.Errorf("SSH client %p start sftp client session err %s", sshClient, err)
RecycleClient(sshClient)
return nil, err
func (u *UserSftpConn) Search(key string) (res []os.FileInfo, err error) {
if u.searchDir == nil{
logger.Errorf("not found search folder")
return nil, fmt.Errorf("not found")
}
HomeDirPath, err := sftpClient.Getwd()
assetsTree, err := service.SearchPermAsset(u.User.ID, key)
if err != nil {
logger.Errorf("SSH client %p get home dir err %s", sshClient, err)
_ = sftpClient.Close()
RecycleClient(sshClient)
logger.Errorf("search asset err: %s", err)
return nil, err
}
logger.Infof("SSH client %p start sftp client session success", sshClient)
conn = &SftpConn{client: sftpClient, conn: sshClient, HomeDirPath: HomeDirPath}
return conn, err
}
func (u *UserSftp) Close() {
for _, client := range u.sftpClients {
if client == nil {
subDirs := map[string]os.FileInfo{}
for _, item := range assetsTree {
typeName, ok := item.Meta["type"].(string)
if !ok {
continue
}
client.Close()
}
close(u.LogChan)
}
type requestMessage struct {
host string
su string
dpath string
suUnique bool
}
func NewHostnameDir(asset *model.Asset) *HostnameDir {
h := HostnameDir{asset: asset}
return &h
}
type HostnameDir struct {
asset *model.Asset
suMaps map[string]*model.SystemUser
}
func (h *HostnameDir) loadSystemUsers(userID string) {
if h.suMaps == nil {
sus := make(map[string]*model.SystemUser)
SystemUsers := service.GetUserAssetSystemUsers(userID, h.asset.ID)
for i := 0; i < len(SystemUsers); i++ {
if SystemUsers[i].Protocol == "ssh" {
sus[SystemUsers[i].Name] = &SystemUsers[i]
body, err := json.Marshal(item.Meta[typeName])
if err != nil {
logger.Errorf("Search Json Marshal err: %s", err)
continue
}
switch typeName {
case "asset":
asset, err := model.ConvertMetaToAsset(body)
if err != nil {
logger.Errorf("convert to asset err: %s", err)
continue
}
if !asset.IsSupportProtocol("ssh") {
continue
}
assetDir := NewAssetDir(u.User, asset, u.Addr, u.logChan)
folderName := assetDir.folderName
for {
_, ok := subDirs[folderName]
if !ok {
break
}
folderName = fmt.Sprintf("%s_", folderName)
}
if folderName != assetDir.folderName {
assetDir.folderName = folderName
}
subDirs[assetDir.folderName] = &assetDir
}
h.suMaps = sus
}
u.searchDir.SetSubDirs(subDirs)
return u.searchDir.List()
}
func (h *HostnameDir) HasUniqueSu() (string, bool) {
sus := h.GetSystemUsers()
if len(sus) == 1 {
return sus[0].Name, true
func NewUserSftpConn(user *model.User, addr string) *UserSftpConn {
u := UserSftpConn{
User: user,
Addr: addr,
Dirs: map[string]os.FileInfo{},
modeTime: time.Now().UTC(),
logChan: make(chan *model.FTPLog, 1024),
closed: make(chan struct{}),
}
return "", false
}
func (h *HostnameDir) GetSystemUsers() (sus []model.SystemUser) {
sus = make([] model.SystemUser, 0, len(h.suMaps))
for _, item := range h.suMaps {
sus = append(sus, *item)
}
model.SortSystemUserByPriority(sus)
return sus
}
type SftpConn struct {
HomeDirPath string
client *sftp.Client
conn *SSHClient
}
func (s *SftpConn) Close() {
if s.client == nil {
return
}
_ = s.client.Close()
RecycleClient(s.conn)
}
func NewFakeFile(name string, isDir bool) *FakeFileInfo {
return &FakeFileInfo{
name: name,
modtime: time.Now().UTC(),
isDir: isDir,
size: int64(0),
}
}
func NewFakeSymFile(name string) *FakeFileInfo {
return &FakeFileInfo{
name: name,
modtime: time.Now().UTC(),
size: int64(0),
symlink: name,
}
}
type FakeFileInfo struct {
name string
isDir bool
size int64
modtime time.Time
symlink string
u.initial()
go u.loopPushFTPLog()
return &u
}
func (f *FakeFileInfo) Name() string { return f.name }
func (f *FakeFileInfo) Size() int64 { return f.size }
func (f *FakeFileInfo) Mode() os.FileMode {
ret := os.FileMode(0644)
if f.isDir {
ret = os.FileMode(0755) | os.ModeDir
}
if f.symlink != "" {
ret = os.FileMode(0777) | os.ModeSymlink
func NewUserSftpConnWithAssets(user *model.User, addr string, assets ...model.Asset) *UserSftpConn {
u := UserSftpConn{
User: user,
Addr: addr,
Dirs: map[string]os.FileInfo{},
modeTime: time.Now().UTC(),
logChan: make(chan *model.FTPLog, 1024),
closed: make(chan struct{}),
}
for _, asset := range assets {
if asset.IsSupportProtocol("ssh") {
assetDir := NewAssetDir(u.User, asset, u.Addr, u.logChan)
folderName := assetDir.folderName
for {
_, ok := u.Dirs[folderName]
if !ok {
break
}
folderName = fmt.Sprintf("%s_", folderName)
}
if folderName != assetDir.folderName {
assetDir.folderName = folderName
}
u.Dirs[assetDir.folderName] = &assetDir
}
}
return ret
}
func (f *FakeFileInfo) ModTime() time.Time { return f.modtime }
func (f *FakeFileInfo) IsDir() bool { return f.isDir }
func (f *FakeFileInfo) Sys() interface{} {
return &syscall.Stat_t{Uid: 0, Gid: 0}
}
type FileInfoList []os.FileInfo
func (fl FileInfoList) Len() int {
return len(fl)
go u.loopPushFTPLog()
return &u
}
func (fl FileInfoList) Swap(i, j int) { fl[i], fl[j] = fl[j], fl[i] }
func (fl FileInfoList) Less(i, j int) bool { return fl[i].Name() < fl[j].Name() }
package srvconn
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/pkg/sftp"
"github.com/jumpserver/koko/pkg/common"
"github.com/jumpserver/koko/pkg/config"
"github.com/jumpserver/koko/pkg/logger"
"github.com/jumpserver/koko/pkg/model"
"github.com/jumpserver/koko/pkg/service"
)
const (
SearchFolderName = "_Search"
)
type SearchResultDir struct {
subDirs map[string]os.FileInfo
folderName string
modeTime time.Time
}
func (sd *SearchResultDir) Name() string {
return sd.folderName
}
func (sd *SearchResultDir) Size() int64 { return 0 }
func (sd *SearchResultDir) Mode() os.FileMode {
return os.ModePerm | os.ModeDir
}
func (sd *SearchResultDir) ModTime() time.Time { return sd.modeTime }
func (sd *SearchResultDir) IsDir() bool { return true }
func (sd *SearchResultDir) Sys() interface{} {
return &syscall.Stat_t{Uid: 0, Gid: 0}
}
func (sd *SearchResultDir) List() (res []os.FileInfo, err error) {
for _, item := range sd.subDirs {
res = append(res, item)
}
return
}
func (sd *SearchResultDir) SetSubDirs(subDirs map[string]os.FileInfo) {
if sd.subDirs != nil {
for _, dir := range sd.subDirs {
if assetDir, ok := dir.(*AssetDir); ok {
assetDir.close()
}
}
}
sd.subDirs = subDirs
}
func (sd *SearchResultDir) close() {
for _, dir := range sd.subDirs {
if assetDir, ok := dir.(*AssetDir); ok {
assetDir.close()
}
}
}
type NodeDir struct {
node *model.Node
subDirs map[string]os.FileInfo
folderName string
modeTime time.Time
once *sync.Once
}
func (nd *NodeDir) Name() string {
return nd.folderName
}
func (nd *NodeDir) Size() int64 { return 0 }
func (nd *NodeDir) Mode() os.FileMode {
return os.ModePerm | os.ModeDir
}
func (nd *NodeDir) ModTime() time.Time { return nd.modeTime }
func (nd *NodeDir) IsDir() bool { return true }
func (nd *NodeDir) Sys() interface{} {
return &syscall.Stat_t{Uid: 0, Gid: 0}
}
func (nd *NodeDir) List() (res []os.FileInfo, err error) {
for _, item := range nd.subDirs {
res = append(res, item)
}
return
}
func (nd *NodeDir) loadNodeAsset(uSftp *UserSftpConn) {
nd.once.Do(func() {
nodeTrees := service.GetUserNodeTreeWithAsset(uSftp.User.ID, nd.node.ID, "1")
dirs := map[string]os.FileInfo{}
for _, item := range nodeTrees {
typeName, ok := item.Meta["type"].(string)
if !ok {
continue
}
body, err := json.Marshal(item.Meta[typeName])
if err != nil {
continue
}
switch typeName {
case "node":
node, err := model.ConvertMetaToNode(body)
if err != nil {
logger.Errorf("convert node err: %s", err)
continue
}
nodeDir := NewNodeDir(node)
folderName := nodeDir.folderName
for {
_, ok := dirs[folderName]
if !ok {
break
}
folderName = fmt.Sprintf("%s_", folderName)
}
if folderName != nodeDir.folderName {
nodeDir.folderName = folderName
}
dirs[folderName] = &nodeDir
case "asset":
asset, err := model.ConvertMetaToAsset(body)
if err != nil {
logger.Errorf("convert asset err: %s", err)
continue
}
if !asset.IsSupportProtocol("ssh") {
continue
}
assetDir := NewAssetDir(uSftp.User, asset, uSftp.Addr, uSftp.logChan)
folderName := assetDir.folderName
for {
_, ok := dirs[folderName]
if !ok {
break
}
folderName = fmt.Sprintf("%s_", folderName)
}
if folderName != assetDir.folderName {
assetDir.folderName = folderName
}
dirs[folderName] = &assetDir
}
}
nd.subDirs = dirs
})
}
func (nd *NodeDir) close() {
for _, dir := range nd.subDirs {
if nodeDir, ok := dir.(*NodeDir); ok {
nodeDir.close()
continue
}
if assetDir, ok := dir.(*AssetDir); ok {
assetDir.close()
}
}
}
func NewNodeDir(node model.Node) NodeDir {
folderName := node.Value
if strings.Contains(node.Value, "/") {
folderName = strings.ReplaceAll(node.Value, "/", "_")
}
return NodeDir{
node: &node,
folderName: folderName,
subDirs: map[string]os.FileInfo{},
modeTime: time.Now().UTC(),
once: new(sync.Once),
}
}
func NewAssetDir(user *model.User, asset model.Asset, addr string, logChan chan<- *model.FTPLog) AssetDir {
folderName := asset.Hostname
if strings.Contains(folderName, "/") {
folderName = strings.ReplaceAll(folderName, "/", "_")
}
conf := config.GetConf()
return AssetDir{
user: user,
asset: &asset,
folderName: folderName,
modeTime: time.Now().UTC(),
addr: addr,
suMaps: nil,
logChan: logChan,
Overtime: conf.SSHTimeout * time.Second,
RootPath: conf.SftpRoot,
ShowHidden: conf.ShowHiddenFile,
reuse: conf.ReuseConnection,
sftpClients: map[string]*SftpConn{},
}
}
type AssetDir struct {
user *model.User
asset *model.Asset
folderName string
modeTime time.Time
addr string
suMaps map[string]*model.SystemUser
logChan chan<- *model.FTPLog
sftpClients map[string]*SftpConn // systemUser_id
once sync.Once
RootPath string
reuse bool
ShowHidden bool
Overtime time.Duration
}
func (ad *AssetDir) Name() string {
return ad.folderName
}
func (ad *AssetDir) Size() int64 { return 0 }
func (ad *AssetDir) Mode() os.FileMode {
return os.ModePerm | os.ModeDir
}
func (ad *AssetDir) ModTime() time.Time { return ad.modeTime }
func (ad *AssetDir) IsDir() bool { return true }
func (ad *AssetDir) Sys() interface{} {
return &syscall.Stat_t{Uid: 0, Gid: 0}
}
func (ad *AssetDir) loadSystemUsers() {
ad.once.Do(func() {
sus := make(map[string]*model.SystemUser)
SystemUsers := service.GetUserAssetSystemUsers(ad.user.ID, ad.asset.ID)
for i := 0; i < len(SystemUsers); i++ {
if SystemUsers[i].Protocol == "ssh" {
ok := true
folderName := SystemUsers[i].Name
for ok {
if _, ok = sus[folderName]; ok {
folderName = fmt.Sprintf("%s_", folderName)
}
}
sus[folderName] = &SystemUsers[i]
}
}
ad.suMaps = sus
})
}
func (ad *AssetDir) Create(path string) (*sftp.File, error) {
pathData := ad.parsePath(path)
folderName, ok := ad.IsUniqueSu()
if !ok {
if len(pathData) == 1 && pathData[0] == "" {
return nil, sftp.ErrSshFxPermissionDenied
}
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return nil, sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.UploadAction) {
return nil, sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return nil, sftp.ErrSshFxConnectionLost
}
sf, err := con.client.Create(realPath)
filename := realPath
isSuccess := false
operate := model.OperateUpload
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return sf, err
}
func (ad *AssetDir) MkdirAll(path string) (err error) {
pathData := ad.parsePath(path)
folderName, ok := ad.IsUniqueSu()
if !ok {
if len(pathData) == 1 && pathData[0] == "" {
return sftp.ErrSshFxPermissionDenied
}
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.UploadAction) {
return sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return sftp.ErrSshFxConnectionLost
}
err = con.client.MkdirAll(realPath)
filename := realPath
isSuccess := false
operate := model.OperateMkdir
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return
}
func (ad *AssetDir) Open(path string) (*sftp.File, error) {
pathData := ad.parsePath(path)
folderName, ok := ad.IsUniqueSu()
if !ok {
if len(pathData) == 1 && pathData[0] == "" {
return nil, sftp.ErrSshFxPermissionDenied
}
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return nil, sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.DownloadAction) {
return nil, sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return nil, sftp.ErrSshFxConnectionLost
}
sf, err := con.client.Open(realPath)
filename := realPath
isSuccess := false
operate := model.OperateDownaload
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return sf, err
}
func (ad *AssetDir) ReadDir(path string) (res []os.FileInfo, err error) {
pathData := ad.parsePath(path)
folderName, ok := ad.IsUniqueSu()
if !ok {
if len(pathData) == 1 && pathData[0] == "" {
for folderName := range ad.suMaps {
res = append(res, NewFakeFile(folderName, true))
}
return
}
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return nil, sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.ConnectAction) {
return res, sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return nil, sftp.ErrSshFxConnectionLost
}
res, err = con.client.ReadDir(realPath)
if !ad.ShowHidden {
noHiddenFiles := make([]os.FileInfo, 0, len(res))
for i := 0; i < len(res); i++ {
if !strings.HasPrefix(res[i].Name(), ".") {
noHiddenFiles = append(noHiddenFiles, res[i])
}
}
return noHiddenFiles, err
}
return
}
func (ad *AssetDir) ReadLink(path string) (res string, err error) {
pathData := ad.parsePath(path)
if len(pathData) == 1 && pathData[0] == "" {
return "", sftp.ErrSshFxOpUnsupported
}
folderName, ok := ad.IsUniqueSu()
if !ok {
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return "", sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.ConnectAction) {
return res, sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return "", sftp.ErrSshFxConnectionLost
}
res, err = con.client.ReadLink(realPath)
return
}
func (ad *AssetDir) RemoveDirectory(path string) (err error) {
pathData := ad.parsePath(path)
folderName, ok := ad.IsUniqueSu()
if !ok {
if len(pathData) == 1 && pathData[0] == "" {
return sftp.ErrSshFxPermissionDenied
}
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.UploadAction) {
return sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return sftp.ErrSshFxConnectionLost
}
err = ad.removeDirectoryAll(con.client, realPath)
filename := realPath
isSuccess := false
operate := model.OperateRemoveDir
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return
}
func (ad *AssetDir) Rename(oldNamePath, newNamePath string) (err error) {
oldPathData := ad.parsePath(oldNamePath)
newPathData := ad.parsePath(newNamePath)
folderName, ok := ad.IsUniqueSu()
if !ok {
if oldPathData[0] != newPathData[0] {
return sftp.ErrSshFxNoSuchFile
}
folderName = oldPathData[0]
oldPathData = oldPathData[1:]
newPathData = newPathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
conn1, oldRealPath := ad.GetSFTPAndRealPath(su, strings.Join(oldPathData, "/"))
conn2, newRealPath := ad.GetSFTPAndRealPath(su, strings.Join(newPathData, "/"))
if conn1 != conn2 {
return sftp.ErrSshFxOpUnsupported
}
err = conn1.client.Rename(oldRealPath, newRealPath)
filename := fmt.Sprintf("%s=>%s", oldRealPath, newRealPath)
isSuccess := false
operate := model.OperateRename
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return
}
func (ad *AssetDir) Remove(path string) (err error) {
pathData := ad.parsePath(path)
folderName, ok := ad.IsUniqueSu()
if !ok {
if len(pathData) == 1 && pathData[0] == "" {
return sftp.ErrSshFxPermissionDenied
}
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.UploadAction) {
return sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return sftp.ErrSshFxConnectionLost
}
err = con.client.Remove(realPath)
filename := realPath
isSuccess := false
operate := model.OperateDelete
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return
}
func (ad *AssetDir) Stat(path string) (res os.FileInfo, err error) {
pathData := ad.parsePath(path)
if len(pathData) == 1 && pathData[0] == "" {
return ad, nil
}
folderName, ok := ad.IsUniqueSu()
if !ok {
folderName = pathData[0]
pathData = pathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return nil, sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.ConnectAction) {
return res, sftp.ErrSshFxPermissionDenied
}
con, realPath := ad.GetSFTPAndRealPath(su, strings.Join(pathData, "/"))
if con == nil {
return nil, sftp.ErrSshFxConnectionLost
}
res, err = con.client.Stat(realPath)
return
}
func (ad *AssetDir) Symlink(oldNamePath, newNamePath string) (err error) {
oldPathData := ad.parsePath(oldNamePath)
newPathData := ad.parsePath(newNamePath)
folderName, ok := ad.IsUniqueSu()
if !ok {
if oldPathData[0] != newPathData[0] {
return sftp.ErrSshFxNoSuchFile
}
folderName = oldPathData[0]
oldPathData = oldPathData[1:]
newPathData = newPathData[1:]
}
su, ok := ad.suMaps[folderName]
if !ok {
return sftp.ErrSshFxNoSuchFile
}
if !ad.validatePermission(su, model.UploadAction) {
return sftp.ErrSshFxPermissionDenied
}
conn1, oldRealPath := ad.GetSFTPAndRealPath(su, strings.Join(oldPathData, "/"))
conn2, newRealPath := ad.GetSFTPAndRealPath(su, strings.Join(newPathData, "/"))
if conn1 != conn2 {
return sftp.ErrSshFxOpUnsupported
}
err = conn1.client.Symlink(oldRealPath, newRealPath)
filename := fmt.Sprintf("%s=>%s", oldRealPath, newRealPath)
isSuccess := false
operate := model.OperateSymlink
if err == nil {
isSuccess = true
}
ad.CreateFTPLog(su, operate, filename, isSuccess)
return
}
func (ad *AssetDir) removeDirectoryAll(conn *sftp.Client, path string) error {
var err error
var files []os.FileInfo
files, err = conn.ReadDir(path)
if err != nil {
return err
}
for _, item := range files {
realPath := filepath.Join(path, item.Name())
if item.IsDir() {
err = ad.removeDirectoryAll(conn, realPath)
if err != nil {
return err
}
continue
}
err = conn.Remove(realPath)
if err != nil {
return err
}
}
return conn.RemoveDirectory(path)
}
func (ad *AssetDir) GetSFTPAndRealPath(su *model.SystemUser, path string) (conn *SftpConn, realPath string) {
var ok bool
conn, ok = ad.sftpClients[su.ID]
if !ok {
var err error
conn, err = ad.GetSftpClient(su)
if err != nil {
logger.Errorf("Get Sftp Client err: %s", err.Error())
return nil, ""
}
ad.sftpClients[su.ID] = conn
}
switch strings.ToLower(ad.RootPath) {
case "home", "~", "":
realPath = filepath.Join(conn.HomeDirPath, strings.TrimPrefix(path, "/"))
default:
realPath = filepath.Join(ad.RootPath, strings.TrimPrefix(path, "/"))
}
return
}
func (ad *AssetDir) IsUniqueSu() (folderName string, ok bool) {
sus := ad.getSubFolderNames()
if len(sus) == 1 {
return sus[0], true
}
return
}
func (ad *AssetDir) getSubFolderNames() []string {
sus := make([]string, 0, len(ad.suMaps))
for folderName := range ad.suMaps {
sus = append(sus, folderName)
}
return sus
}
func (ad *AssetDir) validatePermission(su *model.SystemUser, action string) bool {
for _, pemAction := range su.Actions {
if pemAction == action || pemAction == model.AllAction {
return true
}
}
return false
}
func (ad *AssetDir) GetSftpClient(su *model.SystemUser) (conn *SftpConn, err error) {
var (
sshClient *SSHClient
ok bool
)
if ad.reuse {
key := MakeReuseSSHClientKey(ad.user, ad.asset, su)
switch su.Username {
case "":
sshClient, ok = searchSSHClientFromCache(key)
if ok {
su.Username = sshClient.username
}
default:
sshClient, ok = GetClientFromCache(key)
}
if !ok {
sshClient, err = NewClient(ad.user, ad.asset, su, ad.Overtime, ad.reuse)
if err != nil {
logger.Errorf("Get new SSH client err: %s", err)
return
}
} else {
logger.Infof("Reuse connection for SFTP: %s->%s@%s. SSH client %p current ref: %d",
ad.user.Username, sshClient.username, ad.asset.IP, sshClient, sshClient.RefCount())
}
} else {
sshClient, err = NewClient(ad.user, ad.asset, su, ad.Overtime, ad.reuse)
if err != nil {
logger.Errorf("Get new SSH client err: %s", err)
return
}
}
sftpClient, err := sftp.NewClient(sshClient.client)
if err != nil {
logger.Errorf("SSH client %p start sftp client session err %s", sshClient, err)
RecycleClient(sshClient)
return nil, err
}
HomeDirPath, err := sftpClient.Getwd()
if err != nil {
logger.Errorf("SSH client %p get home dir err %s", sshClient, err)
_ = sftpClient.Close()
RecycleClient(sshClient)
return nil, err
}
logger.Infof("SSH client %p start sftp client session success", sshClient)
conn = &SftpConn{client: sftpClient, conn: sshClient, HomeDirPath: HomeDirPath}
return conn, err
}
func (ad *AssetDir) parsePath(path string) []string {
path = strings.TrimPrefix(path, "/")
return strings.Split(path, "/")
}
func (ad *AssetDir) close() {
for _, conn := range ad.sftpClients {
if conn != nil {
conn.Close()
}
}
}
func (ad *AssetDir) CreateFTPLog(su *model.SystemUser, operate, filename string, isSuccess bool) {
data := model.FTPLog{
User: fmt.Sprintf("%s (%s)", ad.user.Name, ad.user.Username),
Hostname: ad.asset.Hostname,
OrgID: ad.asset.OrgID,
SystemUser: su.Name,
RemoteAddr: ad.addr,
Operate: operate,
Path: filename,
DataStart: common.CurrentUTCTime(),
IsSuccess: isSuccess,
}
ad.logChan <- &data
}
type SftpConn struct {
HomeDirPath string
client *sftp.Client
conn *SSHClient
}
func (s *SftpConn) Close() {
if s.client == nil {
return
}
_ = s.client.Close()
RecycleClient(s.conn)
}
func NewFakeFile(name string, isDir bool) *FakeFileInfo {
return &FakeFileInfo{
name: name,
modTime: time.Now().UTC(),
isDir: isDir,
size: int64(0),
}
}
func NewFakeSymFile(name string) *FakeFileInfo {
return &FakeFileInfo{
name: name,
modTime: time.Now().UTC(),
size: int64(0),
symlink: name,
}
}
type FakeFileInfo struct {
name string
isDir bool
size int64
modTime time.Time
symlink string
}
func (f *FakeFileInfo) Name() string { return f.name }
func (f *FakeFileInfo) Size() int64 { return f.size }
func (f *FakeFileInfo) Mode() os.FileMode {
ret := os.FileMode(0644)
if f.isDir {
ret = os.FileMode(0755) | os.ModeDir
}
if f.symlink != "" {
ret = os.FileMode(0777) | os.ModeSymlink
}
return ret
}
func (f *FakeFileInfo) ModTime() time.Time { return f.modTime }
func (f *FakeFileInfo) IsDir() bool { return f.isDir }
func (f *FakeFileInfo) Sys() interface{} {
return &syscall.Stat_t{Uid: 0, Gid: 0}
}
type FileInfoList []os.FileInfo
func (fl FileInfoList) Len() int {
return len(fl)
}
func (fl FileInfoList) Swap(i, j int) { fl[i], fl[j] = fl[j], fl[i] }
func (fl FileInfoList) Less(i, j int) bool { return fl[i].Name() < fl[j].Name() }
......@@ -132,7 +132,7 @@ func (tc *ServerTelnetConnection) login(data []byte) AuthStatus {
return AuthSuccess
}
if tc.CustomString != "" {
if tc.CustomSuccessPattern.Match(data) {
if tc.CustomSuccessPattern != nil && tc.CustomSuccessPattern.Match(data) {
return AuthSuccess
}
}
......
package utils
import (
"os/exec"
"os/user"
)
func IsInstalledMysqlClient() bool {
if mysqlPath, err := exec.LookPath("mysql"); err == nil {
cmd := exec.Command(mysqlPath, "-V")
if err = cmd.Start(); err == nil {
_ = cmd.Process.Kill()
return true
}
}
return false
}
func IsUserExist(username string) bool {
if _, err := user.Lookup(username); err == nil {
return true
}
return false
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment