This commit is contained in:
Manuel 'soma' Munz 2013-09-25 14:57:21 +02:00
commit 7d611c05fd
90 changed files with 5172 additions and 0 deletions

674
COPYING 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>.

41
README Normal file
View File

@ -0,0 +1,41 @@
README
this is the repository for fail2ban-p2p. Fail2ban-p2p is a standalone
application written in python that will exchange IPs of attackers detected
by fail2ban (http://www.fail2ban.org) using a p2p-network.
Basic concept:
* Every node in the p2p-network is connected to at least one other 'friend'
* friends exchange their public keys to verify messages signed with the
senders private key.
* Nodes send each other messages when one of them detected an attacker
* Nodes also pass along this information to spread it in the network
* You can assign different trustlevels for friends and a threshold that is
required to ban an attacker locally.
Documentation:
See folder doc/ for documentation about installation and configuration
Directory structure:
config sample configuration
debian necessary files for creating packages for debian
doc/ home of all documentation
fail2ban-p2p/ classes and functions
scripts/ scripts for building fail2ban-p2p releases
tests/ testcases, if any
Short coding styleguide:
- One class per file
- One directory per package
- One tab = 4 spaces
- lower-case variables, if it consists of multiple words, beginning of every
new word is upper-case, e.g.:
donauDampfSchiffFahrtsGesellschaft, protocolVersion, tmp
- the above is also true for function names
- class names behave similarly, except for the fact that they begin with a
capital letter.

11
config/fail2ban-p2p.conf Normal file
View File

@ -0,0 +1,11 @@
[Node]
name=mynodename
addresses=0.0.0.0
port=1337
ownermail=foo@bar.de
bantime=7200
threshold=80
[Logging]
logfile=/var/log/fail2ban-p2p.log
loglevel=INFO

View File

@ -0,0 +1,11 @@
[Node]
name=node1
addresses=localhost
port=10001
ownermail=node1@bar.de
bantime=7200
threshold=80
[Logging]
logfile=/tmp/fail2ban-p2p-node1.log
loglevel=DEBUG

View File

@ -0,0 +1,10 @@
port = 10002
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCeEaRZRyQKMIxYIt7ZYc8wgMu
M9X8wIuQW4TeoX3Hp7NpDmej92YXqAR8Aed4Q9XvCrU+Oq+YApNjI33s9UDu3z42
NPTvKfHPis6XJBa0Uln+bMREWI0v/fILG0mW0CVMrhyRRPeVGVjC1x8TexNzojsx
Ixcd7wC4G6f+Kwpn7wIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC34Wy9nn4kiwhK1oFDIuFpzT0cFZhNiwEtSIkQuK2QlNJiBU2t
14S+ZVsMAej7VmyEeQs1G2rCFtEu1KE54oEaQaq06PEsnwGki1PAOmO/T7MCX+w/
xcQu0m/Wvh8ydbia5mMa37tPDoddiO209yJMYMZKWTc1zGNaf1iy9eWIJQIDAQAB
AoGAfnDzPjxjDyvPau6vegPdLsyjbdFnpkKkb4gGQEpNhzLeq+prrNObAvVdMxeJ
JnMaMcmuLDmLIqVf+CzcJJqdHM93sPrJXN9qTKh05BNK3S8qc+Ns1RTVF93QyWHi
b9q4K6YyT7EInC7Ve5TP9/uH6ouYDwHanToXJTZGNVq6uI0CQQDewo0SNzzV7bDY
pkQ197GvcRYMejkoZQqdGNYx+JDKe0eoC8D+ON6LX6u9T+HPKSG6HxdwlVTuTmKX
ZxO11yQnAkEA01Gtbb7Ok9OD+jM13BtLPoSKS4uQNV5jOvogpStu5OGdNx2Yoima
jueUeFK9HLzMLDJmjWQvin0QsD9+t6Dk0wJACjGO8RF0CDobSJ67KlkOWX/sSV/i
c7XD+ZJkYt8ECTABBHCdQUTq8ifLnRslsywnrfO0R+OdglY17sW5wi15KwJBAL+c
gxZM+oGePECFaOQBN7QjeEbR8NwDjxSuMyWxgWc2kFimlH0OHmBP6hdEZsgFBVla
BhVU76qyhoxZtqwIzxMCQQC2MAX7u73wlcI+S1rJNSBuKCGD7G9nQagm+bddkdcw
hJrn7KaKr6SlEVntgvgMz/vgo4DLewBiRDdZTX6Vw/Js
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC34Wy9nn4kiwhK1oFDIuFpzT0c
FZhNiwEtSIkQuK2QlNJiBU2t14S+ZVsMAej7VmyEeQs1G2rCFtEu1KE54oEaQaq0
6PEsnwGki1PAOmO/T7MCX+w/xcQu0m/Wvh8ydbia5mMa37tPDoddiO209yJMYMZK
WTc1zGNaf1iy9eWIJQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,11 @@
[Node]
name=node2
addresses=0.0.0.0
port=10002
ownermail=node2@bar.de
bantime=7200
threshold=80
[Logging]
logfile=/tmp/fail2ban-p2p-node2.log
loglevel=DEBUG

View File

@ -0,0 +1,10 @@
port = 10001
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC34Wy9nn4kiwhK1oFDIuFpzT0c
FZhNiwEtSIkQuK2QlNJiBU2t14S+ZVsMAej7VmyEeQs1G2rCFtEu1KE54oEaQaq0
6PEsnwGki1PAOmO/T7MCX+w/xcQu0m/Wvh8ydbia5mMa37tPDoddiO209yJMYMZK
WTc1zGNaf1iy9eWIJQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,11 @@
port = 10003
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0K7I6d7DfFILfabjFZYDmYJk8
KlEHkEPNFkCLJSt0NlOGxMt9yqqNWi3pht+6a3uW0nfqU6NZc3fxpnFOHvXfI8Rl
cBRPdaGUJs2A3qbEfKVSUAF+L8Zq7XI6oHyEAjc59/tFaGQHtnK9ntJqhIIZNiDT
jrDAxZ8412gntLtLpQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,10 @@
port = 10004
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLEqAEUCL+IM36ijGxRwx5AqpU
J3hc7mT6MCNtLmaLoC36lC+fzmp6PKIaEdLeurQ21nj9GFLN7tSvVXZdaHWo5V2Q
06HgcO6lGi8wjoT8Gw3E2H1dCAgjm2pFON2uDfruqgQqnHL2/Bd7div0c+utfplv
zqdwrm+BQ1yyD8PTLQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDCeEaRZRyQKMIxYIt7ZYc8wgMuM9X8wIuQW4TeoX3Hp7NpDmej
92YXqAR8Aed4Q9XvCrU+Oq+YApNjI33s9UDu3z42NPTvKfHPis6XJBa0Uln+bMRE
WI0v/fILG0mW0CVMrhyRRPeVGVjC1x8TexNzojsxIxcd7wC4G6f+Kwpn7wIDAQAB
AoGBAIicIUaF9vi2CSTSo2k9uzDNQZq1Qz9YqzHveHlEjK0ye2/zdI7Ufl1j5DKQ
y9/KF4Dizss2Qp/QP2VHS3CoIMHze2eeEEt7Qu8ZJhJGYRjGQ3rS1s4V3vr+TGyv
sabhYDVPGOxG0XBlMU4ZAWCwx3aiSorqiN5ryF1vd0Kc8bUhAkEA42LkXHikbBty
MKjPUrsqjZpv+BF7rXnNuPeHGoP48cUG66yRr7XfVRyO90AfamiUlj0AX8aNTJCy
OATnQ7ABNwJBANrxAAHhGPRGB/Z2GfTy9WonNimZQWWSt6PhIag72sYl3vsWfKdu
LVmM+u6WVVSmmp6CQnv2RClEaOnqrS8bCwkCQEm4xlE0zBpAy8T69jzcce93ItZK
1M5pr0lI94ShRRUdzCCc0p8lWEM//xoqsATP41zSakyjEyy/vQhsjo5jggECQHjm
qJhhEwShP3hsEz1ehQMPkCs8hA5xDJOkmI9sLg1JkG6bJk7W2pge79qcjZZnQe7S
A6Csh0s6iazSeLwQdPECQQCeQVUc2RN36ImChnEJxmtcSpgQfat1F/FKuOvozuvp
fZs5pVYgwzIhM2B499bYzc+b1r0e5JYmo4oqbrt3FDEe
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCeEaRZRyQKMIxYIt7ZYc8wgMu
M9X8wIuQW4TeoX3Hp7NpDmej92YXqAR8Aed4Q9XvCrU+Oq+YApNjI33s9UDu3z42
NPTvKfHPis6XJBa0Uln+bMREWI0v/fILG0mW0CVMrhyRRPeVGVjC1x8TexNzojsx
Ixcd7wC4G6f+Kwpn7wIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,11 @@
[Node]
name=node3
addresses=0.0.0.0
port=10003
ownermail=node3@bar.de
bantime=7200
threshold=80
[Logging]
logfile=/tmp/fail2ban-p2p-node3.log
loglevel=DEBUG

View File

@ -0,0 +1,10 @@
port = 10002
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCeEaRZRyQKMIxYIt7ZYc8wgMu
M9X8wIuQW4TeoX3Hp7NpDmej92YXqAR8Aed4Q9XvCrU+Oq+YApNjI33s9UDu3z42
NPTvKfHPis6XJBa0Uln+bMREWI0v/fILG0mW0CVMrhyRRPeVGVjC1x8TexNzojsx
Ixcd7wC4G6f+Kwpn7wIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,10 @@
port = 10004
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLEqAEUCL+IM36ijGxRwx5AqpU
J3hc7mT6MCNtLmaLoC36lC+fzmp6PKIaEdLeurQ21nj9GFLN7tSvVXZdaHWo5V2Q
06HgcO6lGi8wjoT8Gw3E2H1dCAgjm2pFON2uDfruqgQqnHL2/Bd7div0c+utfplv
zqdwrm+BQ1yyD8PTLQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQD0K7I6d7DfFILfabjFZYDmYJk8KlEHkEPNFkCLJSt0NlOGxMt9
yqqNWi3pht+6a3uW0nfqU6NZc3fxpnFOHvXfI8RlcBRPdaGUJs2A3qbEfKVSUAF+
L8Zq7XI6oHyEAjc59/tFaGQHtnK9ntJqhIIZNiDTjrDAxZ8412gntLtLpQIDAQAB
AoGAapl5IlWG/p2x1WAOrv91mx6pR78hyS+OqkcAvr7njcD6Dmh0fuKwOy4XxVCA
9J5gQqR4ffEt66uhvfpwlS6nIH3neVVqV5zfe12jbh55zKeZoYXe1zDYENKk7B4g
f5BgNVaepiL7ssM98fe0a/hgbc01xUjk4IYdS+eEAd2lvoECQQD8wZIxLrKpiUDl
O4M8LTCcMEirfaORN+XaCYGzIontArMmccsKn9oZkbBcIKnR5IOW4ZkIxpu5qKCv
nv3tqTR5AkEA903q7h+nQTSPjQZOyZfc8h3YXYq3TFsKQkb7+ALZ1DbNQxigwOLM
T79BiKQMYnrioC5r0RaeM76aHdZSPYlNjQJBAPrb0BH6TB6R+BPLxkuyej16epWi
I/ZcaUfHCbBWRlgyxsYQSLnpv5iDDWvSi1mjmKrmi3G3VRWmdJz5iwMXXdkCQFCk
xPZPth/KPwFyzCBq+C6v0s12HZ21llvUf/f5HgVYtYiqsEkV7CAZMwqWzD8U6W/o
k1oEcSRYhDM0n27XpkUCQQDaWG5P9s3tZ69hc83BCr3iHtXNtbgA9/zj8zwCTmD2
nrBJTDMNyNqpdl8lcTC1Vzgv+Ha5u+1UDIzxmsigm0SM
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0K7I6d7DfFILfabjFZYDmYJk8
KlEHkEPNFkCLJSt0NlOGxMt9yqqNWi3pht+6a3uW0nfqU6NZc3fxpnFOHvXfI8Rl
cBRPdaGUJs2A3qbEfKVSUAF+L8Zq7XI6oHyEAjc59/tFaGQHtnK9ntJqhIIZNiDT
jrDAxZ8412gntLtLpQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,11 @@
[Node]
name=node4
addresses=0.0.0.0
port=10004
ownermail=node4@bar.de
bantime=7200
threshold=80
[Logging]
logfile=/tmp/fail2ban-p2p-node4.log
loglevel=DEBUG

View File

@ -0,0 +1,10 @@
port = 10002
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCeEaRZRyQKMIxYIt7ZYc8wgMu
M9X8wIuQW4TeoX3Hp7NpDmej92YXqAR8Aed4Q9XvCrU+Oq+YApNjI33s9UDu3z42
NPTvKfHPis6XJBa0Uln+bMREWI0v/fILG0mW0CVMrhyRRPeVGVjC1x8TexNzojsx
Ixcd7wC4G6f+Kwpn7wIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,11 @@
port = 10003
trustlevel = 80
address = 127.0.0.1
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0K7I6d7DfFILfabjFZYDmYJk8
KlEHkEPNFkCLJSt0NlOGxMt9yqqNWi3pht+6a3uW0nfqU6NZc3fxpnFOHvXfI8Rl
cBRPdaGUJs2A3qbEfKVSUAF+L8Zq7XI6oHyEAjc59/tFaGQHtnK9ntJqhIIZNiDT
jrDAxZ8412gntLtLpQIDAQAB
-----END PUBLIC KEY-----

View File

@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXwIBAAKBgQDLEqAEUCL+IM36ijGxRwx5AqpUJ3hc7mT6MCNtLmaLoC36lC+f
zmp6PKIaEdLeurQ21nj9GFLN7tSvVXZdaHWo5V2Q06HgcO6lGi8wjoT8Gw3E2H1d
CAgjm2pFON2uDfruqgQqnHL2/Bd7div0c+utfplvzqdwrm+BQ1yyD8PTLQIDAQAB
AoGBAKbxb9U74BiU9WCzfTilFQ7ibw5xyFR1s1OugWE/lRPSIhpu+lvhAM3uzMCr
yHRMftzaImrHNUOQxQ5DLuSJfLdedB8ar/P5lwJn6bGt7N9XqzCSCE0x8fvfsGBM
Vtc5ed+DA/WgiWcqQ1aPDCgRV8f1tVxOCabQqKqpXVxqSYNNAkEA7Rcn/BpSKQ/G
a0/JmcRVpjMEKivXpz/JC6twGHkfa7PqbgmfyCC1acWWjerhHwN60IA58grVtakA
2tAOiEjrowJBANtE58flh3DPZN9UIYrSxEPkUQD9020S9rMO0M8H9yvqXajEq7ek
BvelBNTHZZy0MM91KtdLgaFVt4pndq5OMu8CQQDJvRtr26WvhNnMNB8R9Ur/2Ycg
rx+YE6FpiZ4fZOkEhxniOdQ4wQQ8lUFvTr3x2s8lHQaxWuDP65drmP/UnV/LAkEA
iGwTpVxaa0at5QFMKTo/IFqCR5KlI7zjvr4eDmFPWIRlp2ZNzGECcLu8CMLSpq+5
mqm0cOUqjv1sx3Dd907yAwJBAK2bdFJIm+IAt5vv82s2m2/WEXUmvJg8t8/ICOuj
atOa2zNDL3T0aP0saXENBkudlbujMUnmAw4FNnWDQuhiLAA=
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLEqAEUCL+IM36ijGxRwx5AqpU
J3hc7mT6MCNtLmaLoC36lC+fzmp6PKIaEdLeurQ21nj9GFLN7tSvVXZdaHWo5V2Q
06HgcO6lGi8wjoT8Gw3E2H1dCAgjm2pFON2uDfruqgQqnHL2/Bd7div0c+utfplv
zqdwrm+BQ1yyD8PTLQIDAQAB
-----END PUBLIC KEY-----

6
debian/README.Debian vendored Normal file
View File

@ -0,0 +1,6 @@
fail2ban-p2p for Debian
-----------------------
<possible notes regarding this package - if none, delete this file>
-- Manuel Munz <manu@somakoma.de> Wed, 07 Nov 2012 16:40:08 +0100

9
debian/README.source vendored Normal file
View File

@ -0,0 +1,9 @@
fail2ban-p2p for Debian
-----------------------
<this file describes information about the source package, see Debian policy
manual section 4.14. You WILL either need to modify or delete this file>

56
debian/changelog vendored Normal file
View File

@ -0,0 +1,56 @@
fail2ban-p2p (0.1.2) precise; urgency=low
* Better input filtering and error messages for invalid messages
* document classes and functions in code
* add sphinx for generating documentation
* reorder modules to resolve circular imports
* general cleanups
* client: fix an exception when the message received from the server was not valid json
-- Manuel Munz <manu@somakoma.de> Fri, 24 May 2013 15:23:49 +0200
fail2ban-p2p (0.1.1) precise; urgency=low
* 0.1.1 Fix problem with table dump in fail2ban-p2p-client
-- Manuel Munz <manu@somakoma.de> Tue, 16 Apr 2013 18:00:24 +0200
fail2ban-p2p (0.1.0) precise; urgency=low
* fix trustlevels handling
* pull banlists from friends when starting the node
-- Manuel Munz <manu@somakoma.de> Thu, 11 Apr 2013 16:14:53 +0200
fail2ban-p2p (0.0.5-1) oneiric; urgency=low
* Change in message protocol. Use JSON encoded messages now.
* Warning: This beraks compatibility with earlier versions.
-- Manuel Munz <manu@somakoma.de> Thu, 21 Mar 2013 18:42:32 +0100
fail2ban-p2p (0.0.4-1) oneiric; urgency=low
* removed dummy signature check, fixes crash when 'signature' was sent as signature
* fix permissions on private keyfile
* more log output
-- Manuel Munz <manu@somakoma.de> Wed, 23 Jan 2013 16:07:55 +0100
fail2ban-p2p (0.0.3-1) oneiric; urgency=low
* Update to 0.0.3
-- Manuel Munz <manu@somakoma.de> Wed, 23 Jan 2013 15:53:43 +0100
fail2ban-p2p (0.0.2-1) oneiric; urgency=low
* Update to 0.0.2
-- Manuel Munz <manu@somakoma.de> Wed, 23 Jan 2013 15:53:30 +0100
fail2ban-p2p (0.0.1-1) unstable; urgency=low
* Initial release (Closes: #nnnn) <nnnn is the bug number of your ITP>
-- Manuel Munz <manu@somakoma.de> Wed, 07 Nov 2012 16:40:08 +0100

1
debian/compat vendored Normal file
View File

@ -0,0 +1 @@
8

19
debian/control vendored Normal file
View File

@ -0,0 +1,19 @@
Source: fail2ban-p2p
Section: net
Priority: optional
Maintainer: Manuel Munz <manu@somakoma.de>
Build-Depends: debhelper (>= 8.0.0), python (>= 2.5.4-1~)
Build-Depends-Indep: python-central (>= 0.5.6)
XS-Python-Version: current, >= 2.4
Standards-Version: 3.9.2
#Homepage:
#Vcs-Git: git://git.debian.org/collab-maint/fail2ban-p2p.git
#Vcs-Browser: http://git.debian.org/?p=collab-maint/fail2ban-p2p.git;a=summary
Package: fail2ban-p2p
Architecture: all
Depends: ${shlibs:Depends}, ${misc:Depends}, ${python:Depends}, python-m2crypto, python-argparse, adduser
XB-Python-Version: ${python:Versions}
Description: Distribute attacker information from fail2ban via a p2p network
Fail2ban-p2p can be used to distribute information about atackers in a
p2p/f2f network to ban these attackers on all hosts.

26
debian/copyright vendored Normal file
View File

@ -0,0 +1,26 @@
This package was originally debianized by Manuel Munz
<manu@somakoma.de> on Wed Nov 11 15:50:00 HST 2012
Copyright: 2012- Manuel Munz/Johannes Fürmann
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 2 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, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301, USA.
On Debian systems, the complete text of the GNU General Public
License, version 2, can be found in /usr/share/common-licenses/GPL-2.
The Debian packaging is (C) 2011-, Manuel Munz <manu@somakoma.de>
and is licensed under the GPL, see above.

1
debian/docs vendored Normal file
View File

@ -0,0 +1 @@
README

45
debian/emacsen-install.ex vendored Normal file
View File

@ -0,0 +1,45 @@
#! /bin/sh -e
# /usr/lib/emacsen-common/packages/install/fail2ban-p2p
# Written by Jim Van Zandt <jrv@debian.org>, borrowing heavily
# from the install scripts for gettext by Santiago Vila
# <sanvila@ctv.es> and octave by Dirk Eddelbuettel <edd@debian.org>.
FLAVOR=$1
PACKAGE=fail2ban-p2p
if [ ${FLAVOR} = emacs ]; then exit 0; fi
echo install/${PACKAGE}: Handling install for emacsen flavor ${FLAVOR}
#FLAVORTEST=`echo $FLAVOR | cut -c-6`
#if [ ${FLAVORTEST} = xemacs ] ; then
# SITEFLAG="-no-site-file"
#else
# SITEFLAG="--no-site-file"
#fi
FLAGS="${SITEFLAG} -q -batch -l path.el -f batch-byte-compile"
ELDIR=/usr/share/emacs/site-lisp/${PACKAGE}
ELCDIR=/usr/share/${FLAVOR}/site-lisp/${PACKAGE}
# Install-info-altdir does not actually exist.
# Maybe somebody will write it.
if test -x /usr/sbin/install-info-altdir; then
echo install/${PACKAGE}: install Info links for ${FLAVOR}
install-info-altdir --quiet --section "" "" --dirname=${FLAVOR} /usr/share/info/${PACKAGE}.info.gz
fi
install -m 755 -d ${ELCDIR}
cd ${ELDIR}
FILES=`echo *.el`
cp ${FILES} ${ELCDIR}
cd ${ELCDIR}
cat << EOF > path.el
(setq load-path (cons "." load-path) byte-compile-warnings nil)
EOF
${FLAVOR} ${FLAGS} ${FILES}
rm -f *.el path.el
exit 0

15
debian/emacsen-remove.ex vendored Normal file
View File

@ -0,0 +1,15 @@
#!/bin/sh -e
# /usr/lib/emacsen-common/packages/remove/fail2ban-p2p
FLAVOR=$1
PACKAGE=fail2ban-p2p
if [ ${FLAVOR} != emacs ]; then
if test -x /usr/sbin/install-info-altdir; then
echo remove/${PACKAGE}: removing Info links for ${FLAVOR}
install-info-altdir --quiet --remove --dirname=${FLAVOR} /usr/share/info/fail2ban-p2p.info.gz
fi
echo remove/${PACKAGE}: purging byte-compiled files for ${FLAVOR}
rm -rf /usr/share/${FLAVOR}/site-lisp/${PACKAGE}
fi

25
debian/emacsen-startup.ex vendored Normal file
View File

@ -0,0 +1,25 @@
;; -*-emacs-lisp-*-
;;
;; Emacs startup file, e.g. /etc/emacs/site-start.d/50fail2ban-p2p.el
;; for the Debian fail2ban-p2p package
;;
;; Originally contributed by Nils Naumann <naumann@unileoben.ac.at>
;; Modified by Dirk Eddelbuettel <edd@debian.org>
;; Adapted for dh-make by Jim Van Zandt <jrv@debian.org>
;; The fail2ban-p2p package follows the Debian/GNU Linux 'emacsen' policy and
;; byte-compiles its elisp files for each 'emacs flavor' (emacs19,
;; xemacs19, emacs20, xemacs20...). The compiled code is then
;; installed in a subdirectory of the respective site-lisp directory.
;; We have to add this to the load-path:
(let ((package-dir (concat "/usr/share/"
(symbol-name flavor)
"/site-lisp/fail2ban-p2p")))
;; If package-dir does not exist, the fail2ban-p2p package must have
;; removed but not purged, and we should skip the setup.
(when (file-directory-p package-dir)
(setq load-path (cons package-dir load-path))
(autoload 'fail2ban-p2p-mode "fail2ban-p2p-mode"
"Major mode for editing fail2ban-p2p files." t)
(add-to-list 'auto-mode-alist '("\\.fail2ban-p2p$" . fail2ban-p2p-mode))))

1
debian/fail2ban-p2p-doc.docs vendored Normal file
View File

@ -0,0 +1 @@
#DOCS#

1
debian/fail2ban-p2p-doc.install vendored Normal file
View File

@ -0,0 +1 @@
#DOCS#

4
debian/fail2ban-p2p.cron.d.ex vendored Normal file
View File

@ -0,0 +1,4 @@
#
# Regular cron jobs for the fail2ban-p2p package
#
0 4 * * * root [ -x /usr/bin/fail2ban-p2p_maintenance ] && /usr/bin/fail2ban-p2p_maintenance

12
debian/fail2ban-p2p.debhelper.log vendored Normal file
View File

@ -0,0 +1,12 @@
dh_installdirs
dh_installdocs
dh_installlogrotate
dh_pycentral
dh_installinit
dh_link
dh_compress
dh_fixperms
dh_installdeb
dh_gencontrol
dh_md5sums
dh_builddeb

13
debian/fail2ban-p2p.default vendored Normal file
View File

@ -0,0 +1,13 @@
# Defaults for fail2ban-p2p initscript
# sourced by /etc/init.d/fail2ban-p2p
# installed at /etc/default/fail2ban-p2p by the maintainer scripts
#
# This is a POSIX shell fragment
#
# Additional options that are passed to the Daemon.
DAEMON_OPTS=""
# Set this to true to start the daemon at boot
START_DAEMON=false

20
debian/fail2ban-p2p.doc-base.EX vendored Normal file
View File

@ -0,0 +1,20 @@
Document: fail2ban-p2p
Title: Debian fail2ban-p2p Manual
Author: <insert document author here>
Abstract: This manual describes what fail2ban-p2p is
and how it can be used to
manage online manuals on Debian systems.
Section: unknown
Format: debiandoc-sgml
Files: /usr/share/doc/fail2ban-p2p/fail2ban-p2p.sgml.gz
Format: postscript
Files: /usr/share/doc/fail2ban-p2p/fail2ban-p2p.ps.gz
Format: text
Files: /usr/share/doc/fail2ban-p2p/fail2ban-p2p.text.gz
Format: HTML
Index: /usr/share/doc/fail2ban-p2p/html/index.html
Files: /usr/share/doc/fail2ban-p2p/html/*.html

15
debian/fail2ban-p2p.postinst.debhelper vendored Normal file
View File

@ -0,0 +1,15 @@
# Automatically added by dh_pycentral
rm -f /var/lib/pycentral/fail2ban-p2p.pkgremove
if which pycentral >/dev/null 2>&1; then
pycentral pkginstall fail2ban-p2p
if grep -qs '^fail2ban-p2p$' /var/lib/pycentral/delayed-pkgs; then
sed -i '/^fail2ban-p2p$/d' /var/lib/pycentral/delayed-pkgs
fi
fi
# End automatically added section
# Automatically added by dh_installinit
if [ -x "/etc/init.d/fail2ban-p2p" ]; then
update-rc.d fail2ban-p2p defaults 99 >/dev/null
invoke-rc.d fail2ban-p2p start || exit $?
fi
# End automatically added section

5
debian/fail2ban-p2p.postrm.debhelper vendored Normal file
View File

@ -0,0 +1,5 @@
# Automatically added by dh_installinit
if [ "$1" = "purge" ] ; then
update-rc.d fail2ban-p2p remove >/dev/null
fi
# End automatically added section

8
debian/fail2ban-p2p.preinst.debhelper vendored Normal file
View File

@ -0,0 +1,8 @@
# Automatically added by dh_pycentral
case "$1" in
install|upgrade)
mkdir -p /var/lib/pycentral
echo '# the presence of this file allows calling pkgremove on upgrade' \
> /var/lib/pycentral/fail2ban-p2p.pkgremove
esac
# End automatically added section

50
debian/fail2ban-p2p.prerm.debhelper vendored Normal file
View File

@ -0,0 +1,50 @@
# Automatically added by dh_installinit
if [ -x "/etc/init.d/fail2ban-p2p" ]; then
invoke-rc.d fail2ban-p2p stop || exit $?
fi
# End automatically added section
# Automatically added by dh_pycentral
case "$1" in remove|upgrade)
pkgremove=y
esac
if [ -f /var/lib/pycentral/fail2ban-p2p.pkgremove ] || [ -f /var/lib/pycentral/pkgremove ]; then
pkgremove=y
fi
if [ "$pkgremove" = y ]; then
if which python >/dev/null 2>&1 && which pycentral >/dev/null 2>&1; then
pycentral pkgremove fail2ban-p2p
else
flist=$(tempfile)
slist=$(tempfile)
dpkg -L fail2ban-p2p | tee $flist | \
while read n; do
case "$n" in
/usr/share/pyshared/*)
n2=${n#/usr/share/pyshared/*}
case "$n" in
*.py) echo "p $n";;
*) [ -d "$n" ] && echo "d $n2" || echo "f $n2"
esac
;;
*) continue
esac
done > $slist
if [ -s $slist ]; then
for d in /usr/lib/python[0-9].[0-9]/????-packages; do
case "$d" in */python2.1/*|*/python2.2/*) continue; esac
while read t n; do
case "$t" in
p) rm -f $d/$n $d/${n}[co];;
d) rmdir $d/$n 2>/dev/null || true;;
*) rm -f $d/$n
esac
done < $slist
done
fi
awk '/\/usr\/share\/pyshared/ {next} /\.py$/ {print $0"c\n" $0"o"}' $flist \
| xargs -r rm -f >&2
rm -f $flist $slist
fi
rm -f /var/lib/pycentral/fail2ban-p2p.pkgremove
fi
# End automatically added section

3
debian/fail2ban-p2p.substvars vendored Normal file
View File

@ -0,0 +1,3 @@
python:Versions=current, >= 2.4
python:Depends=python (>= 2.4), python-central (>= 0.6.11)
misc:Depends=

1
debian/files vendored Normal file
View File

@ -0,0 +1 @@
fail2ban-p2p_0.0.1-1_all.deb net optional

161
debian/init.d vendored Normal file
View File

@ -0,0 +1,161 @@
#!/bin/sh
### BEGIN INIT INFO
# Provides: fail2ban-p2p
# Required-Start: $network $local_fs
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: <Enter a short description of the sortware>
# Description: <Enter a long description of the software>
# <...>
# <...>
### END INIT INFO
# Author: Manuel Munz <manu@somakoma.de>
# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=fail2ban-p2p # Introduce a short description here
NAME=fail2ban-p2p # Introduce the short server's name here
DAEMON=/usr/bin/fail2ban-p2p.py # Introduce the server's location here
DAEMON_ARGS="" # Arguments to run the daemon with
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
# Exit if the package is not installed
[ -x $DAEMON ] || exit 0
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
if [ ! "$START_DAEMON" = "true" ]; then
echo "Fail2ban-p2p is not started. Enable it by editing /etc/default/fail2ban-p2p"
exit 0
fi
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions
#
# Function that starts the daemon/service
#
do_start()
{
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started
start-stop-daemon -m -c fail2ban-p2p -g fail2ban-p2p -b --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
|| return 1
start-stop-daemon -c fail2ban-p2p -g fail2ban-p2p -m -b --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
$DAEMON_ARGS \
|| return 2
# Add code here, if necessary, that waits for the process to be ready
# to handle requests from services started subsequently which depend
# on this one. As a last resort, sleep for some time.
}
#
# Function that stops the daemon/service
#
do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred
start-stop-daemon --stop --quiet --retry=TERM/10/KILL/5 --pidfile $PIDFILE --name ${NAME}.py
RETVAL="$?"
[ "$RETVAL" = 2 ] && return 2
# Wait for children to finish too if this is a daemon that forks
# and if the daemon is only ever run from this initscript.
# If the above conditions are not satisfied then add some other code
# that waits for the process to drop all resources that could be
# needed by services started subsequently. A last resort is to
# sleep for some time.
start-stop-daemon --stop --quiet --oknodo --retry=0/10/KILL/9 --exec $DAEMON
[ "$?" = 2 ] && return 2
# Many daemons don't delete their pidfiles when they exit.
rm -f $PIDFILE
return "$RETVAL"
}
#
# Function that sends a SIGHUP to the daemon/service
#
#VERBOSE="yes"
do_reload() {
#
# If the daemon can reload its configuration without
# restarting (for example, when it is sent a SIGHUP),
# then implement that here.
#
do_start
do_stop
return 0
}
case "$1" in
start)
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC " "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
status)
status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
;;
#reload|force-reload)
#
# If do_reload() is not implemented then leave this commented out
# and leave 'force-reload' as an alias for 'restart'.
#
#log_daemon_msg "Reloading $DESC" "$NAME"
#do_reload
#log_end_msg $?
#;;
restart|force-reload)
#
# If the "reload" option is implemented then remove the
# 'force-reload' alias
#
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
*)
#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
exit 3
;;
esac
:

59
debian/manpage.1.ex vendored Normal file
View File

@ -0,0 +1,59 @@
.\" Hey, EMACS: -*- nroff -*-
.\" First parameter, NAME, should be all caps
.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
.\" other parameters are allowed: see man(7), man(1)
.TH FAIL2BAN-P2P SECTION "November 7, 2012"
.\" Please adjust this date whenever revising the manpage.
.\"
.\" Some roff macros, for reference:
.\" .nh disable hyphenation
.\" .hy enable hyphenation
.\" .ad l left justify
.\" .ad b justify to both left and right margins
.\" .nf disable filling
.\" .fi enable filling
.\" .br insert line break
.\" .sp <n> insert n+1 empty lines
.\" for manpage-specific macros, see man(7)
.SH NAME
fail2ban-p2p \- program to do something
.SH SYNOPSIS
.B fail2ban-p2p
.RI [ options ] " files" ...
.br
.B bar
.RI [ options ] " files" ...
.SH DESCRIPTION
This manual page documents briefly the
.B fail2ban-p2p
and
.B bar
commands.
.PP
.\" TeX users may be more comfortable with the \fB<whatever>\fP and
.\" \fI<whatever>\fP escape sequences to invode bold face and italics,
.\" respectively.
\fBfail2ban-p2p\fP is a program that...
.SH OPTIONS
These programs follow the usual GNU command line syntax, with long
options starting with two dashes (`-').
A summary of options is included below.
For a complete description, see the Info files.
.TP
.B \-h, \-\-help
Show summary of options.
.TP
.B \-v, \-\-version
Show version of program.
.SH SEE ALSO
.BR bar (1),
.BR baz (1).
.br
The programs are documented fully by
.IR "The Rise and Fall of a Fooish Bar" ,
available via the Info system.
.SH AUTHOR
fail2ban-p2p was written by <upstream author>.
.PP
This manual page was written by Manuel Munz <manu@somakoma.de>,
for the Debian project (and may be used by others).

154
debian/manpage.sgml.ex vendored Normal file
View File

@ -0,0 +1,154 @@
<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [
<!-- Process this file with docbook-to-man to generate an nroff manual
page: `docbook-to-man manpage.sgml > manpage.1'. You may view
the manual page with: `docbook-to-man manpage.sgml | nroff -man |
less'. A typical entry in a Makefile or Makefile.am is:
manpage.1: manpage.sgml
docbook-to-man $< > $@
The docbook-to-man binary is found in the docbook-to-man package.
Please remember that if you create the nroff version in one of the
debian/rules file targets (such as build), you will need to include
docbook-to-man in your Build-Depends control field.
-->
<!-- Fill in your name for FIRSTNAME and SURNAME. -->
<!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>">
<!ENTITY dhsurname "<surname>SURNAME</surname>">
<!-- Please adjust the date whenever revising the manpage. -->
<!ENTITY dhdate "<date>November 7, 2012</date>">
<!-- SECTION should be 1-8, maybe w/ subsection other parameters are
allowed: see man(7), man(1). -->
<!ENTITY dhsection "<manvolnum>SECTION</manvolnum>">
<!ENTITY dhemail "<email>manu@somakoma.de</email>">
<!ENTITY dhusername "Manuel Munz">
<!ENTITY dhucpackage "<refentrytitle>FAIL2BAN-P2P</refentrytitle>">
<!ENTITY dhpackage "fail2ban-p2p">
<!ENTITY debian "<productname>Debian</productname>">
<!ENTITY gnu "<acronym>GNU</acronym>">
<!ENTITY gpl "&gnu; <acronym>GPL</acronym>">
]>
<refentry>
<refentryinfo>
<address>
&dhemail;
</address>
<author>
&dhfirstname;
&dhsurname;
</author>
<copyright>
<year>2003</year>
<holder>&dhusername;</holder>
</copyright>
&dhdate;
</refentryinfo>
<refmeta>
&dhucpackage;
&dhsection;
</refmeta>
<refnamediv>
<refname>&dhpackage;</refname>
<refpurpose>program to do something</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>&dhpackage;</command>
<arg><option>-e <replaceable>this</replaceable></option></arg>
<arg><option>--example <replaceable>that</replaceable></option></arg>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1>
<title>DESCRIPTION</title>
<para>This manual page documents briefly the
<command>&dhpackage;</command> and <command>bar</command>
commands.</para>
<para>This manual page was written for the &debian; distribution
because the original program does not have a manual page.
Instead, it has documentation in the &gnu;
<application>Info</application> format; see below.</para>
<para><command>&dhpackage;</command> is a program that...</para>
</refsect1>
<refsect1>
<title>OPTIONS</title>
<para>These programs follow the usual &gnu; command line syntax,
with long options starting with two dashes (`-'). A summary of
options is included below. For a complete description, see the
<application>Info</application> files.</para>
<variablelist>
<varlistentry>
<term><option>-h</option>
<option>--help</option>
</term>
<listitem>
<para>Show summary of options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-v</option>
<option>--version</option>
</term>
<listitem>
<para>Show version of program.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1>
<title>SEE ALSO</title>
<para>bar (1), baz (1).</para>
<para>The programs are documented fully by <citetitle>The Rise and
Fall of a Fooish Bar</citetitle> available via the
<application>Info</application> system.</para>
</refsect1>
<refsect1>
<title>AUTHOR</title>
<para>This manual page was written by &dhusername; &dhemail; for
the &debian; system (and may be used by others). Permission is
granted to copy, distribute and/or modify this document under
the terms of the &gnu; General Public License, Version 2 any
later version published by the Free Software Foundation.
</para>
<para>
On Debian systems, the complete text of the GNU General Public
License can be found in /usr/share/common-licenses/GPL.
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:2
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:nil
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
-->

291
debian/manpage.xml.ex vendored Normal file
View File

@ -0,0 +1,291 @@
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!--
`xsltproc -''-nonet \
-''-param man.charmap.use.subset "0" \
-''-param make.year.ranges "1" \
-''-param make.single.year.ranges "1" \
/usr/share/xml/docbook/stylesheet/docbook-xsl/manpages/docbook.xsl \
manpage.xml'
A manual page <package>.<section> will be generated. You may view the
manual page with: nroff -man <package>.<section> | less'. A typical entry
in a Makefile or Makefile.am is:
DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/docbook-xsl/manpages/docbook.xsl
XP = xsltproc -''-nonet -''-param man.charmap.use.subset "0"
manpage.1: manpage.xml
$(XP) $(DB2MAN) $<
The xsltproc binary is found in the xsltproc package. The XSL files are in
docbook-xsl. A description of the parameters you can use can be found in the
docbook-xsl-doc-* packages. Please remember that if you create the nroff
version in one of the debian/rules file targets (such as build), you will need
to include xsltproc and docbook-xsl in your Build-Depends control field.
Alternatively use the xmlto command/package. That will also automatically
pull in xsltproc and docbook-xsl.
Notes for using docbook2x: docbook2x-man does not automatically create the
AUTHOR(S) and COPYRIGHT sections. In this case, please add them manually as
<refsect1> ... </refsect1>.
To disable the automatic creation of the AUTHOR(S) and COPYRIGHT sections
read /usr/share/doc/docbook-xsl/doc/manpages/authors.html. This file can be
found in the docbook-xsl-doc-html package.
Validation can be done using: `xmllint -''-noout -''-valid manpage.xml`
General documentation about man-pages and man-page-formatting:
man(1), man(7), http://www.tldp.org/HOWTO/Man-Page/
-->
<!-- Fill in your name for FIRSTNAME and SURNAME. -->
<!ENTITY dhfirstname "FIRSTNAME">
<!ENTITY dhsurname "SURNAME">
<!-- dhusername could also be set to "&dhfirstname; &dhsurname;". -->
<!ENTITY dhusername "Manuel Munz">
<!ENTITY dhemail "manu@somakoma.de">
<!-- SECTION should be 1-8, maybe w/ subsection other parameters are
allowed: see man(7), man(1) and
http://www.tldp.org/HOWTO/Man-Page/q2.html. -->
<!ENTITY dhsection "SECTION">
<!-- TITLE should be something like "User commands" or similar (see
http://www.tldp.org/HOWTO/Man-Page/q2.html). -->
<!ENTITY dhtitle "fail2ban-p2p User Manual">
<!ENTITY dhucpackage "FAIL2BAN-P2P">
<!ENTITY dhpackage "fail2ban-p2p">
]>
<refentry>
<refentryinfo>
<title>&dhtitle;</title>
<productname>&dhpackage;</productname>
<authorgroup>
<author>
<firstname>&dhfirstname;</firstname>
<surname>&dhsurname;</surname>
<contrib>Wrote this manpage for the Debian system.</contrib>
<address>
<email>&dhemail;</email>
</address>
</author>
</authorgroup>
<copyright>
<year>2007</year>
<holder>&dhusername;</holder>
</copyright>
<legalnotice>
<para>This manual page was written for the Debian system
(and may be used by others).</para>
<para>Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU General Public License,
Version 2 or (at your option) any later version published by
the Free Software Foundation.</para>
<para>On Debian systems, the complete text of the GNU General Public
License can be found in
<filename>/usr/share/common-licenses/GPL</filename>.</para>
</legalnotice>
</refentryinfo>
<refmeta>
<refentrytitle>&dhucpackage;</refentrytitle>
<manvolnum>&dhsection;</manvolnum>
</refmeta>
<refnamediv>
<refname>&dhpackage;</refname>
<refpurpose>program to do something</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>&dhpackage;</command>
<!-- These are several examples, how syntaxes could look -->
<arg choice="plain"><option>-e <replaceable>this</replaceable></option></arg>
<arg choice="opt"><option>--example=<parameter>that</parameter></option></arg>
<arg choice="opt">
<group choice="req">
<arg choice="plain"><option>-e</option></arg>
<arg choice="plain"><option>--example</option></arg>
</group>
<replaceable class="option">this</replaceable>
</arg>
<arg choice="opt">
<group choice="req">
<arg choice="plain"><option>-e</option></arg>
<arg choice="plain"><option>--example</option></arg>
</group>
<group choice="req">
<arg choice="plain"><replaceable>this</replaceable></arg>
<arg choice="plain"><replaceable>that</replaceable></arg>
</group>
</arg>
</cmdsynopsis>
<cmdsynopsis>
<command>&dhpackage;</command>
<!-- Normally the help and version options make the programs stop
right after outputting the requested information. -->
<group choice="opt">
<arg choice="plain">
<group choice="req">
<arg choice="plain"><option>-h</option></arg>
<arg choice="plain"><option>--help</option></arg>
</group>
</arg>
<arg choice="plain">
<group choice="req">
<arg choice="plain"><option>-v</option></arg>
<arg choice="plain"><option>--version</option></arg>
</group>
</arg>
</group>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1 id="description">
<title>DESCRIPTION</title>
<para>This manual page documents briefly the
<command>&dhpackage;</command> and <command>bar</command>
commands.</para>
<para>This manual page was written for the Debian distribution
because the original program does not have a manual page.
Instead, it has documentation in the GNU <citerefentry>
<refentrytitle>info</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry> format; see below.</para>
<para><command>&dhpackage;</command> is a program that...</para>
</refsect1>
<refsect1 id="options">
<title>OPTIONS</title>
<para>The program follows the usual GNU command line syntax,
with long options starting with two dashes (`-'). A summary of
options is included below. For a complete description, see the
<citerefentry>
<refentrytitle>info</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry> files.</para>
<variablelist>
<!-- Use the variablelist.term.separator and the
variablelist.term.break.after parameters to
control the term elements. -->
<varlistentry>
<term><option>-e <replaceable>this</replaceable></option></term>
<term><option>--example=<replaceable>that</replaceable></option></term>
<listitem>
<para>Does this and that.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-h</option></term>
<term><option>--help</option></term>
<listitem>
<para>Show summary of options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-v</option></term>
<term><option>--version</option></term>
<listitem>
<para>Show version of program.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 id="files">
<title>FILES</title>
<variablelist>
<varlistentry>
<term><filename>/etc/foo.conf</filename></term>
<listitem>
<para>The system-wide configuration file to control the
behaviour of <application>&dhpackage;</application>. See
<citerefentry>
<refentrytitle>foo.conf</refentrytitle>
<manvolnum>5</manvolnum>
</citerefentry> for further details.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><filename>${HOME}/.foo.conf</filename></term>
<listitem>
<para>The per-user configuration file to control the
behaviour of <application>&dhpackage;</application>. See
<citerefentry>
<refentrytitle>foo.conf</refentrytitle>
<manvolnum>5</manvolnum>
</citerefentry> for further details.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 id="environment">
<title>ENVIONMENT</title>
<variablelist>
<varlistentry>
<term><envar>FOO_CONF</envar></term>
<listitem>
<para>If used, the defined file is used as configuration
file (see also <xref linkend="files"/>).</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1 id="diagnostics">
<title>DIAGNOSTICS</title>
<para>The following diagnostics may be issued
on <filename class="devicefile">stderr</filename>:</para>
<variablelist>
<varlistentry>
<term><errortext>Bad configuration file. Exiting.</errortext></term>
<listitem>
<para>The configuration file seems to contain a broken configuration
line. Use the <option>--verbose</option> option, to get more info.
</para>
</listitem>
</varlistentry>
</variablelist>
<para><command>&dhpackage;</command> provides some return codes, that can
be used in scripts:</para>
<segmentedlist>
<segtitle>Code</segtitle>
<segtitle>Diagnostic</segtitle>
<seglistitem>
<seg><errorcode>0</errorcode></seg>
<seg>Program exited successfully.</seg>
</seglistitem>
<seglistitem>
<seg><errorcode>1</errorcode></seg>
<seg>The configuration file seems to be broken.</seg>
</seglistitem>
</segmentedlist>
</refsect1>
<refsect1 id="bugs">
<!-- Or use this section to tell about upstream BTS. -->
<title>BUGS</title>
<para>The program is currently limited to only work
with the <package>foobar</package> library.</para>
<para>The upstreams <acronym>BTS</acronym> can be found
at <ulink url="http://bugzilla.foo.tld"/>.</para>
</refsect1>
<refsect1 id="see_also">
<title>SEE ALSO</title>
<!-- In alpabetical order. -->
<para><citerefentry>
<refentrytitle>bar</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry>, <citerefentry>
<refentrytitle>baz</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry>, <citerefentry>
<refentrytitle>foo.conf</refentrytitle>
<manvolnum>5</manvolnum>
</citerefentry></para>
<para>The programs are documented fully by <citetitle>The Rise and
Fall of a Fooish Bar</citetitle> available via the <citerefentry>
<refentrytitle>info</refentrytitle>
<manvolnum>1</manvolnum>
</citerefentry> system.</para>
</refsect1>
</refentry>

2
debian/menu.ex vendored Normal file
View File

@ -0,0 +1,2 @@
?package(fail2ban-p2p):needs="X11|text|vc|wm" section="Applications/see-menu-manual"\
title="fail2ban-p2p" command="/usr/bin/fail2ban-p2p"

42
debian/postinst vendored Normal file
View File

@ -0,0 +1,42 @@
#!/bin/sh
# postinst script for fail2ban-p2p
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <postinst> `configure' <most-recently-configured-version>
# * <old-postinst> `abort-upgrade' <new version>
# * <conflictor's-postinst> `abort-remove' `in-favour' <package>
# <new-version>
# * <postinst> `abort-remove'
# * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
# <failed-install-package> <version> `removing'
# <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
configure)
[ -z "$SERVER_USER" ] && SERVER_USER="fail2ban-p2p"
# fix permissions on /etc/fail2ban-p2p
chown $SERVER_USER:adm /etc/fail2ban-p2p > /dev/null
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

37
debian/postrm.ex vendored Normal file
View File

@ -0,0 +1,37 @@
#!/bin/sh
# postrm script for fail2ban-p2p
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <postrm> `remove'
# * <postrm> `purge'
# * <old-postrm> `upgrade' <new-version>
# * <new-postrm> `failed-upgrade' <old-version>
# * <new-postrm> `abort-install'
# * <new-postrm> `abort-install' <old-version>
# * <new-postrm> `abort-upgrade' <old-version>
# * <disappearer's-postrm> `disappear' <overwriter>
# <overwriter-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
;;
*)
echo "postrm called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

76
debian/preinst vendored Normal file
View File

@ -0,0 +1,76 @@
#!/bin/sh
# preinst script for fail2ban-p2p
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <new-preinst> `install'
# * <new-preinst> `install' <old-version>
# * <new-preinst> `upgrade' <old-version>
# * <old-preinst> `abort-upgrade' <new-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
install|upgrade)
# see http://www.debian.org/doc/manuals/securing-debian-howto/ch9.en.html
# Sane defaults:
[ -z "$SERVER_HOME" ] && SERVER_HOME="/var/run/fail2ban-p2p"
[ -z "$SERVER_USER" ] && SERVER_USER="fail2ban-p2p"
[ -z "$SERVER_NAME" ] && SERVER_NAME="Fail2ban-p2p user"
[ -z "$SERVER_GROUP" ] && SERVER_GROUP="fail2ban-p2p"
# create user
# 1. create group if not existing
if ! getent group | grep -q "^$SERVER_GROUP:" ; then
echo -n "Adding group $SERVER_GROUP.."
addgroup --quiet --system $SERVER_GROUP 2>/dev/null ||true
echo "..done"
fi
# 2. create homedir if not existing
test -d $SERVER_HOME || mkdir $SERVER_HOME
# 3. create user if not existing
if ! getent passwd | grep -q "^$SERVER_USER:"; then
echo -n "Adding system user $SERVER_USER.."
adduser --quiet \
--system \
--ingroup $SERVER_GROUP \
--no-create-home \
--disabled-password \
$SERVER_USER 2>/dev/null || true
echo "..done"
fi
# 4. adjust passwd entry
usermod -c "$SERVER_NAME" \
-d $SERVER_HOME \
-g $SERVER_GROUP \
$SERVER_USER
# 5. adjust file and directory permissions
if ! dpkg-statoverride --list $SERVER_HOME >/dev/null
then
chown -R $SERVER_USER:adm $SERVER_HOME
chmod u=rwx,g=rxs,o= $SERVER_HOME
fi
# create logfile and make it owned by the user
test -f /var/log/fail2ban-p2p.log || touch /var/log/fail2ban-p2p.log
chown $SERVER_USER:adm /var/log/fail2ban-p2p.log > /dev/null
;;
abort-upgrade)
;;
*)
echo "preinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

38
debian/prerm.ex vendored Normal file
View File

@ -0,0 +1,38 @@
#!/bin/sh
# prerm script for fail2ban-p2p
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <prerm> `remove'
# * <old-prerm> `upgrade' <new-version>
# * <new-prerm> `failed-upgrade' <old-version>
# * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
# * <deconfigured's-prerm> `deconfigure' `in-favour'
# <package-being-installed> <version> `removing'
# <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
remove|upgrade|deconfigure)
;;
failed-upgrade)
;;
*)
echo "prerm called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0

65
debian/rules vendored Executable file
View File

@ -0,0 +1,65 @@
#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by Joey Hess and Craig Small.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by Craig Small in version 0.37 of dh-make.
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
DESTDIR=$(CURDIR)/debian/fail2ban-p2p
configure: configure-stamp
configure-stamp:
dh_testdir
touch configure-stamp
build:
clean: clean-inits
dh_testdir
dh_testroot
rm -f build-stamp configure-stamp
rm -rf build
# Does not hurt to ask distutils to do their duty
python setup.py clean
# Enforce removal of *.pyc files. Apparently dh_clean does
# not perform find on provided filename patterns.
find . -name \*.pyc -exec rm -f {} \;
dh_clean
install: build
dh_testdir
dh_testroot
dh_clean -k
dh_installdirs
# Install the package into debian/fail2ban-p2p.
python setup.py install --root=$(DESTDIR) --no-compile --install-layout=deb
#
# Just to comply with policy 4.8
binary-arch:
# Build architecture-independent files here.
binary-indep: install
dh_testdir
dh_testroot
#dh_installchangelogs ChangeLog
dh_installdocs
dh_installlogrotate
dh_pycentral
dh_installinit -- defaults 99
#dh_installman man/*.1
dh_link
dh_compress
dh_fixperms
dh_installdeb
dh_gencontrol
dh_md5sums
dh_builddeb
binary: binary-indep
.PHONY: build clean binary-indep binary-arch binary install configure copy-inits clean-inits

1
debian/source/format vendored Normal file
View File

@ -0,0 +1 @@
3.0 (native)

23
debian/watch.ex vendored Normal file
View File

@ -0,0 +1,23 @@
# Example watch control file for uscan
# Rename this file to "watch" and then you can run the "uscan" command
# to check for upstream updates and more.
# See uscan(1) for format
# Compulsory line, this is a version 3 file
version=3
# Uncomment to examine a Webpage
# <Webpage URL> <string match>
#http://www.example.com/downloads.php fail2ban-p2p-(.*)\.tar\.gz
# Uncomment to examine a Webserver directory
#http://www.example.com/pub/fail2ban-p2p-(.*)\.tar\.gz
# Uncommment to examine a FTP server
#ftp://ftp.example.com/pub/fail2ban-p2p-(.*)\.tar\.gz debian uupdate
# Uncomment to find new files on sourceforge, for devscripts >= 2.9
# http://sf.net/fail2ban-p2p/fail2ban-p2p-(.*)\.tar\.gz
# Uncomment to find new files on GooglePages
# http://example.googlepages.com/foo.html fail2ban-p2p-(.*)\.tar\.gz

1
doc/BUGS Normal file
View File

@ -0,0 +1 @@
Please report bugs at https://svn.physik.uni-augsburg.de/projects/fail2ban-p2p/

36
doc/CONFIG Normal file
View File

@ -0,0 +1,36 @@
= fail2ban-p2p.conf =
Default location is /etc/fail2ban-p2p/fail2ban-p2p.conf.
This file holds the information for your node. Following things must be configured:
== Node ==
{{{
[Node]
name=mynodename
addresses=127.0.0.1,10.0.0.1
port=1337
ownermail=foo@bar.de
bantime=7200
threshold=80
}}}
* name: Name of your Node, this is only used fpr informational purposes. In the
mesh the node is identified by its uid (hash of public key)
* addresses: A comma seperated list of listen addresses
* port: Listening port
* ownermail: Your email address (not used for now)
* bantime: how long in seconds fail2ban-p2p keeps banned hosts in its internal database
* threshold: Minimum trustlevel a ban for a host needs to take action (block it)
== Logging ==
{{{
[Logging]
logfile=/var/log/fail2ban-p2p.log
loglevel=INFO
}}}
* logfile: The file where fail2ban-p2p logs to
* loglevel: How verbose log output is, can be:
DEBUG, INFO, WARN, ERROR, BAN

117
doc/INSTALL Normal file
View File

@ -0,0 +1,117 @@
If packages for your distribution are available use them. If not use the
manual installation described below.
== Depencies ==
* python
* python-m2crypt
* python-argparse
== Installation on Debian based systems ==
* Download the latest deb package
* install depencies: apt-get install python-m2crypt python-argparse
* install fail2ban-p2p: dpkg -i fail2ban-p2p-<version>.deb
== Manual instalation ==
Download the latest tarball and extract it. After changing into the
fail2ban-p2p directory execute "python setup.py install", this will
install fail2ban-p2p.py and fail2ban-p2p-client.py to /usr/local/bin.
Modules will be installed to /usr/share/fail2ban-p2p/fail2ban-p2p.
== Configuration ==
The default configuration directory is /etc/fail2ban-p2p. You can specify
another directory with the -c command line option. See the CONFIG file in
this directory for a explanation of all config options.
== Setup ==
In order to use fail2ban-p2p you need to create a keypair for your node,
exchange public keys with at least one friend and setup fail2ban to work
with fail2ban-p2p.
1.) Creating a keypair for your node and exchange it with friend(s)
If no keypair is found in the configuration directory it will be created
at the first start of fail2ban-p2p.py or when using the -K command line
option. This needs to be done by a user who has write permissions in
the configuration directory.
Two files are created: private.pem and public.pem. private.pem is your
private key, keep this secret. public.pem needs to be shared with at least
one friend. But before you share it add something like this in public.pem
before the key:
address = 1.2.3.4
port = 1337
trustlevel = 80
This is the information how your node is reachable.
address Use your IP address or dns name here.
To listen on all addresses use 0.0.0.0
port The port your node listens ons (see fail2ban-p2p.conf)
trustlevel This is something your friend is allowed to edit
to give you more or less trust. Its a percentage, so use
something between 0 and 100.
Now send the edited public.pem to your friend(s). For every friend that you
want to add get his private.pem and place it in <config dir>/friends. Rename
the file to the name you want to use for this friend.
2.) Integration with fail2ban
To properly work and be able to exchange information with the fail2ban-daemon
you need to integrate fail2ban and fail2ban-p2p. Information about attackers
needs to be exchanged in two directions:
2.1.) From fail2ban-p2p to fail2ban
Fail2ban gets its information about attackers by watching the fail2ban-p2p
logfile. To setup fail2ban to watch the fail2ban-p2p log file do the following:
* Make fail2ban-p2p log into /var/log/fail2ban-p2p.log (this is the default)
* Add a jail for fail2ban-p2p like this in /etc/fail2ban/jails.conf:
[ssh-p2p]
enabled = true
port = ssh
filter = sshd-p2p
logpath = /var/log/fail2ban-p2p.log
bantime = 120
findtime = 120
maxretry = 1
See the fail2ban manual for explanation of these options. You probably
want to increase the bantime. It is important to leave maxretry at 1 (block
a host after 1 entry for it was found in /var/log/fail2ban-p2p.log).
* Add a filter sshd-p2p.conf in /etc/fail2ban/filter.d/sshd-p2p.conf
[Definition]
failregex = ^(.*)BAN(\t)<HOST>*$
2.2.) From fail2ban to fail2ban-p2p
* Setup an action to execute "fail2ban-p2p-client.py -b <ip>" to sent
the attacker IP from fail2ban to fail2ban-p2p.
For an example see doc/fail2ban/action.d/fail2ban-p2p.conf.
You might want to correct the path to client.py and also specify a
configuration directory for fail2ban-p2p with the -c option if you do
use a custom config directory.
* add this action to a jail, e.g. for the predefined ssh jail in jail.conf:
[ssh]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
action = iptables[name=SSH, port=ssh, protocol=tcp]
fail2ban-p2p[name=SSH]
maxretry = 2
This will ban the offending ip with the iptables action and also send
a notice to fail2ban-p2p that fail2ban has blocked an ip.

View File

@ -0,0 +1,21 @@
# Fail2Ban configuration file
#
# Author: Manuel Munz (manu at somakoma dot de)
#
[Definition]
# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: <ip> IP address
# <failures> number of failures
# <time> unix timestamp of the ban time
# Values: CMD
#
actionban = python /usr/bin/fail2ban-p2p-client.py -b <ip>
[Init]
# Defaut name of the chain
#
name = default

66
doc/messagetypes.txt Normal file
View File

@ -0,0 +1,66 @@
= Message Types for fail2ban-p2p =
General: messages are sent as JSON
== Type 1: Attack message ==
Message that is send to notify friends about the IPs of attackers.
{
"msg": {
"hops": [
"hop1",
"hop2"
],
"msgType": 1,
"parameter": {
"AttackerIP": "1.2.3.4",
"Timestamp": "1363279754",
"Trustlevel": "80"
},
},
"protocolVersion": 2
"signature": "foo"
}
The parameters AttackerIP and Timestamp are MANDATORY!
== Type 2: Dumprequest / Direct output ==
Message send to neighbors to request a dump of all known attackmessages
for a given Timeframe. Will return a json encoded list of all banned ips.
{
"msg": {
"hops": [
"local"
],
"msgType": 2,
"parameter": {
"TimeFrame": "3600"
},
},
"protocolVersion": 2
"signature": "foo"
}
TimeFrame is mandatory.
== Type 3: Dumprequest / Send normal ban messages to sender of this message ==
Message send to friend to trigger sending ban messages for all ips in
banlist for a given Timeframe. This can be used to pull banlists when a node
is started up.
{
"msg": {
"hops": [
"local"
],
"msgType": 3,
"parameter": {
"TimeFrame": "3600"
},
},
"protocolVersion": 2
"signature": "foo"
}
TimeFrame is mandatory.

153
doc/system/Makefile Normal file
View File

@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/fail2ban-p2p.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/fail2ban-p2p.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/fail2ban-p2p"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/fail2ban-p2p"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

74
doc/system/code.rst Normal file
View File

@ -0,0 +1,74 @@
Code Documentation
==================
command
-------
.. automodule:: command
:members:
config
-------
.. automodule:: config
:members:
crypto
------
.. automodule:: crypto
:members:
friend
------
.. automodule:: friend
:members:
log
---
.. automodule:: log
:members:
node
----
.. automodule:: node
:members:
odict
-----
.. automodule:: odict
:members:
parser
------
.. automodule:: parser
:members:
server
------
.. automodule:: server
:members:
util
----
.. automodule:: util
:members:
validators
----------
.. automodule:: validators
:members:
version
-------
.. automodule:: version
:members:

244
doc/system/conf.py Normal file
View File

@ -0,0 +1,244 @@
# -*- coding: utf-8 -*-
#
# fail2ban-p2p documentation build configuration file, created by
# sphinx-quickstart2 on Thu Apr 18 16:48:25 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
sys.path.insert(0, os.path.abspath('../../fail2ban-p2p'))
from version import version
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.doctest','sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'fail2ban-p2p'
copyright = u'2013, Manuel Munz, Johannes Fürmann'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = version
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'fail2ban-p2pdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'fail2ban-p2p.tex', u'fail2ban-p2p Documentation',
u'Manuel Munz, Johannes Fürmann', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'fail2ban-p2p', u'fail2ban-p2p Documentation',
[u'Manuel Munz, Johannes Fürmann'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'fail2ban-p2p', u'fail2ban-p2p Documentation',
u'Manuel Munz, Johannes Fürmann', 'fail2ban-p2p', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

View File

@ -0,0 +1,187 @@
.. _configuration:
Configuration
*************
In order to use fail2ban-p2p you need to create a keypair for your node,
exchange public keys with at least one friend and setup fail2ban to work
with fail2ban-p2p.
The default configuration directory is /etc/fail2ban-p2p. You can specify
another directory with the -c command line option. See the CONFIG file in
this directory for a explanation of all config options.
The main configuration file is **fail2ban-p2p.conf**.
The private and public keys are found in this directory, too.
For every friend there is a file in **/etc/fail2ban-p2p/friends/**
with the friends name as filename
(in case you know `tinc <http://www.tinc-vpn.org>`_
you might find this kind of configuration files very familiar).
Configure your node in fail2ban-p2p.conf
========================================
The default location for the main configuration file is
/etc/fail2ban-p2p/fail2ban-p2p.conf. This file contains the configuration
for your node. Following things **must** be configured:
Node - Section
--------------
.. code-block:: python
[Node]
name=mynodename
addresses=127.0.0.1,10.0.0.1
port=1337
ownermail=foo@bar.de
bantime=7200
threshold=80
+-----------+----------------------------------------------------------+
| parameter | Explanation |
+===========+==========================================================+
| name | The name of your node. This is only used for |
| | informational purposes. In the network nodes are |
| | identified by uid (hash of the nodes public key) |
+-----------+----------------------------------------------------------+
| addresses | A comma seperated list of listen addresses |
+-----------+----------------------------------------------------------+
| port | Listening port |
+-----------+----------------------------------------------------------+
| ownermail | Your email address. |
| | (not used for now, but eventually in the future) |
+-----------+----------------------------------------------------------+
| bantime | How long fail2ban-p2p keeps banned hosts in its internal |
| | database (in seconds) |
+-----------+----------------------------------------------------------+
| treshold | Minimum trustlevel a received message needs to have to |
| | launch an action |
+-----------+----------------------------------------------------------+
Logging - Section
-----------------
.. code-block:: python
[Logging]
logfile=/var/log/fail2ban-p2p.log
loglevel=INFO
+-----------+----------------------------------------------------------+
| parameter | Explanation |
+===========+==========================================================+
| logfile | The file where logs are written to |
| | (default: /var/log/fail2ban-p2p.log) |
+-----------+----------------------------------------------------------+
| loglevel | Set verbosity level for log output. The following levels |
| | are defined: DEBUG, INFO, WARN, ERROR, BAN |
+-----------+----------------------------------------------------------+
Create a keypair for your node and exchange it with friend(s)
=============================================================
If no keypair is found in the configuration directory it will be created
at the first start of fail2ban-p2p.py or when using the -K command line
option. This needs to be done by a user who has write permissions in
the configuration directory.
Two files are created: private.pem and public.pem. private.pem is your
private key, keep this secret. public.pem needs to be shared with at least
one friend. But before you share it add something like this in public.pem
before the key:
.. code-block:: python
address = 1.2.3.4
port = 1337
trustlevel = 80
This is the information how your node is reachable.
+-----------+----------------------------------------------------------+
| parameter | Explanation |
+===========+==========================================================+
| address | Use your IP address or dns name here. |
| | To listen on all addresses use 0.0.0.0 |
+-----------+----------------------------------------------------------+
| port | The port your node listens ons (see fail2ban-p2p.conf) |
+-----------+----------------------------------------------------------+
| trustlevel| This is something your friend is allowed to editi |
| | to give you more or less trust. Its a percentage, so use |
| | something between 0 and 100. |
+-----------+----------------------------------------------------------+
Now send the edited public.pem to your friend(s). For every friend that you
want to add get his private.pem and place it in ``<config dir>/friends``. Rename
the file to the name you want to use for this friend.
Integration with fail2ban
=========================
To properly work and be able to exchange information with the fail2ban-daemon
you need to integrate fail2ban and fail2ban-p2p. Information about attackers
needs to be exchanged in two directions:
From fail2ban-p2p to fail2ban
-----------------------------
Fail2ban gets its information about attackers by watching the fail2ban-p2p
logfile. To setup fail2ban to watch the fail2ban-p2p log file do the following:
1. Make fail2ban-p2p log into /var/log/fail2ban-p2p.log (this is the default)
2. Add a jail for fail2ban-p2p like this in /etc/fail2ban/jails.conf:
.. code-block:: python
[ssh-p2p]
enabled = true
port = ssh
filter = sshd-p2p
logpath = /var/log/fail2ban-p2p.log
bantime = 120
findtime = 120
maxretry = 1
See the fail2ban manual for explanation of these options. You probably
want to increase the bantime. It is important to leave maxretry at 1 (block
a host after 1 entry for it was found in /var/log/fail2ban-p2p.log).
3. Add a filter sshd-p2p.conf in /etc/fail2ban/filter.d/sshd-p2p.conf
.. code-block:: python
[Definition]
failregex = ^(.*)BAN(\t)<HOST>*$
From fail2ban to fail2ban-p2p
-----------------------------
1. Setup an action to execute "fail2ban-p2p-client.py -b <ip>" to sent
the attacker IP from fail2ban to fail2ban-p2p.
For an example see doc/fail2ban/action.d/fail2ban-p2p.conf.
You might want to correct the path to client.py and also specify a
configuration directory for fail2ban-p2p with the -c option if you
use a custom config directory.
2. Add this action to a jail, e.g. for the predefined ssh jail in
/etc/fail2ban/jail.conf:
.. code-block:: python
[ssh]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
action = iptables[name=SSH, port=ssh, protocol=tcp]
fail2ban-p2p[name=SSH]
maxretry = 2
This will ban the offending ip with the iptables action and also send a message
about this attacker to the locally running fail2ban-p2p.

114
doc/system/design.rst Normal file
View File

@ -0,0 +1,114 @@
Design
******
.. _design:
How messages are distributed
============================
.. image:: ./images/message-propagation.png
:align: left
**Legend**
* grey dotted: bidirectional connection between nodes (both can send messages to each other)
* red: Brute Force to Node A
* blue: Brute Force to Node B
**Explanation**
Every node in this Graph uses a Trustlevel of 80% (which is the default for fail2ban-p2p) and also uses a Treshold of 80%. That means: Only if we get a message with a Trustlevel which is equal or higher than the Treshold the attacker is blocked.
**First: Attacker brute forces Node A (red)**
Fail2ban on Node A detects that the attacker had to many failed logins. It now blocks the attackers IP (1.2.3.4) locally and also sends a message to the local fail2ban-p2p node. fail2ban-p2p now distributes this attacker information to its friends Node B and Node C, both accept it with a Trustlevel of 80%. Because this is equal to the Treshold value B and C now also block this attacker. Node C also sends this message to its two other friends D and E. But D and E give the message from C now only a Trustlevel of 64% (80%*80%), they don't block that attacker (yet), but would redistribute the message to their friends again and save the information about this attacker in their internal database.
**Second: Attacker now also brute forces Node B (blue)**
This time Fail2ban on Node B detects the brute force and blocks the attacker (in fact it is already blocked, but forget that for this example). It now sends this attacker information to Node A which already knows about the attacker and already blocked it. But it redistributes the message to its friend C again. Because the node which detected the attack (Node B) is 1 hop away Node C now gives this attacker information a Trustvalue of 64% and add this to the Trustvalue of 80% it already have. trust cannot be more than 100%, so node C now updates its internal database and stores 100% trustvalue for the attacker. It also retransmits the attacker info to Nodes D and E. Bot give this message a Trustvalue of 51,2% now (80%*80%*80%) which is again added to the Trustvalue of 64% it had before for that attacker IP and again it cuts it at 100%. Finally the attackers IP is now also blocked on Nodes D and E.
.. _message_types:
Message Types for fail2ban-p2p
==============================
All messages are exchanged in JSON formatted strings. The following message types are
definded:
Type 1: Attack message
----------------------
This message type is used to notify friends about the IP of an attacker.
**Mandatory parameters:** AttackerIP, Timestamp
.. code-block:: javascript
{
"msg": {
"hops": [
"hop1",
"hop2"
],
"msgType": 1,
"parameter": {
"AttackerIP": "1.2.3.4",
"Timestamp": "1363279754",
"Trustlevel": "80"
},
},
"protocolVersion": 2
"signature": "foo"
}
Type 2: Dumprequest / Direct output
-----------------------------------
Message send to neighbors to request a dump of all known attackmessages
for a given Timeframe. Will return a json encoded list of all banned ips.
**Mandatory parameters:** TimeFrame
.. code-block:: javascript
{
"msg": {
"hops": [
"local"
],
"msgType": 2,
"parameter": {
"TimeFrame": "3600"
},
},
"protocolVersion": 2
"signature": "foo"
}
Type 3: Dumprequest / Send normal ban messages to sender of this message
------------------------------------------------------------------------
Message send to friend to trigger sending ban messages for all ips in
banlist for a given Timeframe. This can be used to pull banlists when a node
is started up.
**Mandatory parameters:** TimeFrame
.. code-block:: javascript
{
"msg": {
"hops": [
"local"
],
"msgType": 3,
"parameter": {
"TimeFrame": "3600"
},
},
"protocolVersion": 2
"signature": "foo"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

29
doc/system/index.rst Normal file
View File

@ -0,0 +1,29 @@
.. fail2ban-p2p documentation master file, created by
sphinx-quickstart2 on Thu Apr 18 16:48:25 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to fail2ban-p2p's documentation!
========================================
Contents:
.. toctree::
:maxdepth: 2
intro
installation
configuration
design
code
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -0,0 +1,46 @@
.. _install:
Installation
************
If packages for your distribution are available use them. If not use the
manual installation described below.
Depencies
=========
fail2ban-p2p depends on the following packages:
* python
* python-m2crypt
* python-argparse
Installation from svn
=====================
To checkout the source code with svn use:
* trunk: svn co https://svn.physik.uni-augsburg.de/svn/fail2ban-p2p/trunk or
* tagged versions: https://svn.physik.uni-augsburg.de/svn/fail2ban-p2p/tags/$version
After the checkout change into the fail2ban directory and install fail2ban-p2p with
# python setup.py install
Installation from tarball
================================
Download the latest release tarball from
https://svn.physik.uni-augsburg.de/projects/fail2ban-p2p/wiki/releases
and extract it. After changing into the fail2ban-p2p directory execute
# python setup.py install
This will install fail2ban-p2p.py and fail2ban-p2p-client.py to /usr/local/bin.
Modules will be installed to /usr/share/fail2ban-p2p/fail2ban-p2p.
Installation on Debian based systems
====================================
* Download the latest deb package from https://svn.physik.uni-augsburg.de/projects/fail2ban-p2p/wiki/releases
* install depencies: apt-get install python-m2crypt python-argparse
* install fail2ban-p2p: dpkg -i fail2ban-p2p-<version>.deb

62
doc/system/intro.rst Normal file
View File

@ -0,0 +1,62 @@
Introduction
************
About fail2ban-p2p
==================
fail2ban-p2p is a programm that can be used together with
`fail2ban <http://www.fail2ban.org>`_ to **distribute information about
attackers using a p2p/f2f network.** Like fail2ban it is written in
python. fail2ban-p2p is in an **early stage of development**, please be
prepared for bugs and if you find some, let us know (open a
`ticket <https://svn.physik.uni-augsburg.de/projects/fail2ban-p2p/newticket>`_).
Every node in a fail2ban-p2p network is connected to at least one other node
("friend"). When fail2ban detects an attacker it launches an action (e.g.
block the attackers IP with iptables). To work together with fail2ban-p2p
fail2ban is configured to launch another action once an attacker is identified:
fail2ban sends the attackers IP address to the locally running instance of
fail2ban-p2p. fail2ban-p2p then redistributes this information about the attacker
to all friends which are online. fail2ban-p2p on the friends nodes writes this
information to a logfile that is watched by fail2ban. Now Fail2ban on the friends
node itself can launch an action (e.g. block that attacker IP).
Fail2ban-p2p only handles the distribution of attacker IPs, while fail2ban is used
to detect attackers and launch actions (e.g. ban the attackers). Friends redistribute
received messages to their friends and so on, until the whole network is informed
about that attacker.
There is a configurable trustlevel value (a percentage, the default is 80%) that is
applied to forwarded messages. Trustlevel decreases the more hops the node that
initially detected the attacker is away. In other words:
**You trust your own direct "friends" more than their friends.**
To ensure fail2ban-p2p processes only messages that were received by direct friends,
all messages are signed with your private key and can be verified by the friend
who receives the message. That means when you configure a new friend you also
have to exchange public keys with him.
The following graphic may help to better understand how messages are distributed
in a fail2ban-p2p network:
.. image:: ./images/message-propagation.png
For an in-depth explanation of this graph see :ref:`design`
Installation
============
Fail2ban-p2p can be installed from source code (tarball or svn).
We also provide packages for **Debian**. See :ref:`install` for installation
instructions.
Configuration
=============
To be able to use fail2ban-p2p you need to configure your node and
exchange public keys with your friends. See :ref:`configuration` for
details how to do this.
Mailinglist
===========
For help/discussion please subscribe to the fail2ban-p2p mailing list at http://mailman.rz.uni-augsburg.de/mailman/listinfo/fail2ban-p2p

190
doc/system/make.bat Normal file
View File

@ -0,0 +1,190 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build2
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\fail2ban-p2p.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\fail2ban-p2p.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

151
fail2ban-p2p-client.py Executable file
View File

@ -0,0 +1,151 @@
#!/usr/bin/python2
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
"""
This script can be used to send a ban message to the own node.
To do this it will use the ip address and port given in the configfile
for this node.
"""
import sys
sys.path.insert(1, "./fail2ban-p2p")
sys.path.insert(2, "/usr/share/fail2ban-p2p/fail2ban-p2p")
import config
import hashlib
import os
import argparse
import crypto
import socket
import M2Crypto
from time import time
import json
import util
import version
# Parse arguments
parser = argparse.ArgumentParser(description='fail2ban-p2p-client help.')
parser.add_argument('-b', help='IP address to ban', metavar='IP')
parser.add_argument('-c', default='/etc/fail2ban-p2p/', help='Read configuration from DIR.',
metavar='DIR')
parser.add_argument('-d', help='Dump table of blocked hosts in the format <FORMAT> (table, json or count).',
metavar='FORMAT')
parser.add_argument('-t', help='The list of blocked hosts should go back that many seconds.',
metavar='SECONDS')
parser.add_argument('-q', action='store_true', help='Quiet, no output')
parser.add_argument('-v', action='store_true', help='Verbose output')
args = parser.parse_args()
c = config.Config()
c.configPath = args.c or "/etc/fail2ban-p2p"
c.privkey = os.path.join(c.configPath, 'private.pem')
c.pubkey = os.path.join(c.configPath, 'public.pem')
if c.loadConfig() == False:
exit()
if not args.d and not args.b:
print "Please use the -b argument to specify an IP to ban or -d to request information about banned nodes."
exit()
dump = False
if args.d:
dump = True;
if not args.d == "table" and not args.d == "json" and not args.d == "count":
print("invalid value for -d argument!")
exit()
timeframe = 3600
if args.t:
try:
timeframe = int(args.t)
except ValueError as e:
print("Invalid Timeframe specified, only use integers! Using default value of 3600 instead")
timeframe = 3600
quiet = False
if args.q:
quiet = True
if dump:
# Generate a message of type 2 (request to dump list of banned hosts)
unordered_dict = {
"msgType": 2,
"parameter": { "TimeFrame": timeframe},
"hops": ['local']
}
serializable_dict = util.sort_recursive(unordered_dict)
if args.b:
# Generate a ban message (Type 1)
unordered_dict = {
"msgType": 1,
"parameter": { "Timestamp": int(time()), "AttackerIP": args.b, "Trustlevel": 100 },
"hops": ['local']
}
serializable_dict = util.sort_recursive(unordered_dict)
if args.b or dump:
signed_message = json.dumps(serializable_dict)
SignEVP = M2Crypto.EVP.load_key(c.privkey)
SignEVP.sign_init()
SignEVP.sign_update(signed_message)
StringSignature = SignEVP.sign_final().encode('hex')
signed_dict = {
#"protocolVersion": version.protocol,
"msg": serializable_dict,
"signature": StringSignature,
"protocolVersion": version.protocolVersion
}
cmdsigned = json.dumps(signed_dict)
ret = None
# send message
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
s.connect((c.addresses[0], int(c.port)))
s.send(cmdsigned)
ret = s.recv(1048576) # we need about 50 Bytes per banned node
if not quiet and args.v:
print ("Message sent: " + cmdsigned)
except:
if not quiet:
print ("could not connect to "+c.name+" ("+c.addresses[0]+":"+str(c.port)+")")
finally:
s.close()
if ret:
if args.d:
if "ERROR" in ret:
print("An error occured:\n")
print(ret)
elif args.d == "json":
print(ret)
elif args.d == "count":
print(len(json.loads(ret)))
else:
banList = json.loads(ret)
if len(banList) > 0:
print("IP".ljust(15, ' ') + "\tTimestamp\t\tBantime\t\tTrustlevel\tStatus")
for ban in banList:
status = "PENDING"
if int(c.threshold) <= int(ban['Trustlevel']):
status = "BANNED"
print(ban['AttackerIP'].ljust(15, ' ') + "\t" + str(ban['Timestamp']) + "\t\t" + str(ban['BanTime']) + "\t\t" + str(ban['Trustlevel'])) + "\t\t" + status
else:
print("No hosts in banlist")
else:
print("Answer: " + ret)

62
fail2ban-p2p.py Executable file
View File

@ -0,0 +1,62 @@
#!/usr/bin/python2
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
# Main program for fail2ban-p2p.
# set lib paths
import sys
sys.path.insert(1, "./fail2ban-p2p")
sys.path.insert(2, "/usr/share/fail2ban-p2p/fail2ban-p2p")
import config
import node
import log
import os
import argparse
import crypto
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='fail2ban-p2p help.')
parser.add_argument('-K', action='store_true', help='Create private/public keypair')
parser.add_argument('-c', default='/etc/fail2ban-p2p/', help='Read configuration from DIR.',
metavar='DIR')
args = parser.parse_args()
c = config.Config()
c.configPath = args.c or "/etc/fail2ban-p2p"
c.privkey = os.path.join(c.configPath, 'private.pem')
c.pubkey = os.path.join(c.configPath, 'public.pem')
if c.loadConfig() == False:
raise OSError #, 'Config error, check log.'
logger = log.initialize_logging("fail2ban-p2p")
if args.K:
crypto.create_keys()
exit()
# make sure the keys exist
if not os.path.isfile(c.privkey) or not os.path.isfile(c.pubkey):
logger.warning('Private or public key not found, creating them')
crypto.create_keys()
n = None
try:
n = node.Node()
n.loadConfig()
n.getFriends()
n.requestBanlist()
n.cleanBanlist()
n.openSocket()
except (KeyboardInterrupt):
logger.info("Keyboard Interrupt received, going down")
n.cleanBanlistStop()
n.closeSocket()
logger.info("kthxbai!")

96
fail2ban-p2p/command.py Normal file
View File

@ -0,0 +1,96 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import util
import config
import log
import crypto
import M2Crypto
import json
import util
import version
logger = log.initialize_logging("fail2ban-p2p." + __name__)
class Command:
'''
Handle command objects.
Kwargs:
* protocolVersion (int): Protocol version number
* msgType (int): message type
* parameter (dict): Parameters to send in the message
* signature (string): The messages signature
* hops (array): Hops that previously have relayed this message
'''
msgType = None
parameter = ()
signature = ""
hops = []
def __init__(self, protocolVersion=None, msgType=None, parameter={}, signature=None, hops=[]):
self.msgType = msgType
self.parameter = parameter
self.protocolVersion = protocolVersion
self.signature = signature
self.hops = hops
def __string__(self):
return "Command (msgType = "+str(msgType)+", ...)"
def toSerializableDict(self):
'''
Returns a recursively sorted dictionary
'''
unordered_dict = {
"msgType": self.msgType,
"parameter": self.parameter,
"hops": self.hops
}
return util.sort_recursive(unordered_dict)
def toProtocolMessage(self):
'''
Create a JSON-encoded Protocol message.
'''
serializable_dict = self.toSerializableDict()
signed_message = json.dumps(serializable_dict)
signature = self.sign(signed_message)
signed_dict = {
"msg": serializable_dict,
"signature": signature,
"protocolVersion": version.protocolVersion
}
return json.dumps(signed_dict)
def sign(self, text):
"""
Compute signature for a message.
Args:
text (string): the json encoded message text.
Returns:
A string with the signature for 'text'
"""
logger.debug("signing outgoing message")
c = config.Config()
SignEVP = M2Crypto.EVP.load_key(c.privkey)
SignEVP.sign_init()
SignEVP.sign_update(text)
StringSignature = SignEVP.sign_final().encode('hex')
logger.debug("Our signature for this message is: " + StringSignature)
self.signature = StringSignature
return StringSignature

79
fail2ban-p2p/config.py Normal file
View File

@ -0,0 +1,79 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import ConfigParser
import os
import logging
class Config:
"""
Handles config file loading and parsing of config values,
uses borg pattern
"""
__shared_state = {}
configPath = ""
configFile = ""
logFile = ""
logLevel = ""
addresses = []
name = ""
port = 0
ownermail = ""
banTime = 0
threshold = 0
def __init__(self, configPath = '/etc/fail2ban-p2p'):
self.__dict__ = self.__shared_state # borg pattern.
def loadConfig(self):
"""
Load and parse the config file
"""
def get_option(section, option, mandatory, default):
'''Gets an option from the config file
Args:
section: Section in config file
option: option in config file
default: the default value if option was not found
mandatory: if this option is mandatory
Returns:
The value of the option we requested or the default value if the
option is not mandatory; else False
'''
try:
value = config.get(section, option)
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
if mandatory:
print "Mandatory option " + option + " not found in config file " + self.configFile
return False
else:
value = default
return value
config = ConfigParser.RawConfigParser()
self.configFile = os.path.join(self.configPath, 'fail2ban-p2p.conf')
if os.access(self.configFile, os.R_OK):
config.read(self.configFile)
self.logFile = get_option('Logging', 'logfile', False, '/var/log/fail2ban-p2p.log')
self.logLevel = get_option('Logging', 'loglevel', False, 'DEBUG')
self.logLevel = eval("logging." + self.logLevel) or 10
self.addresses = get_option('Node', 'addresses', False, '0.0.0.0')
self.addresses = [a.strip() for a in self.addresses.split(',')]
self.name = get_option('Node', 'name', False, 'Ididnotsetaname')
self.port = get_option('Node', 'port', False, 1337)
self.banTime = get_option('Node', 'bantime', False, 7200)
self.ownermail = get_option('Node', 'ownermail', False, "ididnotsetmyemail@example.org")
self.threshold = get_option('Node', 'threshold', False, 80)
else:
print('ERROR: Configuration directory "' + self.configPath + '" does not exist.\n' +
'Please create a configuration or specify another valid configuration directory with the "-c" argument.')
return False

43
fail2ban-p2p/crypto.py Normal file
View File

@ -0,0 +1,43 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import config
import os
import M2Crypto
import log
c = config.Config()
logger = log.initialize_logging("fail2ban-p2p." + __name__)
def create_keys():
"""Create private/public keypair (RSA 1024 bit)
If this function is called a private/public keypair is created if it does
not already exist. If the keypair already exists then the function will
ask for confirmation to overwrite it. The created keypair will be saved
in the config directory.
"""
if os.path.isfile(c.privkey) or os.path.isfile(c.pubkey):
print "A keypair for this node already exists."
ask = raw_input('Do you really want to create a new one? [y/N] ')
if ask != "y":
return
M2Crypto.Rand.rand_seed (os.urandom (1024))
logger.info("Generating a 1024 bit private/public key pair...")
keypair = M2Crypto.RSA.gen_key (1024, 65537)
try:
keypair.save_key(c.privkey, None)
os.chmod(c.privkey, 0400)
keypair.save_pub_key(c.pubkey)
logger.debug("Private key (secret) was saved to " + c.privkey)
logger.debug("Public key was saved to " + c.pubkey)
except IOError, e:
logger.error("Could not save the keypair, check permissions! " + "%s" % e)
exit()

View File

@ -0,0 +1,16 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
class InvalidMessage(Exception):
pass
class InvalidSignature(Exception):
pass
class InvalidProtocolVersion(Exception):
pass

58
fail2ban-p2p/friend.py Normal file
View File

@ -0,0 +1,58 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import command
import socket
import log
logger = log.initialize_logging("fail2ban-p2p." + __name__)
class Friend:
"""Contains information about friends (i.e. associated nodes).
Kwargs:
* name (string): A name for this friend (derived from filename)
* uid (string): A unique identifier (sha224 of friends public key)
* address (array): IP Addresses or Domains where the friend is listening for
incoming connections
* port (int): Port for the friends listener (0-65535)
* publicKey (string): friends public key
* trustLevel (int): How much we trust messages from this friend (0-100%)
"""
def __init__(self, name="", uid="", address="", port=0, publicKey=0, trustLevel=0):
self.name = name
self.address = address
self.port = port
self.uid = uid
self.publicKey = publicKey
self.trustLevel = trustLevel
def sendCommand(self, command):
"""send a command message to a friend
Args:
* command -- Command object
"""
logger.debug("attempting to send a command to friend "+self.name)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cmd = command.toProtocolMessage()
logger.debug("Message to be sent: "+cmd)
try:
logger.debug("trying to connect to "+self.address+":"+str(self.port))
s.settimeout(10)
s.connect((self.address, self.port))
s.send(cmd)
logger.debug ("Message sent: " + cmd)
except:
logger.warning("could not connect to friend "+self.name+" ("+self.address+":"+str(self.port)+")")
finally:
s.close()

55
fail2ban-p2p/log.py Normal file
View File

@ -0,0 +1,55 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import config
import logging
import sys
import os
from logging.handlers import WatchedFileHandler
def initialize_logging(name="unknown"):
"""Initializes the logging module.
This initializes pythons logging module:
* set loglevel (from nodes config)
* set logfile
* define new loglevel BAN with priority 90
* format log messages
* log to file as well as stderr
Kwargs:
name (string): name of the module initializing the logger
"""
c = config.Config()
if not c.logLevel:
c.logLevel = logging.DEBUG
if not c.logFile:
c.logFile = "/dev/null"
logging.BAN = 90
logging.addLevelName(logging.BAN, 'BAN')
logger = logging.getLogger(name)
logger.ban = lambda msg, *args: logger._log(logging.BAN, msg, args)
formatter = logging.Formatter('%(asctime)s - %(name)s\t%(levelname)s\t%(message)s')
logger.setLevel(c.logLevel)
if name == "fail2ban-p2p": # Only add new handlers when called from main.py
try:
log2file = WatchedFileHandler(c.logFile)
log2file.setFormatter(formatter)
log2file.setLevel(c.logLevel)
logger.addHandler(log2file)
except:
print("--- WARNING --- LOGFILE " + c.logFile + " IS EITHER NONEXISTENT OR NOT WRITABLE")
log2stderr = logging.StreamHandler(sys.stderr)
log2stderr.setFormatter(formatter)
log2stderr.setLevel(c.logLevel)
logger.addHandler(log2stderr)
return logger

449
fail2ban-p2p/node.py Normal file
View File

@ -0,0 +1,449 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import config
import socket
import thread
import threading
from command import Command
import server
import log
import os
import re
import friend
import hashlib
import json
import version
from select import select
from time import time
import crypto
import M2Crypto
import customexceptions
import validators
logger = log.initialize_logging("fail2ban-p2p." + __name__)
class Node:
"""Handles the self-awareness of the program."""
__shared_state = {}
# config attributes
uid = 0
name = ""
addresses = []
port = 0
ownerMail = ""
banTime = 0
# working attributes
banList = []
messageQueue = []
friends = []
running = True
lock = threading.Lock()
def __init__(self):
self.__dict__ = self.__shared_state # borg pattern.
def openSocket(self):
"""
Opens a server socket on the port specified in the config files, forks away a thread to
handle the incoming requests.
"""
logger.info("This is node " + str(self.name) + " (uid=" + str(self.uid) + ") coming up")
logger.debug("running version: " + version.version)
try:
sockets = []
for a in self.addresses:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((a, int(self.port)))
s.listen(1)
sockets.append(s)
except Exception as e:
logger.warning("Couldn't bind to address "+a+" (Reason: "+str(e)+")")
while self.running:
readable, writable, errored = select(sockets, [], [])
for sock in readable:
client_socket, address = sock.accept()
logger.debug("connection from "+address[0])
thread.start_new_thread(server.serve, (self, client_socket, address))
except Exception as e:
print(e)
def closeSocket(self):
"""
Closes the server Socket
"""
logger.debug("closing socket")
self.running = False
def processMessages(self):
"""Locks own instance and acts on incoming messages."""
self.lock.acquire()
logger.debug("begin message handling")
for c in self.messageQueue:
if not self.uid in c.hops:
if c.hops[0] == 'local':
del c.hops[0]
# relay if we're not already in the hops list
c.hops.append(self.uid)
if c.msgType == 1:
# apply friend's trustlevel
if not 'Trustlevel' in c.parameter:
logger.warn("Incoming Message has no Trustlevel, I won't trust it. Never.")
c.parameter['Trustlevel'] = 0;
if c.sender != "local":
c.parameter['Trustlevel'] = int((float(c.sender.trustLevel)/100 * float(c.parameter['Trustlevel'])/100)*100)
logger.debug("Message now has trust level "+ str(c.parameter['Trustlevel']))
# Aggregate trustlevel if that IP is already in our database under these conditions:
# * Timestamp of the received message has changed
# * The originator of this message did not send it before
relay = True
ipindb = False
if len(self.banList) > 0:
for ban in self.banList:
if ban['AttackerIP'] == c.parameter['AttackerIP']:
ipindb = True
logger.debug("IP already in database.")
if int(ban['Timestamp']) != int(c.parameter['Timestamp']):
if not c.hops[0] in ban['Hops']:
trustold = ban['Trustlevel']
trustnew = int(trustold)+int(c.parameter['Trustlevel'])
if trustnew > 100:
trustnew = 100
ban['Trustlevel'] = trustnew
ban['Hops'].append(c.hops[0])
logger.debug("TrustLevel for this IP is now "+str(trustnew))
c.parameter['Trustlevel'] = trustnew
else:
relay = False
logger.debug("There is already an entry from %s in our database, do nothing with this message." % c.hops[0])
else:
relay = False
logger.debug("Timestamp has not changed, do nothing with this message")
if not ipindb:
self.banList.append({'AttackerIP': c.parameter['AttackerIP'], 'Timestamp': c.parameter['Timestamp'], 'BanTime': self.banTime, 'Trustlevel':c.parameter['Trustlevel'], 'Hops': [c.hops[0]]})
logger.debug("Added %s to internal banlist" % (c.parameter['AttackerIP']))
# write ban entry to log if the message's trust level is above our own threshold
if relay:
if int(c.parameter['Trustlevel']) >= int(config.Config().threshold):
logger.ban(c.parameter['AttackerIP'])
else:
logger.debug("Message's trust level (%s) was below our threshold (%s)" % (c.parameter['Trustlevel'], config.Config().threshold))
# Relay message
for friend in self.friends:
logger.debug("sending message to all friends")
friend.sendCommand(c)
if c.msgType == 3:
# dump all ips from banlist to the friend who send this dump request
sender_uid = c.hops[0]
for friend in self.friends:
logger.debug("Comparing senders uid (%s) with one of our friends uid (%s)" % (sender_uid, friend.uid))
if friend.uid == sender_uid:
logger.debug("The message is from our friend %s (uid: %s)" % ( friend.name, friend.uid) )
logger.debug("Dumping banlist to %s (uid: %s)" % ( friend.name, friend.uid) )
if len(self.banList) > 0:
for ban in self.banList:
c = Command()
c.msgType = 1
c.hops = [ self.uid ]
c.protocolVersion = version.protocolVersion
c.parameter = { "AttackerIP": ban['AttackerIP'], "Timestamp": ban['Timestamp'], "Trustlevel": ban['Trustlevel'] }
friend.sendCommand(c)
else:
logger.debug("I know this message, I won't resend it to prevent loops")
logger.debug("end message handling")
self.messageQueue = []
logger.debug("deleted processed messages")
self.lock.release()
def addMessage(self, command):
"""Locks Instance, adds message to queue, releases instanceLock
Args:
* command (obj): command object
"""
logger.debug("command added to queue")
self.lock.acquire()
self.messageQueue.append(command)
self.lock.release()
self.processMessages()
def loadConfig(self):
"""Loads Config and own keypair."""
c = config.Config()
self.configPath = c.configPath
self.configFile = c.configFile
pubkey_file = open(c.pubkey, 'r').read()
pubkey = re.findall("-----BEGIN PUBLIC KEY-----(.*?)-----END PUBLIC KEY-----", pubkey_file, re.DOTALL|re.M)[0]
logger.debug("our own pubkey is: %s" % pubkey)
self.uid = str(hashlib.sha224(pubkey).hexdigest())
logger.debug("that makes our own uid: %s", self.uid)
self.addresses = c.addresses
self.port = c.port
self.ownerMail = c.ownermail
self.banTime = int(c.banTime)
self.name = c.name
def getFriends(self):
"""Reads Friends from config path.
This iterates over all files in <config path>/friends, extracts all options and
add these friends to self.friends if their configuration is valid.
"""
error = False
friendPath = os.path.join(self.configPath, 'friends')
friends = [f for f in os.listdir(friendPath) if os.path.isfile(os.path.join(friendPath, f))]
if not friends:
logger.warning("No friends found. In order to properly use fail2ban-p2p" +
" add at least one friend.")
for file in friends:
with open(os.path.join(os.path.join(self.configPath, 'friends'), file), 'r') as f:
friendinfo = str(f.read())
f.closed
try:
pubkey = re.findall("-----BEGIN PUBLIC KEY-----(.*?)-----END PUBLIC KEY-----", friendinfo, re.DOTALL|re.M)[0]
except IndexError:
logger.warning("No pubkey found in config for " + file)
error = True
if pubkey:
logger.debug("read friend's public key: %s" % pubkey )
uid = str(hashlib.sha224(pubkey).hexdigest())
try:
address = re.search("address\s*=\s*(.*)", friendinfo).group(1)
except AttributeError:
logger.warning("address not found in config for " + file)
error = True
try:
port = re.search("port\s*=\s*(.*)", friendinfo).group(1)
# make sure port is in valid range
if not 0 < int(port) < 65536:
logger.warning("Port is invalid in '%s' friend file, must be between 0 and 65535" % file)
error = True
except AttributeError:
logger.warning("port not found in config for " + file)
error = True
try:
trustlevel = re.search("trustlevel\s*=\s*(.*)", friendinfo).group(1)
except AttributeError:
logger.warning("trustlevel not found in config for" + file)
error = True
if not error:
obj = friend.Friend(name=file, uid=uid, address=address, port=int(port),
trustLevel=int(trustlevel), publicKey=pubkey)
obj.configpath=os.path.join(os.path.join(self.configPath, 'friends'), file)
logger.debug("added friend " + file +
" (uid=" + uid + ", address=" + address + ", port=" + str(port) +
", trustLevel=" + str(trustlevel) + ")"
)
self.friends.append(obj)
else:
logger.error("Could not add friend '%s' due to errors in the config file" % file)
def verifyMessage(self, message):
"""Verify a message
Args:
* message -- message object
"""
logger.debug("signature in command class is: "+str(message.signature))
logger.debug("attempting to verify command")
# semantic verification
# 1. Parameters for all msgTypes
# msgType
if not message.msgType:
logger.warn("Required parameter 'msgType' is missing in received message.")
raise customexceptions.InvalidMessage
else:
if not validators.isInteger(message.msgType):
logger.warn("Invalid parameter 'msgType' in received message, can only be an integer.")
raise customexceptions.InvalidMessage
# Protocol version
if not version.protocolVersion == message.protocolVersion:
logger.warn("The protocol version of the received message (" + str(message.protocolVersion) + ") does not match the protocol version of this node (" + str(version.protocolVersion) + ").")
raise customexceptions.InvalidProtocolVersion
# Signature
if not message.signature:
logger.warn("Signature is missing in received message")
raise customexceptions.InvalidMessage
# Hops
for h in message.hops:
if not validators.isAlphaNumeric(h):
logger.warn("Invalid characters in hops. Only alphanumeric characters are allowed.")
raise customexceptions.InvalidMessage
# Parameters
if not message.parameter:
logger.warn("Message contains no parameters!")
raise customexceptions.InvalidMessage
# 2. parameters for custom message types
if message.msgType == 1:
# Verify AttackerIP
if not ("AttackerIP" in message.parameter):
logger.warn("Required parameter 'AttackerIP' is missing in received message.")
raise customexceptions.InvalidMessage
else:
if not validators.isIPv4address(message.parameter['AttackerIP']):
logger.warn('Invalid parameter "AttackerIP" in received message.')
raise customexceptions.InvalidMessage
# Verify Timestamp
if not ("Timestamp" in message.parameter):
logger.warn("Required parameter 'Timestamp' is missing in received message.")
raise customexceptions.InvalidMessage
else:
if not validators.isInteger(message.parameter['Timestamp']):
logger.warn('Invalid parameter "Timestamp" in received message.')
raise customexceptions.InvalidMessage
# verify Trustlevel
if not 'Trustlevel' in message.parameter:
logger.warn('Required parameter "Trustlevel" in missing in received message.')
raise customexceptions.InvalidMessage
else:
if not (validators.isInteger(message.parameter['Trustlevel']) and 0 <= int(message.parameter['Trustlevel']) <= 100):
logger.warn('Invalid parameter "Trustlevel" in received message.')
raise customexceptions.InvalidMessage
elif message.msgType == 2 or message.msgType == 3:
if not ("TimeFrame" in message.parameter):
logger.warn("Required parameter 'TimeFrame' is missing in received message.")
raise customexceptions.InvalidMessage
else:
if not validators.isInteger(message.parameter['TimeFrame']):
logger.warn('Invalid parameter "TimeFrame" in received message.')
raise customexceptions.InvalidMessage
else:
logger.warn("Unknown message type: " + str(message.msgType))
raise customexceptions.InvalidMessage
# signature
logger.debug("attempting to verify signature")
last_hop_uid = message.hops[len(message.hops)-1]
logger.debug("Last hop's uid is: %s" % ( last_hop_uid ) )
# look for known signatures
sender = None
for friend in self.friends:
logger.debug("Comparing last hops uid (%s) with one of our friends uid (%s)" % (last_hop_uid, friend.uid))
if friend.uid == last_hop_uid:
logger.debug("The message seems to be from our friend %s (uid: %s)" % ( friend.name, friend.uid) )
sender = friend
pk = M2Crypto.RSA.load_pub_key(sender.configpath)
break
if last_hop_uid == "local": # the message was signed with our own key
logger.debug("This message was signed with our own key.")
c = config.Config()
pk = M2Crypto.RSA.load_pub_key(c.pubkey)
sender = "local"
break
if sender == None:
logger.warning("The message could not be mapped to one of our friends!")
raise customexceptions.InvalidSignature
# load sender's public key
VerifyEVP = M2Crypto.EVP.PKey()
# Assign the public key to our VerifyEVP
VerifyEVP.assign_rsa(pk)
# Begin verification
VerifyEVP.verify_init()
# verify the message against it
VerifyEVP.verify_update (json.dumps(message.toSerializableDict()))
if(VerifyEVP.verify_final(message.signature.decode('hex')) != 1):
logger.warning('Signature doesnt match!')
return False
else:
logger.debug('Signature verified successfully')
message.sender = sender
return True
def dumpBanlist(self, timeframe):
"""Generates List of Bans
Args:
* timeframe (int): Show nodes that were inserted this many seconds ago or later
Returns:
JSON encoded list of known bans.
"""
banlist = []
if not timeframe:
timeframe = 3600
timeframestart = int(time()) - int(timeframe)
logger.debug("Dumping all nodes that were inserted after " + str(timeframestart))
for entry in self.banList:
if int(entry['Timestamp']) > int(timeframestart):
banlist.append(entry)
return json.dumps(banlist)
def requestBanlist(self):
"""Request a Ban List from all friends."""
for friend in self.friends:
logger.debug("Sending dump request to " + friend.name)
c = Command()
c.msgType = 3
c.hops = [ self.uid ]
c.protocolVersion = version.protocolVersion
c.parameter = { "TimeFrame": self.banTime or 3600 }
friend.sendCommand(c)
def cleanBanlist(self):
"""Purges expired bans, restarts itself after 60 seconds."""
logger.debug("Purging all entries from banlist that are older than %s seconds." % self.banTime)
if len(self.banList) > 0:
banListKeep = []
for ban in self.banList:
if ban['Timestamp'] + self.banTime > time():
banListKeep.append(ban)
else:
logger.info("Removed %s from internal banlist because the ban has expired." % ban['AttackerIP'])
self.banList = banListKeep
global cleaner
cleaner = threading.Timer(60,self.cleanBanlist)
cleaner.start()
def cleanBanlistStop(self):
"""stops cleanBanlist thread"""
cleaner.cancel()

270
fail2ban-p2p/odict.py Normal file
View File

@ -0,0 +1,270 @@
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.
# This file is not GPLv3 like the other code but licensed under the MIT license:
# http://opensource.org/licenses/MIT
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
pass
class OrderedDict(dict):
"""
Dictionary that remembers insertion order
.. note::
This module was taken from http://code.activestate.com/recipes/576693/
and is not GPL but licensed under the MIT license.
"""
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as for regular dictionaries.
# The internal self.__map dictionary maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. Signature is the same as for
regular dictionaries, but keyword arguments are not recommended
because their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link which goes at the end of the linked
# list, and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[0]
last[1] = root[0] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'
root = self.__root
curr = root[1]
while curr is not root:
yield curr[2]
curr = curr[1]
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
root = self.__root
curr = root[0]
while curr is not root:
yield curr[2]
curr = curr[0]
def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except AttributeError:
pass
dict.clear(self)
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root[0]
link_prev = link[0]
link_prev[1] = root
root[0] = link_prev
else:
link = root[1]
link_next = link[1]
root[1] = link_next
link_next[0] = root
key = link[2]
del self.__map[key]
value = dict.pop(self, key)
return key, value
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self]
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) items in od'
for k in self:
yield (k, self[k])
def update(*args, **kwds):
'''od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
'''
if len(args) > 2:
raise TypeError('update() takes at most 2 positional '
'arguments (%d given)' % (len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
# Make progressively weaker assumptions about "other"
other = ()
if len(args) == 2:
other = args[1]
if isinstance(other, dict):
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key]
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).
'''
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
# -- the following methods are only used in Python 2.7 --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)

65
fail2ban-p2p/parser.py Normal file
View File

@ -0,0 +1,65 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
import command
import re
import log
import pdb
import json
# constants for length of RELEASE and MSGTYPE
logger = log.initialize_logging("fail2ban-p2p." + __name__)
def getDictValue(dict, key):
"""Get a value from a dict.
Args:
* dict: The dictionary to get the value from
* key: Key of the value to fetch
Returns:
Corresponding value if the key exists or False.
"""
try:
return dict[key]
except KeyError, e:
return False
def parse(msg):
"""Parse a protocol message to a command object.
Args:
* msg -- the received message string
Returns:
command object
"""
logger.debug("parsing message...")
signed_dict = False
try:
signed_dict = json.loads(msg)
except ValueError, e:
logger.warning("The received message does not appear to be valid json.")
return False
if signed_dict:
message_dict = getDictValue(signed_dict, 'msg')
msg = command.Command()
msg.signature = getDictValue(signed_dict, 'signature')
msg.protocolVersion = getDictValue(signed_dict, 'protocolVersion')
msg.msgType = getDictValue(message_dict, 'msgType')
msg.parameter = getDictValue(message_dict, 'parameter')
msg.hops = getDictValue(message_dict, 'hops')
return msg

66
fail2ban-p2p/server.py Normal file
View File

@ -0,0 +1,66 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
from parser import parse
import log
import customexceptions
logger = log.initialize_logging("fail2ban-p2p." + __name__)
def serve(n, connection, address):
"""Starts the server listener socket to receive messages
Args:
* n -- node object
* connection -- client socket
* address -- IP address of the node that sent the message
"""
data = connection.recv(1024)
logger.debug("Parsing message: " + data)
command = parse(data)
if command:
logger.debug("command syntax verified")
try:
n.verifyMessage(command)
logger.debug("command signature verified")
n.addMessage(command)
if command.msgType == 2:
timeframe = int(command.parameter['TimeFrame'])
logger.debug("Requested Timeframe is: " + str(timeframe))
connection.send(n.dumpBanlist(timeframe))
else:
connection.send("OK\n")
except customexceptions.InvalidMessage, e:
connection.send("ERROR Invalid message\n")
logger.warn("This message made no sense.")
except customexceptions.InvalidSignature, e:
connection.send("ERROR invalid signature\n")
logger.warn("The Signature could not be verified")
except customexceptions.InvalidProtocolVersion, e:
connection.send("ERROR invalid protocol version\n")
else:
connection.send("Error\n")
logger.warn('invalid message')
connection.close()
#except Exception, e:
#logger.warn("During the validation of the received message the " +
#"exception \"%s\" occured" % (type(e),))
#logger.debug("The received command was: " + data)
#connection.send("ERROR\n")
#finally:
#connection.close()

41
fail2ban-p2p/util.py Normal file
View File

@ -0,0 +1,41 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
from odict import OrderedDict
def sort_recursive(dictionary):
"""
Recursively sorts nested dictionaries. Should not be applied if the
structures are nested too deeply and/or there is even the remote
possibility that the nesting of the passed dictionary contains a cyclic
structure.
Args:
dictionary (dict): A python dictionary
Returns:
A recursively sorted dictionary
Example:
>>> dict = { 'a': '2', 'c': 3, 'b': { 'e': 4, 'd': 1 }, 'f': 5}
>>> sort_recursive(dict)
OrderedDict([('a', '2'), ('b', OrderedDict([('d', 1), ('e', 4)])), ('c', 3), ('f', 5)])
"""
sorted_list = OrderedDict(sorted(dictionary.items(), key = lambda x: x[0]))
# TODO test for cyclic structures.
for key, value in sorted_list.items():
if type(value) is dict:
sorted_list[key] = sort_recursive(value)
return sorted_list
if __name__ == '__main__':
import doctest
doctest.testmod()

View File

@ -0,0 +1,60 @@
import re
def isInteger(n):
'''Check if a value is an integer
Args:
* n: the value that should be checked
Returns:
* False: Value is no integer
* True: Value is integer
'''
try:
# convert to string before testing to convert to int
# without this also False and True would pass here
int(str(n))
return True
except ValueError:
return False
def isAlphaNumeric(str):
'''Check if a string only contains alphanumeric characters
Args:
* str: the value that should be checked
Returns:
* False: String is not alphanumeric
* True: String is aplhanumeric
'''
try:
if re.match('^[A-Za-z0-9]*$', str):
return True
else:
raise
except:
return False
def isIPv4address(str):
'''Check if a string is a valid IPv4 address
Args:
* str: the string that should be checked
Returns:
* False: String is not an IPv4 address
* True: String is an IPv4 address
'''
try:
reIPv4 = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
if re.match(reIPv4, str):
return True
else:
raise
except:
return False
isIPv4address('1.2.3.300')

10
fail2ban-p2p/version.py Normal file
View File

@ -0,0 +1,10 @@
# Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
# Copyright 2013 Manuel Munz <manu at somakoma.de>
#
# This file is part of fail2ban-p2p.
#
# Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
# see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
version = "0.1.2"
protocolVersion = 2

22
scripts/build-release.sh Normal file
View File

@ -0,0 +1,22 @@
# Script/helper to make a release from fail2ban-p2p svn
# Before you checkout make sure you edited the files in debian directory
# At least edit debian/changelog. Use dch -v <version>-<revision> to create a new entry
tag=0.0.5
rev=1
svn co https://svn.physik.uni-augsburg.de/svn/fail2ban-p2p/tags/$tag
mv $tag fail2ban-p2p-${tag}-${rev}
cd fail2ban-p2p-${tag}-${rev}
rm -rf `find . -type d -name .svn`
cd ..
tar -cvzf fail2ban-p2p-${tag}-${rev}.tar.gz fail2ban-p2p-${tag}-${rev}
echo "Tarball fail2ban-p2p-${tag}-${rev}.tar.gz created"
echo "Now building debian package. Use m to build a 'multiple binary' package."
cd fail2ban-p2p-${tag}-${rev}
dh_make -f ../fail2ban-p2p-${tag}-${rev}.tar.gz --addmissing || echo "Something went wrong with dh_make, please check output and retry"
dpkg-buildpackage -us -uc || echo "Something went wrong with dpkg-buildpackage, please check output and retry"
echo "Now move the .tar.gz and the .deb to releases and commit :)"

5
setup.cfg Normal file
View File

@ -0,0 +1,5 @@
[install]
install-purelib=/usr/share/fail2ban-p2p
[sdist]
formats=bztar

63
setup.py Executable file
View File

@ -0,0 +1,63 @@
"""
Copyright 2013 Johannes Fuermann <johannes at fuermann.cc>
Copyright 2013 Manuel Munz <manu at somakoma.de>
This file is part of fail2ban-p2p.
Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. For details
see the file COPYING or http://www.gnu.org/licenses/gpl-3.0.en.html.
"""
"""
This script can be used to send a ban message to the own node.
To do this it will use the ip address and port given in the configfile
for this node.
"""
from distutils.core import setup
from os.path import isfile, join, isdir
import sys
from sys import argv
from glob import glob
sys.path.insert(1, "./fail2ban-p2p")
from version import version
longdesc = '''
Fail2Ban-P2P can be used to exchange information
about attackers between different hosts that are
running fail2ban in a P2P/F2F network.
'''
setup(
name = "fail2ban-p2p",
#version = version,
description = "exchange fail2ban attacker info between hosts using P2P",
long_description = longdesc,
version = version,
author = "Johannes Fuermann, Manuel Munz",
author_email = "foo@bar.xyz",
url = "https://svn.physik.uni-augsburg.de/projects/fail2ban-p2p",
license = "GPL",
platforms = "Posix",
scripts = [
'fail2ban-p2p.py',
'fail2ban-p2p-client.py'
],
packages = [
'fail2ban-p2p'
],
data_files = [
('/etc/fail2ban-p2p', glob("config/*.conf")),
('/etc/fail2ban-p2p/friends', glob('config/friends/*'))
]
)
# Update config file
if argv[1] == "install":
print
print "Please do not forget to update your configuration files."
print "They are in /etc/fail2ban-p2p/."
print