This commit is contained in:
Good Evening 2018-04-03 01:41:10 +03:00
commit d782c2eb70
68 changed files with 5323 additions and 0 deletions

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
__pycache__
screens/*.png
*.log
*~*
.idea
nohup.out
config.json
docker/lib/redis/dump.rdb
docker/lib/mongo/configdb
docker/lib/mongo/db

33
Config.py Normal file
View File

@ -0,0 +1,33 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import yaml
import logging
from collections import namedtuple
def namedtupledict(*a, **kw):
nt = namedtuple(*a, **kw)
def getitem(self, key):
try:
if type(key) == str:
return getattr(self, key)
return tuple.__getitem__(self, key)
except Exception:
raise Exception("Could not get %s" % key)
def ntiter(self):
for name in self._fields:
yield name, getattr(self, name)
nt.__iter__ = ntiter
nt.__getitem__ = getitem
return nt
cnf = {}
# dafuq
with open('data/config.yaml') as config_file:
cnf = json.loads(json.dumps(yaml.load(config_file)), object_hook=lambda d: namedtupledict('X', d.keys())(*d.values()))

22
Dockerfile Normal file
View File

@ -0,0 +1,22 @@
FROM base/archlinux:latest
RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && locale-gen
ENV LC_ALL=en_US.UTF-8 \
LANG=en_US.UTF-8
RUN pacman -Syy --noconfirm
RUN pacman -S --noconfirm reflector && reflector --verbose -l 200 -p http --sort rate --save /etc/pacman.d/mirrorlist
RUN pacman -S --noconfirm --needed wget python python-pip vim proxychains base-devel geoip bind-tools grep
RUN cd /tmp && \
wget https://github.com/kelseyhightower/confd/releases/download/v0.14.0/confd-0.14.0-linux-amd64 -O confd && \
chmod +x confd
COPY requirements.txt /tmp/requirements.txt
RUN pip3 install -r /tmp/requirements.txt
ADD docker/confd /etc/confd

9
Dockerfile.test Normal file
View File

@ -0,0 +1,9 @@
FROM medved_base:latest
ENV CORE_IP=localhost MONGO_IP=localhost SELENIUM_IP=localhost REDIS_IP=localhost LOGLEVEL=INFO
COPY docker/test.sh /tmp/test.sh
COPY . /mdvd/
RUN /tmp/test.sh

674
LICENSE Normal file
View File

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

38
Makefile Normal file
View File

@ -0,0 +1,38 @@
all: down clean base bup
base:
docker build -t medved_base .
basenc:
docker build -t medved_base . --no-cache
up:
docker-compose up
upd:
docker-compose up -d
bup:
docker-compose up --build
bupd:
docker-compose up --build -d
bupds:
docker-compose up --build -d --scale worker=5
down:
docker-compose down
test:
docker build -t medved_base_test -f Dockerfile.test .
clean:
find -iname *.pyc -delete
find -type d -name __pycache__ -delete
sudo rm -vf *.log
sudo rm -f config.json
cleandb:
sudo rm -rfv docker/lib/mongo/*
sudo rm -rfv docker/lib/redis/*

5
README.md Normal file
View File

@ -0,0 +1,5 @@
# medved
to setup, update token and posting channels in docker/confd/templates/config.json.tmpl. you may also choose which plugins to use and tune their options.
run `make base && docker-compose up --build --scale worker=5`

0
__init__.py Normal file
View File

46
bin/config-linter.py Normal file
View File

@ -0,0 +1,46 @@
import json, yaml
import sys, os
import importlib
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from Config import namedtupledict
from lib import Logger, Loader
logger = Logger('Linter')
logger.info('Reading config')
with open('data/config.yaml', 'r') as config:
data = yaml.load(config)
cnf = json.loads(json.dumps(data), object_hook=lambda d: namedtupledict('X', d.keys())(*d.values()))
logger.info("Config: \n%s", json.dumps(data, indent=2))
logger.info('CORE')
services_check = ["datamgr", "listener", "executor"]
services = []
logger.info("Checking services: %s", ", ".join(services))
for s, sv in cnf.core:
services.append(s)
print(services)
for s in services_check:
if not s in services:
logger.error("Service %s is not defined!", s)
else:
logger.info("Service %s is defined, continuing", s)
for k, v in cnf.core[s]:
if k == 'package':
try:
importlib.import_module(v)
except Exception as e:
logger.error("Unable to load package %s!\n%s", v, e)
else:
logger.info("Package %s was imported successfully", v)
elif k == 'service':
try:
Loader(cnf.core[s]['package']).get(v)
except Exception as e:
logger.error("Unable to load package %s!\n%s", v, e)
else:
logger.info("Service %s was imported successfully", v)

13
bin/gen-ranges.py Executable file
View File

@ -0,0 +1,13 @@
import netaddr as n
import requests as r
# country two letter code
cn = 'ru'
# list of networks
nets = [n.IPNetwork(net.decode('ascii')) for net in r.get('http://www.cc2asn.com/data/%s_ipv4' % cn).iter_lines()]
for net in nets:
print(str(n.IPAddress(net.first)) + '-' + str(n.IPAddress(net.last)))

113
data/config.yaml Normal file
View File

@ -0,0 +1,113 @@
Core:
services:
- data_manager
# - zmq_listener
# - rq_executor
pipelines:
- ftp
services:
data_manager:
package: lib.data.Manager
service: DataManager
oneshot: 500
data:
id: pool
sources:
- random_ip
feeds:
- test_telegram
zmq_listener:
package: lib.net.Listener
service: ZMQListener
data:
id: pool
listen: "0.0.0.0"
port: 12321
rq_executor:
package: lib.exeq.Executor
service: RQExecutor
data:
id: pool
redis:
host: "127.0.0.1"
sources:
random_ip:
package: lib.plugin.base.lib.IP
service: RandomIP
data:
id: random_ip
oneshot: 100
delay: 0.5
feeds:
test_telegram:
package: lib.plugin.base.lib.Telegram
service: TelegramFeed
data:
id: pool
token:
chats:
- id: good_evening
pipelines: [ftp, gopher]
filter:
clause: any-of
equal:
- ftp_list_files_status: success
- gopher_collect_status: success
delay: 10
storage:
pool:
package: lib.plugin.base.lib.Mongo
service: MongoStorage
size: 40960
url: "127.0.0.1"
db: "medved"
coll: 'pool'
random_ip:
package: lib.plugin.base.lib.Mongo
service: MongoStorage
size: 500
url: "127.0.0.1"
db: "medved"
coll: 'randomipsource'
pipelines:
ftp:
steps:
- name: scan
package: lib.plugin.iscan.tasks.common
service: scan
multiple: 200
requires: []
- name: connect
package: lib.plugin.iscan.tasks.ftp
service: connect
multiple: False
requires: [
ftp_scan
]
- name: list_files
package: lib.plugin.iscan.tasks.ftp
service: list_files
multiple: False
requires: [
ftp_connect
]
tasks:
ftp_scan:
ports: [21]
ftp_connect:
logins: data/ftp/logins.txt
passwords: data/ftp/passwords.txt
bruteforce: true
timeout: 15
ftp_list_files:

8
data/ftp/logins.txt Normal file
View File

@ -0,0 +1,8 @@
admin
ftp
ftpuser
ftpadmin
root
uploader
test
user

15
data/ftp/passwords.txt Normal file
View File

@ -0,0 +1,15 @@
password
ftp
ftpuser
12345
123123
1234
123456
1234567
abc123
qwerty123
test
test1
user
admin

119
data/http/filters.json Normal file
View File

@ -0,0 +1,119 @@
{
"RouterOSLoginPage": {
"content": {
"title": [
"RouterOS",
"router"
],
"body": [
"RouterOS",
"mikrotik"
]
},
"storage": {
"max": 150
}
},
"ZyXel": {
"content": {
"body": [
"top.location='/index.html';"
],
"server": "micro_httpd"
}
},
"TechnicolorGatewayLogin": {
"content": {
"title": [
"Technicolor",
"Gateway",
"Login"
],
"body": [
"Technicolor",
"Gateway"
]
},
"storage": {
"max": 100
}
},
"TechnicolorModem": {
"content": {
"title": [
"Módem",
"Inicio",
"sesión"
],
"body": [
"Technicolor",
"TELMEX"
]
},
"storage": {
"max": 100
}
},
"IIS7": {
"content": {
"title": [
"IIS7"
],
"body": [
"IIS7",
"http://go.microsoft.com/fwlink/",
"welcome.png"
]
},
"storage": {
"max": 150
}
},
"NETSurveillanceWEB": {
"content": {
"title": [
"NETSurveillance",
"WEB"
],
"body": [
"NetSuveillanceWebCookie"
]
},
"storage": {
"max": 100
}
},
"TELMEX": {
"content": {
"title": [],
"body": [
"ProductName",
"Huawei",
"TELMEX"
]
},
"storage": {
"max": 100
}
},
"Docsis": {
"content": {
"title": [],
"body": [
"showRefresh(\"Docsis_system"
]
},
"storage": {
"max": 100
}
},
"Hikvision": {
"content": {
"title": [],
"body": [
"Hikvision"
],
"server": "DNVRS-Webs"
}
}
}

64
docker-compose.yml Normal file
View File

@ -0,0 +1,64 @@
version: '3.3'
networks:
default:
ipam:
driver: default
config:
- subnet: 192.168.37.0/24
services:
core:
build:
context: ./docker/core
depends_on:
- redis
- mongo
ports:
- 12321:12321
env_file:
- docker/env
environment:
- REDIS_IP=redis
- MONGO_IP=mongo
- SELENIUM_IP=selenium
- CORE_IP=core
volumes:
- .:/mdvd/
worker:
build:
context: ./docker/worker
env_file:
- docker/env
environment:
- REDIS_IP=redis
- MONGO_IP=mongo
- SELENIUM_IP=selenium
- CORE_IP=core
depends_on:
- core
- selenium
volumes:
- .:/mdvd/
selenium:
image: selenium/standalone-chrome:latest
volumes:
- /dev/shm:/dev/shm
environment:
- JAVA_OPTS=-Dselenium.LOGGER.level=WARNING
mongo:
image: mongo:latest
volumes:
- ./docker/lib/mongo:/data/
env_file:
- docker/env
redis:
image: redis:latest
volumes:
- ./docker/lib/redis:/data/
env_file:
- docker/env

View File

@ -0,0 +1,29 @@
[template]
src = "config.json.tmpl"
dest = "/mdvd/config.json"
keys = [
"/coop/conn/ip",
"/coop/conn/port",
"/coop/listen/ip",
"/coop/listen/port",
"/coop/mode",
"/coop/loglevel",
"/io/pool/delay",
"/io/pool/oneshot",
"/io/pool/size",
"/io/pool/loglevel",
"/io/ds/oneshot",
"/io/ds/loglevel",
"/io/df/loglevel",
"/io/df/telegram/token",
"/io/listener/listen",
"/io/listener/port",
"/io/listener/enabled",
"/io/listener/loglevel",
"/mongo/ip",
"/redis/ip",
"/selenium/ip",
"/core/ip",
"/loglevel"
]

View File

@ -0,0 +1,7 @@
[template]
src = "proxychains.conf.tmpl"
dest = "/etc/proxychains.conf"
keys = [
"/core/ip"
]

View File

@ -0,0 +1,87 @@
{
"stalker": {
"HTTP": {
"filters": "data/http/filters.json",
"loglevel": "{{ getv "/loglevel" }}",
"parallel": 70,
"ports": [
80,
81,
82,
83,
84,
85,
88,
8000,
8008,
8080,
8081,
8888,
9000,
9080,
9090,
9999
],
"screenshots": {
"selenium": "{{ getv "/selenium/ip" }}",
"enabled": true,
"height": 768,
"load_timeout": 40,
"pause": 10,
"script_timeout": 60,
"width": 1366,
"workers": 5
},
"timeout": 30
},
"loglevel": "{{ getv "/loglevel" }}",
"proxy": "{{ getv "/core/ip" }}"
},
"io": {
"df": {
"Remote": {
"delay": 20,
"preserve": true,
"ip": "{{ getv "/coop/conn/ip" }}",
"port": {{ getv "/coop/conn/port" }}
},
"Telegram": {
"delay": 20,
"preserve": true,
"token": "{{ getv "/io/df/telegram/token" }}",
"chats": [
{
"id": "xai7poozengee2Aen3poMookohthaZ",
"plugins": ["FTP", "Gopher", "HTTP"],
"enabled": true
},
{
"id": "aiWeipeighah7vufoHa0ieToipooYe",
"plugins": ["FTP"],
"enabled": true
},
{
"id": "ohl7AeGah5uo8cho4nae9Eemaeyae3",
"plugins": ["Gopher"],
"enabled": true
},
{
"id": "gohquooFee3duaNaeNuthushoh8di2",
"plugins": ["HTTP"],
"enabled": true
}
]
},
"default": ["Telegram"],
"loglevel": "{{ getv "/io/df/loglevel" }}"
},
"loglevel": "{{ getv "/loglevel" }}",
"mongo": {
"db": "medved",
"url": "mongodb://{{ getv "/mongo/ip" }}:27017"
},
"redis": {
"host": "{{ getv "/redis/ip" }}"
}
}
}

View File

@ -0,0 +1,16 @@
strict_chain
tcp_read_time_out 15000
tcp_connect_time_out 15000
localnet 127.0.0.0/255.0.0.0
localnet 172.16.0.0/255.240.0.0
localnet 192.168.0.0/255.255.0.0
localnet 149.154.167.197/255.255.255.255
localnet 149.154.167.198/255.255.255.255
localnet 149.154.167.199/255.255.255.255
localnet 149.154.167.200/255.255.255.255
[ProxyList]
socks5 {{ getv "/core/ip" }} 9050

18
docker/core/Dockerfile Normal file
View File

@ -0,0 +1,18 @@
FROM medved_base:latest
RUN pacman -S --noconfirm --needed git libpcap linux-headers clang tor
RUN git clone https://github.com/robertdavidgraham/masscan && \
cd masscan && \
make -j && \
mv bin/masscan /bin/masscan
RUN wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz && gunzip GeoLiteCity.dat.gz
RUN mkdir -p /usr/share/GeoIP/ && mv GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat
ADD files/torrc /etc/tor/torrc
ADD files/run.sh /tmp/run.sh
CMD ["/tmp/run.sh"]

12
docker/core/files/run.sh Executable file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env bash
export CORE_IP=$(host ${CORE_IP} | head -n1 | grep -Po "(\d+\.?){4}")
export MONGO_IP=$(host ${MONGO_IP} | head -n1 | grep -Po "(\d+\.?){4}")
export SELENIUM_IP=$(host ${SELENIUM_IP} | head -n1 | grep -Po "(\d+\.?){4}")
export REDIS_IP=$(host ${REDIS_IP} | head -n1 | grep -Po "(\d+\.?){4}")
/tmp/confd -onetime -backend env
sudo -u tor tor
cd /mdvd && proxychains -q python3 medved.py

5
docker/core/files/torrc Normal file
View File

@ -0,0 +1,5 @@
SocksPort 0.0.0.0:9050
SocksPolicy accept *
Log notice syslog
DataDirectory /var/lib/tor
RunAsDaemon 1

29
docker/env Normal file
View File

@ -0,0 +1,29 @@
LOGLEVEL=DEBUG
COOP_CONN_IP=192.168.99.130
COOP_CONN_PORT=12321
COOP_LISTEN_IP=0.0.0.0
COOP_LISTEN_PORT=12321
COOP_MODE=master
COOP_LOGLEVEL=DEBUG
IO_POOL_LOGLEVEL=DEBUG
IO_POOL_SIZE=15000
IO_POOL_DELAY=3
IO_POOL_ONESHOT=200
IO_LISTENER_LOGLEVEL=DEBUG
IO_LISTENER_ENABLED=true
IO_LISTENER_LISTEN=0.0.0.0
IO_LISTENER_PORT=12321
IO_DS_ONESHOT=350
IO_DS_LOGLEVEL=DEBUG
IO_DF_LOGLEVEL=DEBUG
IO_DF_TELEGRAM_TOKEN=TOKEN
LC_ALL=en_US.utf-8
LANG=en_US.utf-8

0
docker/lib/mongo/.keep Normal file
View File

0
docker/lib/redis/.keep Normal file
View File

10
docker/test.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/bash -x
export CORE_IP=$(host ${CORE_IP} | head -n1 | grep -Po "(\d+\.?){4}")
source /mdvd/docker/env
/tmp/confd -onetime -backend env
cat /etc/proxychains.conf
cat /mdvd/config.json | python -m json.tool

5
docker/worker/Dockerfile Normal file
View File

@ -0,0 +1,5 @@
FROM medved_base:latest
ADD files/run.sh /tmp/run.sh
CMD ["/tmp/run.sh"]

7
docker/worker/files/run.sh Executable file
View File

@ -0,0 +1,7 @@
#!/usr/bin/env bash
export CORE_IP=$(host ${CORE_IP} | head -n1 | grep -Po "(\d+\.?){4}")
/tmp/confd -onetime -backend env
cd /mdvd && proxychains -q rq worker common -u "redis://${REDIS_IP}:6379/"

66
lib/Service.py Normal file
View File

@ -0,0 +1,66 @@
from time import sleep
from threading import Thread
from lib import Logger, Loader, Loadable
from Config import cnf
class Service(Loadable):
def __init__(self, thread, id, root=cnf):
super().__init__(id, root)
self._data = Loader.by_id('storage', self.lcnf.data.id)
self._stop_timeout = 10
self._running = False
self._thread_to_run = thread
self._run_thread = None
self._logger = Logger('Service')
self._init()
def _init(self):
pass
def start(self):
self._logger.debug('pre_start')
self._pre_start()
self._logger.debug('start')
self._running = True
self._run_thread = Thread(target=self._thread_to_run)
self._run_thread.daemon = True
self._run_thread.start()
self._logger.debug('post_start')
self._post_start()
self._logger.info('start finished')
def stop(self):
self._logger.debug('pre_stop')
self._pre_stop()
self._logger.debug('stop')
self._running = False
self._run_thread.join(timeout=self._stop_timeout)
self._logger.debug('post_stop')
self._post_stop()
self._logger.info('stop finished')
def __run(self):
while self._running:
self._logger.debug('NOOP')
sleep(1)
def _pre_stop(self):
pass
def _post_stop(self):
pass
def _pre_start(self):
pass
def _post_start(self):
pass

3
lib/__init__.py Normal file
View File

@ -0,0 +1,3 @@
import data
from .util import Logger, Loader, Loadable
from .Service import Service

19
lib/data/Feed.py Normal file
View File

@ -0,0 +1,19 @@
from queue import LifoQueue
from time import sleep
import itertools
from lib.net import Remote
from lib import Service
class Feed(Service):
def __init__(self, thread, id, root):
super().__init__(thread, id, root)
self._logger.add_field('service', 'Feed')
self._logger.add_field('vname', self.__class__.__name__)
def get(self, plugin, count=1, timeout=3):
items = self._data.get(count)
self._logger.debug("get %s OF %s", len(items), count)
return items

19
lib/data/Filter.py Normal file
View File

@ -0,0 +1,19 @@
from lib import Loader
class Filter:
def __init__(self):
self._not_exist = []
self._exist = []
self._equal = {}
self._not_equal = {}
def generate(self):
pass
def MongoFilter(filter):
def generate(self):
data = {}
#for i in
# dunno

59
lib/data/Manager.py Normal file
View File

@ -0,0 +1,59 @@
from lib.data import Source, Feed
from time import sleep
from lib import Service, Loader
class DataManager(Service):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
self._logger.add_field('service', 'DataManager')
self.sources = {}
for s in self.lcnf.sources:
self.attach_source(s)
self.feeds = {}
for f in self.lcnf.feeds:
self.attach_feed(f)
def _pre_start(self):
self._logger.debug('starting sources')
for _,s in self.sources.items():
s.start()
self._logger.debug('starting feeds')
for _,f in self.feeds.items():
f.start()
def _pre_stop(self):
self._logger.debug('stopping sources')
for _,s in self.sources.items():
s.stop()
self._logger.debug('stopping feeds')
for _,f in self.feeds.items():
f.stop()
def attach_source(self, id):
ds = Loader.by_id('sources', id)
self.sources[id] = ds
def attach_feed(self, id):
df = Loader.by_id('feeds', id)
self.feeds[id] = df
def get_source(self, name) -> Source:
return self.sources.get(name)
def get_feed(self, name) -> Feed:
return self.feeds.get(name)
def __run(self):
while self._running:
if self._data.count() < self.lcnf.oneshot:
while self._running and (self._data.count() + self.lcnf.oneshot < self._data.size()):
self._logger.debug("fill %s OF %s", self._data.count(), self._data.size())
for _,source in self.sources.items():
items = source.next(count=self.lcnf.oneshot)
if items:
self._data.put(items)
sleep(1)
else:
self._logger.debug('Pool size is ok: %s', self._data.count())
sleep(1)

20
lib/data/Source.py Normal file
View File

@ -0,0 +1,20 @@
from lib import Service
class Source(Service):
def __init__(self, thread, id, root):
super().__init__(thread, id, root)
self._logger.add_field('service', 'Feed')
self._logger.add_field('vname', self.__class__.__name__)
def item(self, val = None):
return {
'source': self._id,
'steps': {},
'data': val
}
def next(self, count=10, block=False):
if self._running or not self._data.count() == 0:
return self._data.get(count=count, block=block)
elif self._data.count() == 0:
raise Exception("Storage is empty, generator is stopped")

82
lib/data/Storage.py Normal file
View File

@ -0,0 +1,82 @@
from queue import LifoQueue, Empty, Full
from lib import Loadable, Logger
class Storage(Loadable):
def __init__(self, id, root):
super().__init__(id, root)
self._size = self.lcnf.size
self._logger = Logger("Storage")
self._logger.add_field('vname', self.__class__.__name__)
def size(self):
return self._size
def count(self):
return 0
def _get(self, block, filter):
pass
def _get_many(self, count, block, filter):
items = []
for _ in range(count):
items.append(self._get(block, filter))
return items
def get(self, count=1, block=True, filter=None):
self._logger.debug("get %s, %s", count, block)
items = []
if count == 1:
items.append(self._get(block, filter))
elif count > 1:
items = self._get_many(count, block, filter)
return [i for i in items if i is not None]
def _put(self, item, block):
pass
def _put_many(self, items, block):
for i in items:
if i is not None:
self._put(i, block)
def put(self, items, block=True):
if items:
items = [i for i in items if i is not None]
self._logger.debug("put %s, %s", len(items), block)
if len(items) == 1:
self._put(items[0], block)
elif len(items) > 1:
self._put_many(items, block)
def _find(self):
pass
def find(self):
self._logger.debug("find")
return self._find()
class LiFoStorage(Storage):
def __init__(self, id, root):
super().__init__(id, root)
self._data = LifoQueue()
def count(self):
return self._data.qsize()
def _get(self, block=False, filter=None):
try:
return self._data.get(block=block)
except Empty:
pass
def _put(self, item, block=True):
try:
self._data.put(item, block=block)
except Full:
pass

11
lib/data/Type.py Normal file
View File

@ -0,0 +1,11 @@
from lib import Loadable, Logger
class Type(Loadable):
def __init__(self):
self.data = {}
class Host(Type):
def __init__(self):
self.data = {
'ip': ''
}

7
lib/data/__init__.py Normal file
View File

@ -0,0 +1,7 @@
from .Storage import Storage
from .Source import Source
from .Feed import Feed
from .Manager import DataManager
__all__ = ['Storage', 'Source', 'DataManager']

42
lib/exeq/Executor.py Normal file
View File

@ -0,0 +1,42 @@
from lib import Service, Loader, Loadable
from lib.tasks.worker import worker
from rq import Queue
from redis import Redis
class Executor(Service):
def __init__(self, thread, id, root):
super().__init__(thread, id, root)
self._logger.add_field('service', 'Executor')
self._logger.add_field('vname', self.__class__.__name__)
class RQExecutor(Executor):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
def __run(self):
while self._running:
try:
for pn, pipeline in self.cnf.pipelines:
self._logger.debug("pipeline: %s", pn)
for step in pipeline.steps:
self._logger.debug("step: %s", step.name)
redis_conn = Redis(host=self.lcnf.redis.host)
q = Queue('worker', connection=redis_conn)
filter = {
"not_exist": [
pn + '_' + step.name
]
}
items = []
if step.multiple != False:
items = self._data.get(count=step.multiple, filter=filter)
else:
items = self._data.get(filter=filter)
for i in items:
q.enqueue(Loader(step.package).get(step.service), i)
except Exception as e:
self._logger.error(e)

7
lib/exeq/Pipeline.py Normal file
View File

@ -0,0 +1,7 @@
from lib import Loadable
class Pipeline(Loadable):
def __init__(self, id, root):
super().__init__(id, root)

1
lib/exeq/__init__.py Normal file
View File

@ -0,0 +1 @@
from .Executor import Executor

20
lib/net/Action.py Normal file
View File

@ -0,0 +1,20 @@
class Action:
def __init__(self, datapool):
self._datapool = datapool
self.result = None
def run(self, data):
pass
class data_get(Action):
def run(self, data):
return self._datapool.get(data["plugin"], data["count"])
class data_put(Action):
def run(self, data):
self._datapool.put(data['plugin'], data['items'])
class ActionManager:
@staticmethod
def get(name: str):
return globals()[name.replace('.', '_')]

46
lib/net/Listener.py Normal file
View File

@ -0,0 +1,46 @@
# pylint: disable=E1101
from lib import Service
from lib.net import ActionManager, Message
import zmq
class Listener(Service):
def __init__(self, thread, id, root):
super().__init__(thread, id, root)
self._logger.add_field('service', 'Listener')
self._logger.add_field('vname', self.__class__.__name__)
class ZMQListener(Listener):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
def _pre_start(self):
self._running = True
self._z_ctx = zmq.Context()
self._z_sck = self._z_ctx.socket(zmq.REP)
self._z_sck.bind("tcp://%s:%s" % (self.lcnf.listen, self.lcnf.port))
def _post_stop(self):
self._z_ctx.destroy()
def __run(self):
while self._running:
try:
reply = Message()
msg = None
try:
msg = Message.load(self._z_sck.recv())
if msg:
self._logger.info("Requested %s", msg.get('action'))
action = ActionManager.get(msg.get('action'))(self._datapool)
reply.set('data', action.run(msg.get('data')))
reply.set('status', True)
except Exception as e:
self._logger.warn("Action %s failed", msg.get('action'))
self._logger.debug(e)
reply.set('data', e)
reply.set('status', False)
self._z_sck.send(reply.dump())
except Exception as e:
self._logger.error(e)

27
lib/net/Message.py Normal file
View File

@ -0,0 +1,27 @@
import pickle
class Message:
def __init__(self, data=None):
if data is None:
data = {}
self._data = data
def set(self, key, value):
self._data[key] = value
def get(self, key):
return self._data.get(key, None)
def data(self):
return self._data
def dump(self):
return pickle.dumps(self)
@classmethod
def load(cls, pickled_data):
try:
obj = pickle.loads(pickled_data)
return cls(obj.data())
except EOFError:
return cls({})

45
lib/net/Remote.py Normal file
View File

@ -0,0 +1,45 @@
# pylint: disable=E1101
import zmq
import threading
from Config import cnf
from lib.net import Message
from lib import Logger
class Remote:
def __init__(self, ip, port):
self._send_lock = threading.Lock()
self._ip = ip
self._port = port
self._url = "tcp://%s:%s" % (ip, port)
self._logger = Logger("Remote %s" % self._url)
self._z_ctx = None
self._z_sck = None
def connect(self):
self._z_ctx = zmq.Context()
self._z_sck = self._z_ctx.socket(zmq.REQ)
def run(self, action, data=None):
msg = Message()
msg.set('action', action)
msg.set('data', data)
rep = self._send_msg(msg)
if rep.get('status') == False:
self._logger.info(rep.get('data'))
return rep
def _send_msg(self, msg):
self._logger.debug(msg.data())
self._send_lock.acquire()
self._z_sck.connect(self._url)
self._z_sck.send(msg.dump())
reply = Message.load(self._z_sck.recv())
self._send_lock.release()
self._logger.debug(reply.data())
return reply

4
lib/net/__init__.py Normal file
View File

@ -0,0 +1,4 @@
from .Message import Message
from .Action import Action, ActionManager
from .Remote import Remote
from .Listener import Listener

9
lib/plugin/Manager.py Normal file
View File

@ -0,0 +1,9 @@
import importlib
class Manager:
def __init__(self):
pass
@staticmethod
def get_plugin(name):
return importlib.import_module("lib.plugin.plugins." + name)

6
lib/plugin/Task.py Normal file
View File

@ -0,0 +1,6 @@
class Task:
def __init__(self):
self._data = None
def run(self):
pass

1
lib/plugin/__init__.py Normal file
View File

@ -0,0 +1 @@
from .Manager import Manager

87
lib/plugin/base/lib/IP.py Normal file
View File

@ -0,0 +1,87 @@
from lib.data import Source
from lib import Loader
from time import sleep
import os
import netaddr
import itertools
import random
import socket
import struct
class IPSource(Source):
def __init__(self, thread, id, root):
super().__init__(thread, id, root)
def item(self, val = None):
return {
'source': self._id,
'data': {
'ip': val
}
}
class IPRange(IPSource):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
self._iprange = []
self.load_ip_range()
def load_ip_range(self):
ip_range = []
with open(self.lcnf.path, "r") as text:
for line in text:
try:
diap = line.split('-')
if len(diap) == 2:
ip_range.append(netaddr.IPRange(diap[0], diap[1]))
else:
ip_range.append(netaddr.IPNetwork(diap[0]))
except Exception as e:
raise Exception("Error while adding range {}: {}".format(line, e))
self._iprange = ip_range
def __run(self):
npos = 0
apos = 0
while self._running:
try:
for _ in itertools.repeat(None, self.lcnf.oneshot):
if self.lcnf.ordered:
# put currently selected element
self._data.put(str(self._iprange[npos][apos]))
# rotate next element through networks and addresses
if apos + 1 < self._iprange[npos].size:
apos += 1
else:
apos = 0
if npos + 1 < len(self._iprange):
npos += 1
else:
if self.lcnf.repeat:
npos = 0
else:
self.stop()
else:
self._data.put(str(random.choice(random.choice(self._iprange))))
sleep(self.lcnf.delay)
except Exception as e:
self._logger.warn(e)
class RandomIP(IPSource):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
def __run(self):
while self._running:
try:
items = []
for _ in itertools.repeat(None, self.lcnf.oneshot):
randomip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
items.append(self.item(str(randomip)))
self._data.put(items)
sleep(self.lcnf.delay)
except Exception as e:
self._logger.warn(e)

View File

@ -0,0 +1,46 @@
from pymongo import MongoClient
from time import sleep
from lib.data import Storage
class MongoStorage(Storage):
def __init__(self, id, root):
super().__init__(id, root)
self._client = MongoClient(self.lcnf.url)
self._db = self._client.get_database(self.lcnf.db)
self._coll = self._db.get_collection(self.lcnf.coll)
self._logger.add_field("db", self.lcnf.db, 7)
self._logger.add_field("coll", self.lcnf.coll, 7)
self._logger.debug("Connecting")
def count(self):
return self._coll.count()
def _get(self, block, filter):
if filter is None:
filter = {}
item = self._coll.find_one_and_delete(filter=filter)
if block:
while not item:
item = self._coll.find_one_and_delete(filter=filter)
sleep(1)
return item
def _put(self, item, block):
if block:
while self.count() + 1 >= self.size():
self._logger.debug('Collection full: %s of %s', self.count(), self.size())
sleep(1)
self._coll.insert_one(item)
def _put_many(self, items, block):
if block:
while self.count() + len(items) >= self.size():
self._logger.debug('Collection full: %s of %s', self.count(), self.size())
sleep(1)
self._coll.insert_many(items)
def _find(self, filter=None):
if filter is None:
filter = {}
return self._coll.find(filter)

View File

@ -0,0 +1,40 @@
from lib.data import Feed, Source
from lib.net import Remote
from time import sleep
class RemoteFeed(Feed):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
def __run(self):
while self._running:
try:
remote = Remote(self.lcnf.ip, self.lcnf.port)
remote.connect()
items = self.get(5)
if items:
self._logger.info("Sending %s items" % len(items))
remote.run('data.put', {'items': items})
sleep(self.lcnf.delay)
except Exception as e:
self._logger.warn(e)
class RemoteSource(Source):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
def __run(self):
remote = Remote(self.lcnf.ip, self.lcnf.port)
remote.connect()
while self._running:
self._logger.debug("Requesting from %s", self.lcnf.ip)
rep = remote.run('data.get', {'count': self.lcnf.oneshot})
if rep.get('status'):
targets = rep.get("data")
else:
targets = []
self._logger.debug("Got %s items", len(targets))
for t in targets:
self._data.put(t)
sleep(self.lcnf.delay)

View File

@ -0,0 +1,33 @@
from lib.data import Feed, Filter
from lib.plugin import Manager
import telebot
from time import sleep
class TelegramFeed(Feed):
def __init__(self, id, root):
super().__init__(self.__run, id, root)
def __run(self):
while self._running:
try:
for chat in self.lcnf.chats:
chat_id = chat.id
sleep(self.lcnf.delay)
continue
msg = Manager.get_plugin(plugin).Plugin.TelegramMessage(host)
msg.run()
if msg.data['txt']:
tbot = telebot.TeleBot(self.lcnf.token, threaded=False)
if msg.data['img']:
self._logger.debug("Send IP with img %s:%s to %s" % (host['ip'], host['port'], chat_id))
tbot.send_photo("@" + chat_id, msg.data['img'], caption=msg.data['txt'])
else:
self._logger.debug("Send IP %s:%s to %s" % (host['ip'], host['port'], chat_id))
tbot.send_message("@" + chat_id, msg.data['txt'])
else:
self._logger.error('Empty text!')
sleep(self.lcnf.delay)
except Exception as e:
self._logger.warn(e)

View File

@ -0,0 +1,62 @@
plugin:
name: iscan
version: 0.1
pipelines:
FTP:
actions:
- scan
- connect
- metadata
- filetree
df:
Telegram:
action: metadata
chats:
- xai7poozengee2Aen3poMookohthaZ
- aiWeipeighah7vufoHa0ieToipooYe
HTTP:
actions:
- scan
- connect
- metadata
- screenshot
df:
Telegram:
action: screenshot
chats:
- xai7poozengee2Aen3poMookohthaZ
- gohquooFee3duaNaeNuthushoh8di2
Gopher:
actions:
- connect
- collect
df:
Telegram:
action: collect
chats:
- xai7poozengee2Aen3poMookohthaZ
- ohl7AeGah5uo8cho4nae9Eemaeyae3
df:
Telegram:
token: TOKEN
ds:
IPRange:
file: file
Remote:
docker:
services:
selenium:
image: selenium/standalone-chrome:latest
volumes:
- /dev/shm:/dev/shm
environment:
- JAVA_OPTS=-Dselenium.LOGGER.level=WARNING
worker_env:
- SELENIUM_IP=selenium
required_by:
- HTTP

View File

@ -0,0 +1,56 @@
# pylint: disable=E1101
import subprocess
import json
from jsoncomment import JsonComment
from lib import Logger
import GeoIP
from Config import cnf
logger = Logger("common")
class MasScan:
def __init__(self, bin_path='/usr/bin/masscan', opts="-sS -Pn -n --wait 0 --max-rate 5000"):
self.bin_path = bin_path
self.opts_list = opts.split(' ')
def scan(self, ip_list, port_list):
port_list = ','.join([str(p) for p in port_list])
ip_list = ','.join([str(ip) for ip in ip_list])
process_list = [self.bin_path]
process_list.extend(self.opts_list)
process_list.extend(['-oJ', '-', '-p'])
process_list.append(port_list)
process_list.append(ip_list)
proc = subprocess.run(process_list, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
out = proc.stdout.decode('utf-8') if proc.stdout else '[]'
parser = JsonComment(json)
result = parser.loads(out)
return result
def scan(items, taskid):
gi = GeoIP.open(cnf.geoip_dat, GeoIP.GEOIP_INDEX_CACHE | GeoIP.GEOIP_CHECK_CACHE)
logger.debug("Starting scan")
ms = MasScan()
hosts = ms.scan(ip_list=[i['data']['ip'] for i in items], port_list=cnf.Tasks[taskid].ports)
for h in hosts:
for port in h['ports']:
host = {
'ip': h['ip'],
'port': port['port'],
'data': {
'geo': {
'country': None,
'city': None
}
}
}
geodata = gi.record_by_name(host['ip'])
if geodata:
if 'country_code3' in geodata and geodata['country_code3']:
host['data']['geo']['country'] = geodata['country_code3']
if 'city' in geodata and geodata['city']:
host['data']['geo']['city'] = geodata['city']
logger.debug("Found %s:%s", host['ip'], host['port'])

View File

@ -0,0 +1,57 @@
from lib.util import get_logger
from Config import cnf
from Storage import DB
class Plugin:
class TelegramMessage:
def __init__(self, host, name='Base'):
self._host = host
self._name = name
self._init()
self._logger = get_logger("%s Message" % self._name, cnf.stalker[self._name].loglevel)
self.data = {
'txt': 'Not implemented',
'img': None
}
def _init(self):
pass
def run(self):
try:
self._generate()
except Exception as e:
self._logger.debug("Error occured: %s (%s:%s)", e, self._host['ip'], self._host['port'])
def _generate(self):
pass
class Pipeline:
class PipelineError(Exception):
pass
def __init__(self, host, name='Base'):
self._logger = get_logger("%s Pipeline" % name, cnf.stalker[name].loglevel)
self._host = host
self._name = name
self._init()
self._logger.debug("Starting for %s:%s", self._host['ip'], self._host['port'])
self.run()
def _init(self):
pass
def run(self):
try:
self._find()
self._push()
except Exception as e:
self._logger.debug("Error occured: %s (%s:%s)", e, self._host['ip'], self._host['port'])
def _find(self):
pass
def _push(self):
DB.collection('qu_%s_feed' % self._name).insert_one(self._host)

110
lib/plugin/plugins/FTP.py Normal file
View File

@ -0,0 +1,110 @@
import ftplib
import netaddr
from Config import cnf
from lib.plugin.plugins import BasePlugin
class Plugin(BasePlugin):
class TelegramMessage(BasePlugin.TelegramMessage):
def _init(self):
self._name = "FTP"
def _generate(self):
self.data['txt'] = "ftp://%s:%s@%s/\n" % \
(self._host['data']['username'], self._host['data']['password'], self._host['ip'])
for filename in self._host['data']['files']:
self.data['txt'] += " + %s\n" % filename
self.data['txt'] += "Geo: %s/%s\n" % (self._host['data']['geo']['country'], self._host['data']['geo']['city'])
self.data['txt'] += "#ftp_" + str(int(netaddr.IPAddress(self._host['ip'])))
class Pipeline(BasePlugin.Pipeline):
def _init(self):
self._name = "FTP"
def run(self):
try:
self._connect()
self._find()
self._filter()
self._push()
except Exception as e:
self._logger.debug("Error occured: %s (%s)", e, self._host['ip'])
else:
self._logger.info("Succeeded for %s" % self._host['ip'])
def _connect(self):
self.ftp = ftplib.FTP(host=self._host['ip'], timeout=cnf.stalker.FTP.timeout)
try:
self._logger.debug('Trying anonymous login')
self.ftp.login()
except ftplib.error_perm:
pass
else:
self._logger.debug('Succeeded with anonymous')
self._host['data']['username'] = 'anonymous'
self._host['data']['password'] = ''
return
if cnf.stalker.FTP.bruteforce:
usernames = []
passwords = []
with open(cnf.stalker.FTP.logins, 'r') as lfh:
for username in lfh:
usernames.append(username.rstrip())
with open(cnf.stalker.FTP.passwords, 'r') as pfh:
for password in pfh:
passwords.append(password.rstrip())
for username in usernames:
for password in passwords:
try:
self.ftp.voidcmd('NOOP')
except IOError:
self.ftp = ftplib.FTP(host=self._host['ip'], timeout=cnf.stalker.FTP.timeout)
self._logger.debug('Trying %s' % (username + ':' + password))
try:
self.ftp.login(username, password)
except ftplib.error_perm:
continue
except:
raise
else:
self._logger.debug('Succeeded with %s' %(username + ':' + password))
self._host['data']['username'] = username
self._host['data']['password'] = password
return
raise Exception('No matching credentials found')
def _find(self):
filelist = self.ftp.nlst()
try:
self.ftp.quit()
except:
# that's weird, but we don't care
pass
try:
if len(filelist) == 0 or filelist[0] == "total 0":
raise self.PipelineError("Empty server")
except IndexError:
pass
self._host['data']['files'] = []
for fileName in filelist:
self._host['data']['files'].append(fileName)
def _filter(self):
self._host['data']['filter'] = False
if len(self._host['data']['files']) == 0:
self._host['data']['filter'] = "Empty"
elif len(self._host['data']['files']) < 6:
match = 0
for f in 'incoming', '..', '.ftpquota', '.', 'pub':
if f in self._host['data']['files']:
match += 1
if match == len(self._host['data']['files']):
self._host['data']['filter'] = "EmptyWithSystemDirs"

View File

@ -0,0 +1,70 @@
import socket
import netaddr
from Config import cnf
from lib.plugin.plugins import BasePlugin
class Plugin(BasePlugin):
class TelegramMessage(BasePlugin.TelegramMessage):
def _init(self):
self._name = "Gopher"
def _generate(self):
self.data['txt'] = "gopher://%s/\n" % self._host['ip']
self.data['txt'] += "Dirs:\n"
for dir in [f for f in self._host['data']['files'] if f['type'] == '1']:
self.data['txt'] += " + %s\n" % dir['path']
self.data['txt'] += "Other nodes:\n"
for file in [f for f in self._host['data']['files'] if f['type'] != '1' and f['type'] != 'i']:
self.data['txt'] += " + %s\n %s\n" % (file['path'], file['name'])
self.data['txt'] += "Geo: %s/%s\n" % (self._host['data']['geo']['country'], self._host['data']['geo']['city'])
self.data['txt'] += "#gopher_" + str(int(netaddr.IPAddress(self._host['ip'])))
class Pipeline(BasePlugin.Pipeline):
def _init(self):
self._name = "Gopher"
def run(self):
try:
self._find()
self._push()
except Exception as e:
self._logger.debug("Error occured: %s (%s)", e, self._host['ip'])
else:
self._logger.info("Succeeded for %s" % self._host['ip'])
def _recv(self, sck):
total_data = []
while True:
data = sck.recv(2048)
if not data:
break
total_data.append(data.decode('utf-8'))
return ''.join(total_data)
def _find(self):
sock = socket.socket()
sock.settimeout(cnf.stalker.Gopher.timeout)
sock.connect((self._host['ip'], int(self._host['port'])))
sock.sendall(b'\n\n')
response = self._recv(sock)
sock.close()
self._logger.debug("Parsing result")
self._host['data']['files'] = []
self._host['data']['filter'] = False
for s in [s for s in response.split("\r\n") if s]:
node = {}
fields = s.split("\t")
self._logger.debug(fields)
node['type'] = fields[0][0]
if len(fields) == 4:
node['name'] = fields[0][1:]
node['path'] = fields[1]
node['serv'] = f"{fields[2]}:{fields[3]}"
self._host['data']['files'].append(node)
if not self._host['data']['files']:
raise self.PipelineError("Empty server (not Gopher?)")

185
lib/plugin/plugins/HTTP.py Normal file
View File

@ -0,0 +1,185 @@
from io import BytesIO
import json
import time
import bs4
import requests
import urllib3
from PIL import Image
from bson.binary import Binary
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.proxy import Proxy, ProxyType
import zlib
import netaddr
from Config import cnf
from lib.plugin.plugins import BasePlugin
class Plugin(BasePlugin):
class TelegramMessage(BasePlugin.TelegramMessage):
def _init(self):
self._name = "HTTP"
def _generate(self):
self.data['txt'] = "#code%s" % self._host['data']['response']['code']
server = self._host['data']['response']['headers'].get('Server', None)
if server:
self.data['txt'] += " Server: #%s\n" % server
else:
self.data['txt'] += "\n"
if self._host['data']['title']:
self.data['txt'] += "Title: %s\n" % self._host['data']['title']
self.data['txt'] += "Geo: %s/%s\n" % (self._host['data']['geo']['country'], self._host['data']['geo']['city'])
self.data['txt'] += "http://%s:%s/\n" % (self._host['ip'], self._host['port'])
self.data['txt'] += "#http_" + str(int(netaddr.IPAddress(self._host['ip'])))
if self._host["data"]["screenshot"]:
self.data['img'] = BytesIO(zlib.decompress(self._host["data"]["screenshot"]))
class Pipeline(BasePlugin.Pipeline):
def _init(self):
self._name = "HTTP"
def run(self):
try:
self._find()
self._filter()
self._capture_screenshot()
self._push()
except Exception as e:
self._logger.debug("Error occured: %s (%s:%s)", e, self._host['ip'], self._host['port'])
else:
self._logger.info("Succeeded for %s:%s", self._host['ip'], self._host['port'])
def _find(self):
urllib3.disable_warnings()
response = requests.get(url='http://%s:%s/' % (self._host['ip'], self._host['port']),
timeout=cnf.stalker.HTTP.timeout,
verify=False)
if response.status_code in [400, 401, 403, 500]:
raise self.PipelineError("Bad response")
self._host['data']['response'] = {}
self._host['data']['response']['code'] = response.status_code
self._host['data']['response']['text'] = response.text
self._host['data']['response']['content'] = response.content
self._host['data']['response']['encoding'] = response.encoding
self._host['data']['response']['headers'] = response.headers
encoding = response.encoding if 'charset' in response.headers.get('content-type', '').lower() else None
soup = bs4.BeautifulSoup(response.content, "html.parser", from_encoding=encoding)
if soup.original_encoding != 'utf-8':
meta = soup.select_one('meta[charset], meta[http-equiv="Content-Type"]')
if meta:
if 'charset' in meta.attrs:
meta['charset'] = 'utf-8'
else:
meta['content'] = 'text/html; charset=utf-8'
self._host['data']['response']['text'] = soup.prettify() # encodes to UTF-8 by default
title = soup.select_one('title')
if title:
if title.string:
title = title.string
else:
title = ""
else:
title = ""
self._host['data']['title'] = title
def _filter(self):
self._host['data']['filter'] = False
response = self._host['data']['response']
with open(cnf.stalker.HTTP.filters, encoding='utf-8') as ffh:
filters = json.load(ffh)
for fid, filter in filters.items():
title_filter = filter["content"]["title"] if "title" in filter["content"] else []
body_filter = filter["content"]["body"] if "body" in filter["content"] else []
server_filter = filter["content"]["server"] if "server" in filter["content"] else ""
match = 0
for keyword in title_filter:
if keyword in self._host['data']['title']:
match += 1
if match == len(title_filter):
match = 0
for keyword in body_filter:
if keyword in response['text']:
match += 1
if match == len(body_filter):
match = True
if server_filter:
if self._host['data']['server'] == server_filter:
match = True
else:
match = False
else:
match = False
else:
match = False
if match:
self._host['data']['filter'] = fid
def _capture_screenshot(self):
# сраный selenium, как же я его ненавижу
# боль
# страдания
# ноль документации
img_byte_arr = BytesIO()
url = 'http://%s:%s/' % (self._host["ip"], self._host["port"])
self._host["data"]["screenshot"] = None
self._logger.debug("Obtaining driver")
driver = None
img = None
try:
caps = dict(DesiredCapabilities.CHROME)
caps['args'] = ["--proxy-server", "socks5://%s:9050" % cnf.stalker.proxy]
driver = webdriver.Remote(command_executor = "http://%s:4444/wd/hub" % cnf.stalker.HTTP.screenshots.selenium,
desired_capabilities=caps)
driver.set_window_size(cnf.stalker.HTTP.screenshots.width, cnf.stalker.HTTP.screenshots.height)
driver.set_page_load_timeout(cnf.stalker.HTTP.screenshots.load_timeout)
driver.set_script_timeout(cnf.stalker.HTTP.screenshots.script_timeout)
self._logger.debug("Loading %s:%s", self._host['ip'], self._host['port'])
driver.get(url)
time.sleep(cnf.stalker.HTTP.screenshots.pause)
driver.execute_script("window.scrollTo(0, 0);")
img = driver.get_screenshot_as_png()
except Exception as e:
raise e
finally:
if driver:
driver.quit()
self._logger.debug("Finished for %s:%s", self._host['ip'], self._host['port'])
with Image.open(BytesIO(img)) as img:
img = img.crop((0, 0, cnf.stalker.HTTP.screenshots.width, cnf.stalker.HTTP.screenshots.height))
extrema = img.convert("L").getextrema()
if not extrema == (0, 0):
img.save(img_byte_arr, format='PNG')
self._host["data"]["screenshot"] = Binary(zlib.compress(img_byte_arr.getvalue()))
img_byte_arr.close()
self._logger.debug("Saved screen of %s:%s (e: %s)" % (self._host["ip"], self._host["port"], extrema))
else:
self._logger.debug("Not saving screen of %s:%s, as it is empty", self._host["ip"], self._host["port"])

View File

45
lib/plugin/test.py Normal file
View File

@ -0,0 +1,45 @@
from threading import Thread
from time import sleep
class A: # NOOP
def __init__(self, thread = None):
if thread:
self.__thread = Thread(target=thread)
self._running = False
self._init()
def _init(self):
pass
def start(self):
self._running = True
self.__thread.daemon = True
self.__thread.start()
def stop(self):
self._running = False
self.__thread.join()
def __run(self):
while(self._running):
print('NOOP')
sleep(1)
class B(A): # NOOP
def __init__(self):
super().__init__(self.__run)
def __run(self):
while(self._running):
print('OP')
sleep(1)
class C(A): # NOOP
def __run(self):
while(self._running):
print('OP')
sleep(1)
def _init(self):
self.__thread = Thread(target=self.__run)

2
lib/tasks/__init__.py Normal file
View File

@ -0,0 +1,2 @@
#from .scan import scan
#from .stalk import stalk

6
lib/tasks/worker.py Normal file
View File

@ -0,0 +1,6 @@
from lib.plugin import Manager
def worker(host, plugin):
p = Manager.get_plugin(plugin)
p.Plugin.Pipeline(host, plugin)
del p

107
lib/util.py Normal file
View File

@ -0,0 +1,107 @@
import logging
from Config import cnf as config
import importlib
import sys, os
class Logger(logging.Logger):
def __init__(self, name):
self._lf_start = '[%(asctime)s][%(levelname)-7s][%(name)-10s]'
self._lf_end = ' %(message)s'
self._lf_extra = {}
super().__init__(name, level=self.get_level(name))
self._update()
def get_level(self, name):
return logging.DEBUG
def add_field(self, name, default, size=3):
if not name in self._lf_extra:
self._lf_extra[name] = {
'default': default,
'size': size
}
self._update()
def error(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.ERROR):
kwargs['extra'] = {}
for f, fv in self._lf_extra.items():
kwargs['extra'][f] = fv['default']
self._log(logging.ERROR, msg, args, **dict(kwargs))
def warn(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.WARN):
kwargs['extra'] = {}
for f, fv in self._lf_extra.items():
kwargs['extra'][f] = fv['default']
self._log(logging.WARN, msg, args, **dict(kwargs))
def info(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.INFO):
kwargs['extra'] = {}
for f, fv in self._lf_extra.items():
kwargs['extra'][f] = fv['default']
self._log(logging.INFO, msg, args, **dict(kwargs))
def debug(self, msg, *args, **kwargs):
if self.isEnabledFor(logging.DEBUG):
kwargs['extra'] = {}
for f, fv in self._lf_extra.items():
kwargs['extra'][f] = fv['default']
self._log(logging.DEBUG, msg, args, **dict(kwargs))
def del_field(self, name):
if name in self._lf_extra.keys():
del self._lf_extra[name]
self._update()
def _update(self):
self.handlers = []
fields = "".join(['[%(' + name + ')-' + str(f['size']) + 's]' for name, f in self._lf_extra.items()])
lf = logging.Formatter(self._lf_start + fields + self._lf_end)
ch = logging.StreamHandler()
ch.setLevel(self.level)
ch.setFormatter(lf)
self.addHandler(ch)
class Loadable:
def __init__(self, id, root=config):
self.cnf = config
self.lcnf = root[id]
self._id = id
class Loader:
def __init__(self, path):
self._path = path
self._name = path.split('.')[-1]
self._dir = ".".join(path.split('.')[:-1]) # shiiiet
self._logger = Logger('Loader')
self._logger.add_field('path', self._path)
def get(self, name):
sys.path.append( os.path.join( os.path.dirname( __file__ ), '..' ))
self._logger.debug('load %s', name)
result = importlib.import_module(self._path)
return getattr(result, name)
@classmethod
def by_id(cls, section, id):
l = cls(config[section][id].package)
return l.get(config[section][id].service)(id=id, root=config[section])
"""
section:
package: lib.package
service: Service
id:
qwer: asdf
tyui: ghjk
"""

39
medved.py Executable file
View File

@ -0,0 +1,39 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from Config import cnf
from lib import Logger, Loader
class Core:
def __init__(self):
self.cnf = cnf.Core
self.logger = Logger("Core")
self.logger.debug("Loading services")
self._services = []
for service in self.cnf.services:
service = Loader.by_id('services', service)
self._services.append(service)
def start(self):
self.logger.info("Starting")
for service in self._services:
service.start()
self.logger.info("Started")
def stop(self):
self.logger.info("Stopping Core")
for service in self._services:
service.stop()
self.logger.info("Stopped")
if __name__ == '__main__':
core = Core()
core.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
core.stop()

1
ranges/cern Normal file
View File

@ -0,0 +1 @@
188.184.0.0-188.185.255.255

2440
ranges/russia Normal file

File diff suppressed because it is too large Load Diff

35
ranges/syria Normal file
View File

@ -0,0 +1,35 @@
5.0.0.0-5.0.255.255
5.134.224.0-5.134.255.255
31.9.0.0-31.9.255.255
31.193.64.0-31.193.79.255
37.48.128.0-37.48.191.255
37.48.192.0-37.48.223.255
46.53.0.0-46.53.127.255
46.57.128.0-46.57.255.255
46.58.128.0-46.58.255.255
46.161.192.0-46.161.255.255
46.213.0.0-46.213.255.255
77.44.128.0-77.44.255.255
78.110.96.0-78.110.111.255
78.155.64.0-78.155.95.255
82.137.192.0-82.137.255.255
88.86.0.0-88.86.31.255
90.153.128.0-90.153.255.255
91.144.0.0-91.144.63.255
94.141.192.0-94.141.223.255
94.252.128.0-94.252.255.255
95.140.96.0-95.140.111.255
95.159.0.0-95.159.63.255
109.238.144.0-109.238.159.255
130.0.240.0-130.0.255.255
130.180.128.0-130.180.191.255
178.52.0.0-178.52.255.255
178.171.128.0-178.171.255.255
178.253.64.0-178.253.127.255
188.139.128.0-188.139.255.255
188.160.0.0-188.160.255.255
188.229.128.0-188.229.255.255
188.247.0.0-188.247.31.255
212.11.192.0-212.11.223.255
213.178.224.0-213.178.255.255
217.20.208.0-217.20.223.255

14
requirements.txt Normal file
View File

@ -0,0 +1,14 @@
GeoIP
pytelegrambotapi
requests
pillow
netaddr
requests
BeautifulSoup4
selenium
pymongo
urllib3
zmq
jsoncomment
rq
pyyaml