pax_global_header 0000666 0000000 0000000 00000000064 13332131607 0014511 g ustar 00root root 0000000 0000000 52 comment=d007374182fd4a2cd097358fd254d1c175bec361
conv-0.9.11/ 0000775 0000000 0000000 00000000000 13332131607 0012546 5 ustar 00root root 0000000 0000000 conv-0.9.11/.gitignore 0000664 0000000 0000000 00000000052 13332131607 0014533 0 ustar 00root root 0000000 0000000 .tox/*
dist/
docs/build
*.egg-info/
*.pyc
conv-0.9.11/.travis.yml 0000664 0000000 0000000 00000000244 13332131607 0014657 0 ustar 00root root 0000000 0000000 ---
sudo: false
language: python
python:
- "2.7"
- "3.5"
- "3.6"
install: "pip install -r dev_requirements.txt"
script:
- flake8
- python setup.py test
conv-0.9.11/LICENSE.txt 0000664 0000000 0000000 00000104374 13332131607 0014402 0 ustar 00root root 0000000 0000000
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
conv-0.9.11/LICENSE_Apache.txt 0000664 0000000 0000000 00000026123 13332131607 0015636 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2017 Johannes Hubertz
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
conv-0.9.11/MANIFEST.in 0000664 0000000 0000000 00000000123 13332131607 0014300 0 ustar 00root root 0000000 0000000 include Makefile
include README.rst
include LICENSE.txt
include LICENSE_Apache.txt
conv-0.9.11/Makefile 0000664 0000000 0000000 00000000543 13332131607 0014210 0 ustar 00root root 0000000 0000000 FILES= Makefile README.txt LICENSE.txt iptables_converter.py iptables_converter_tests.py
doc:
$(MAKE) -C docs html
clean:
@python setup.py clean --bdist-base build
@rm -rf *~ *.pyc .pybuild/ .coverage build docs/build/* .tox
@rm -rf iptables_converter.egg-info
@rm -rf dist __pycache__ *.py3
$(MAKE) -C docs clean
@[ ! -d debian ] || dh_clean
conv-0.9.11/README.rst 0000664 0000000 0000000 00000005436 13332131607 0014245 0 ustar 00root root 0000000 0000000 .. image:: https://travis-ci.org/sl0/conv.svg?branch=master
:target: https://travis-ci.org/sl0/conv
:align: right
iptables-converter
==================
**iptables-converter**: convert iptables to iptables-save format, output
comes with [0:0] for iptables-restore -c
**ip6tables-converter**: convert ip6tables to ip6tables-save format,
output comes with [0:0] for ip6tables-restore -c
**Source**: https://github.com:sl0/conv.git
**Version**: 0.9.11
**Date**: 2019-08-04
**Licenses**:
- GNU GENERAL PUBLIC LICENSE Version 3 or any later
- Apache License Version 2.0
**Author**: Johannes Hubertz johannes@hubertz.de
**iptables-converter** speeds up loading of iptables-commands by
converting them to iptables-save format, and then loading them through
iptables-restore is much more quicker than loading the plain commands.
The loading itself is not part of iptables-converter.
Usage:
::
iptables-converter [ -d destination ] [ -s source ] [ --sloppy ]
ip6tables-converter [ -d destination ] [ -s source ] [ --sloppy ]
This assumes that **source** is a plain ascii-file containing lines
starting with **iptables** to build a firewall ruleset. Lines starting
with **/sbin/iptables** are understood as well. Omitting -s source
defaults to reading a file named **rules**. An optional **sloppy**
parameter makes premature definitions (-N name) of any user defined
chains unneccessary, they are defined automatically by first mentioning
them. Optionally **-d destination** writes everything into the given
destination file since verstion 0.9.10. Omitting this option results in
writing Output to stdout, which is the default behavior. Packet-counters
and byte-counters include [0:0] which keeps compatibility to
iptables-restore as well as to **iptables-restore -c**.
**ip6tables-converter** works for ip6tables just the same way.
Both they work for **filter**, **mangle**, **nat** and **raw** tables,
**security** tables are not supported for now.
From version 0.9.10 on it works as a python-module using entry-points
for easier imports. For your convienience, the module is named
**iptables\_conv**.
At travis-ci.org the **tests** are run automatically, thanks to Guido!
To run them locally, please use python:
::
python setup test
or tox, which is the preferred testrunner.
**iptables-converter** is tested to work well with python2.7, python3.5
and python3.6. The tests are
done using pytest for easier writing future testcases. Some sphinx
documentation is prepared. Debian packages are provided for the
`binaries `__ and
`sphinx-documentation `__.
git-buildpackage creates them on the fly. RPMs may be created by python::
setup.py bdist_rpm
Any comments welcome.
Have fun!
Johannes
conv-0.9.11/dev_requirements.txt 0000664 0000000 0000000 00000000035 13332131607 0016666 0 ustar 00root root 0000000 0000000 wheel
flake8
pytest
coverage
conv-0.9.11/docs/ 0000775 0000000 0000000 00000000000 13332131607 0013476 5 ustar 00root root 0000000 0000000 conv-0.9.11/docs/Makefile 0000664 0000000 0000000 00000012765 13332131607 0015151 0 ustar 00root root 0000000 0000000 # 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) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.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 ' where 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/iptables-converter.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/iptables-converter.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/iptables-converter"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/iptables-converter"
@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."
conv-0.9.11/docs/source/ 0000775 0000000 0000000 00000000000 13332131607 0014776 5 ustar 00root root 0000000 0000000 conv-0.9.11/docs/source/conf.py 0000664 0000000 0000000 00000020423 13332131607 0016276 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# iptables-converter documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 21 16:47:22 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
from iptables_conv 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('.'))
sys.path.insert(0, os.path.abspath('../..'))
sys.path.insert(0, os.path.abspath('../../tests'))
# -- 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.autodoc', 'sphinx.ext.doctest']
extensions = ['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'iptables-converter'
copyright = u'2013 - 2018, Johannes Hubertz'
# 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 = []
# 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
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
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 = []
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.
# available: agogo basic default epub haiku nature pyramid scrolls sphinxdoc traditional
#html_theme = 'classic'
html_theme = 'sphinx_rtd_theme'
# 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 = {}
html_theme_options = {
'prev_next_buttons_location': 'both',
}
# 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
# " v 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
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
html_show_sourcelink = False
# 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 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 = 'iptables-converter-doc'
# -- 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', 'iptables-converter.tex', u'iptables-converter Documentation',
u'Johannes Hubertz', '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
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', 'iptables-converter', u'iptables-converter Documentation',
[u'Johannes Hubertz'], 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', 'iptables-converter', u'iptables-converter Documentation',
u'Johannes Hubertz', 'iptables-converter', '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
texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
conv-0.9.11/docs/source/converter-tests.rst 0000664 0000000 0000000 00000015030 13332131607 0020676 0 ustar 00root root 0000000 0000000 ==========================
iptables-converter - tests
==========================
Untested software, that means software which isn't accompanied by automated
functional tests, is assumed to be broken by design. As iptables-converter is
written in python, use of the popular unittests is done for your convienience.
The unittests were developed and run by nose, which later have been replaced
by pytest. The advantages of pytest over nose are much simpler tests and less
overhead. So all newer testcases are written for pytest and thus rely on the
plain python assert statement.
Two testclasses are build: Chains_Test and Tables_Test accordingly to the
two classes from which the iptables-converter module and script is build from.
Basic usage
-----------
Lets see, how to run the tests within the source-tree by just calling
pytest::
$ pytest
========================== test session starts ==========================
platform linux -- Python 3.6.6, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /home/hans/devel/conv, inifile:
plugins: cov-2.5.1
collected 37 items
tests/test_iptables_converter.py ............................
tests/test_iptables_options.py .........
======================= 37 passed in 0.05 seconds =======================
$
All tests passed. Fine.
Verbose usage
-------------
If you want to see more, just add a **-v** to
the commandline::
$ pytest -v
================================ test session starts =================================
platform linux -- Python 3.6.6, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- /home/hans/wb/bin/python3.6
cachedir: .cache
rootdir: /home/hans/devel/conv, inifile:
plugins: cov-2.5.1
collected 37 items
tests/test_iptables_converter.py::Chains_Test::test_01_create_a_chain_object PASSED
tests/test_iptables_converter.py::Chains_Test::test_02_prove_policies PASSED
tests/test_iptables_converter.py::Chains_Test::test_03_tables_names PASSED
tests/test_iptables_converter.py::Chains_Test::test_04_flush PASSED
tests/test_iptables_converter.py::Chains_Test::test_05_new_chain PASSED
tests/test_iptables_converter.py::Chains_Test::test_06_new_existing_chain_fails PASSED
tests/test_iptables_converter.py::Chains_Test::test_07_insert_rule_fail PASSED
tests/test_iptables_converter.py::Chains_Test::test_08_insert_rule_fail PASSED
tests/test_iptables_converter.py::Chains_Test::test_09_insert_rule_works PASSED
tests/test_iptables_converter.py::Chains_Test::test_10_append_rule PASSED
tests/test_iptables_converter.py::Chains_Test::test_11_remove_predef_chain PASSED
tests/test_iptables_converter.py::Chains_Test::test_12_remove_chain PASSED
tests/test_iptables_converter.py::Chains_Test::test_13_illegal_command PASSED
tests/test_iptables_converter.py::Tables_Test::test_01_create_a_tables_object PASSED
tests/test_iptables_converter.py::Tables_Test::test_02_nat_prerouting PASSED
tests/test_iptables_converter.py::Tables_Test::test_03_mangle_table PASSED
tests/test_iptables_converter.py::Tables_Test::test_04_raw_table PASSED
tests/test_iptables_converter.py::Tables_Test::test_05_not_existing_chain PASSED
tests/test_iptables_converter.py::Tables_Test::test_06_read_not_existing_file PASSED
tests/test_iptables_converter.py::Tables_Test::test_07_read_empty_file PASSED
tests/test_iptables_converter.py::Tables_Test::test_08_reference_one PASSED
tests/test_iptables_converter.py::Tables_Test::test_09_shell_variables PASSED
tests/test_iptables_converter.py::Tables_Test::test_10_shell_functions PASSED
tests/test_iptables_converter.py::Tables_Test::test_11_reference_sloppy_one PASSED
tests/test_iptables_converter.py::Tables_Test::test_12_create_a_tables6_object PASSED
tests/test_iptables_converter.py::Tables_Test::test_13_re6ference_one PASSED
tests/test_iptables_converter.py::Tables_Test::test_14_re6ference_sloppy_one PASSED
tests/test_iptables_converter.py::test_15_tables_printout PASSED
tests/test_iptables_options.py::test_01_iptables_converter_option_h PASSED
tests/test_iptables_options.py::test_02_iptables_converter_option_s PASSED
tests/test_iptables_options.py::test_03_iptables_converter_option_d PASSED
tests/test_iptables_options.py::test_04_iptables_converter_option_sd PASSED
tests/test_iptables_options.py::test_05_iptables_converter_main_dlft PASSED
tests/test_iptables_options.py::test_06_iptables_converter_main_ok PASSED
tests/test_iptables_options.py::test_07_iptables_converter_main_write PASSED
tests/test_iptables_options.py::test_08_iptables_converter_option_dest_file PASSED
tests/test_iptables_options.py::test_09_iptables_converter_option_source_file PASSED
============================= 37 passed in 0.06 seconds ==============================
$
Code coverage
-------------
If you want to get to know something about the test-coverage, just
give pytest a try::
$ pytest --cov=iptables_conv --cov-report=term-missing
=============================== test session starts ================================
platform linux -- Python 3.6.6, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /home/hans/devel/conv, inifile:
plugins: cov-2.5.1
collected 37 items
tests/test_iptables_converter.py ............................
tests/test_iptables_options.py .........
----------- coverage: platform linux, python 3.6.6-final-0 -----------
Name Stmts Miss Cover Missing
-------------------------------------------------------------------
iptables_conv/__init__.py 8 0 100%
iptables_conv/iptables_converter.py 230 7 97% 28-29, 72, 129-131, 314
-------------------------------------------------------------------
TOTAL 238 7 97%
============================ 37 passed in 0.10 seconds =============================
$
If you like to have a look into the sources, you will find the
tests directory. Therein all the tests reside. I hope they are
self explaining.
testrunner
----------
To simply run the tests, **setup.py** has a test target::
$ python setup.py test
...
$
This runs flake8 and pytest.
If you prefer less typing::
$ pytest
...
$
Or, possibly the best way of doing is the following super power.
Check tests, syntax and style
-----------------------------
For your convenience, a **tox.ini** is prepared.
Give tox a try to check altogether in one single run:
- python2.7
- python3.5
- python3.6
- flake8
- docs
conv-0.9.11/docs/source/index.rst 0000664 0000000 0000000 00000000735 13332131607 0016644 0 ustar 00root root 0000000 0000000 .. iptables-converter documentation master file, created by
sphinx-quickstart on Sun Jul 21 16:47:22 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. include:: ../../README.rst
.. toctree::
:maxdepth: 1
iptables-converter
converter-tests
sources
Contents:
.. toctree::
:maxdepth: 2
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
conv-0.9.11/docs/source/iptables-converter.rst 0000664 0000000 0000000 00000021321 13332131607 0021337 0 ustar 00root root 0000000 0000000 ================================
iptables-converter - description
================================
In linux iptables exists since kernel version 2.4.
A corresponding userland command **iptables** is used to
control them.
The tables are grouped in filter, nat, mangle and raw.
In every group there are chains, which contain more or
less traffic specific rules. Predefined in filter tables
are INPUT, FORWARD and OUTPUT chain. Perhaps you like to
read the fine manuals about the iptables command in Linux
to get to know more about these.
Usually a systemadministrator wants to write his rules in
a shell script, which is run within the boot sequence or
every now and then on every change... Over the time this
script will grow. The longer it gets, the more time takes
it to complete. Exactly this is the reason, why
**iptables-converter** was written. Only motivation was to
speed up the loading of long scripts with multiple iptables
commands.
The **iptables-converter** is a pure python script with
two entrypoints:
- **iptables-converter**
- **ip6tables-converter**
They reside in linux userland, that means to run one of them
you don't need root priviledges, which are only needed to load
the output of the converters into the kernelspace.
Command line interface
======================
To have an idea which command line options are supported,
just ask it for help::
$ iptables-converter --help
Usage: iptables-converter --help | -h
iptables-converter: version 0.9.11 Have Fun!
Options:
-h, --help show this help message and exit
-d DESTFILE, --dest-file=DESTFILE
output filename, default: stdout
-s SOURCEFILE, --source-file=SOURCEFILE
file with iptables commands, default: rules
--sloppy -N name-of-userchain is inserted automatically, by
default -N is neccessary in input
**ip6tables-converter** surprisingly behaves exactly the same way, except from
the '6' in the command and version line::
$ ip6tables-converter --help
Usage: ip6tables-converter --help | -h
ip6tables-converter: version 0.9.11 Have Fun!
Options:
-h, --help show this help message and exit
-d DESTFILE, --dest-file=DESTFILE
output filename, default: stdout
-s SOURCEFILE, --source-file=SOURCEFILE
file with iptables commands, default: rules
--sloppy -N name-of-userchain is inserted automatically, by
default -N is neccessary in input
The only difference in between them is what is looked at.
iptables-converter just handles lines starting with
**iptables** or **/sbin/iptables**, ip6tables-converter
only lines starting with **ip6tables** or **/sbin/ip6tables**.
DEST- and SOURCEFILE
--------------------
These should be clear, the default values are build in for
your convenience only. A script generating iptables command
writes them into a file named *rules*, which is then read by
the converter, if the **-s** option is not used. The converters
ouptut is then written to **stdout**, if the **-d** option is
not used. So it might be piped or somehow else processed.
--sloppy
--------
The option **--sloppy** perhaps needs some explanation.
Usually the iptables command insists on defined chains,
especially you cannot insert or append a rule into a
non-existent user defined chain. Especially the
**-N UserChain** is needed normally in advance to the
append operation. Inserting into an empty chain is
forbidden as well. By using the **--sloppy** option this
**-N** command is not needed in the input for the
converter as it defines the UserCHain automatically on
the first occurance of any.
Default operating
=================
Assume a plain file with following contents::
iptables -F
iptables -t nat -F
iptables -N USER_CHAIN
iptables -A INPUT -p tcp --dport 23 -j ACCEPT
iptables -A USER_CHAIN -p icmp -j DROP
iptables -P INPUT DROP
iptables -t nat -A POSTROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15
iptables -t nat -A PREROUTING -d 192.0.2.5/32 -p tcp --dport 443 -j DNAT --to-destination 10.0.0.5:1500
As times goes by, this script will grow. The more lines
it has, the longer will it take to be loaded. This is
because every iptables statement needs to modify the
kernels iptables as an atomar operation, which is a
lot of overhead from locking the tables, modifying
and unlocking them. There should be a quicker way of
getting things done. Using iptables-save we can save
easily the actual ruleset from the kernel to a file.
To load it's content into the kernel again is a very
quick action compared to the loading of the originating
shellscript. The iptables-restore operation is one
atomar operation from the kernels view regardless of
the number of modifications. It's clear to be the much
quicker the more lines are covered. The disadvantage
of this proceeding is, the table, f.e. the filter
tables, are loaded at once, i.e. no appending or
inserterting using the *same* command is possible.
You only need a complete set of iptable commands
within a file, just like iptables-save gives it.
So the idea came up to have a converter just for
saving time.
Lets assume, the file shown above is named **generated-rules**,
then we have easy going::
$ iptables-converter -s generated-rules -d converted-rules
$ cat converted-rules
*raw
:OUTPUT ACCEPT [0:0]
:PREROUTING ACCEPT [0:0]
COMMIT
*nat
:OUTPUT ACCEPT [0:0]
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -d 192.0.2.5/32 -p tcp --dport 443 -j DNAT --to-destination 10.0.0.5:1500
-A POSTROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15
COMMIT
*mangle
:FORWARD ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
*filter
:FORWARD ACCEPT [0:0]
:INPUT DROP [0:0]
:USER_CHAIN - [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -p tcp --dport 23 -j ACCEPT
-A USER_CHAIN -p icmp -j DROP
COMMIT
$
On the same machine or after beeing transferred to another
one, the **converted-rules** file can be loaded into the kernel
by using the command **iptables-restore** as *root user*::
# iptables-restore -c converted-rules
Of course you use pathnames where filenames are mentioned.
Usage example
-------------
So you probably may want to run the converter
from within a shell script or the like::
#!/bin/bash
set -e
INPUT_FILE=rules
OUTPUT_FILE=iptables-converted
# needs to be executable as indicator that writing has ended
[ ! -r $INPUT_FILE ] && exit 0
[ ! -x $INPUT_FILE ] && exit 0
iptables-converter.py -s $INPUT_FILE -d $OUTPUT_FILE
# do it only once!
mv $INPUT_FILE $INPUT_FILE}.old
iptables-restore < $OUTPUT_FILE
echo "$INPUT_FILE successfully converted and loaded"
exit 0
# EoF
Error handling
==============
In accidental cases of errors the converter should give you a
traceback wherin the word **ConverterError** appears. This is to
let you get to know, where in your whole programming universe
the error happend.
Two things can not be handled: Shell functions and shell
variables, because the converter does not interpret your
input-file.
Shell functions and shell commands
----------------------------------
As the file which is read is not interpreted
in any way, there are few known error conditions:
#) the file contains some shell variables, indicated by '$',
this leads to an errormessage and exits immediately with returncode 1.
#) the file contains some shell functions, indicated by '(' and/or ')',
this leads to an errormessage and exits immediately with returncode 1.
If you have such a file, and you want to speed up by converting, please
execute it and feed the output as a file to iptables-converter.
Non existent user chains
------------------------
iptables-converter does some more error-checking while reading input.
Normal behavior is to raise an **ConverterError**, if any append or insert
statement to an userdefined chain is not preceeded by a corresonding chain
creation statement '-N'. This may be changed to a more smooth
handling with an additional commandline option **--sloppy**.
Having this, a non existent userchain is created on the fly when
the first append statement is seen. So it is set as first entry gracefully.
Inserting into an emtpy chain anyhow raises an error as iptables-restore
would do it later on trying to set the files content into the kernel.
Not implemented
---------------
Just to mention it: **iptables -E xyz** and **iptables -L** are not
implemented in the **iptables-converter** and throw exceptions for now!
conv-0.9.11/docs/source/sources.rst 0000664 0000000 0000000 00000001173 13332131607 0017215 0 ustar 00root root 0000000 0000000 iptables-converter - pythonic view
==================================
module: iptables_conv
---------------------
.. automodule:: iptables_conv
:members:
.. autoclass:: iptables_conv.iptables_converter.ConverterError
:members:
.. autoclass:: iptables_conv.iptables_converter.Chains
:members:
.. autoclass:: iptables_conv.iptables_converter.Tables
:members:
module: tests
-------------
From 0.9.10 on all future tests will be run by pytest. Prior
tests are written to use the unittest module.
.. automodule:: tests.test_iptables_converter
:members:
.. automodule:: tests.test_iptables_options
:members:
conv-0.9.11/iptables_conv/ 0000775 0000000 0000000 00000000000 13332131607 0015376 5 ustar 00root root 0000000 0000000 conv-0.9.11/iptables_conv/__init__.py 0000664 0000000 0000000 00000002602 13332131607 0017507 0 ustar 00root root 0000000 0000000 # vim: set fileencoding=utf-8 :
#
# (C) 2016,2017 Johannes Hubertz
# 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, please see
#
#
# Additionally this program is licensed under the terms of the
# Apache License, Version 2, see the top level directory right here,
# or you can view there:
#
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__author__", "__author_email__",
"__license__", "__url__", "__version__",
]
__title__ = "iptables-converter"
__author__ = "Johannes Hubertz"
__author_email__ = "johannes@hubertz.de"
__license__ = "GNU General Public License version 3 or later, Apache License Version 2"
__url__ = "https://github.com/sl0/conv.git"
__version__ = "0.9.11"
conv-0.9.11/iptables_conv/iptables_converter.py 0000775 0000000 0000000 00000031332 13332131607 0021647 0 ustar 00root root 0000000 0000000 #
# -*- coding: utf-8 -*-
#
"""
iptables_converter.py:
convert iptables commands within a script
into a correspondig iptables-save script
default filename to read is rules, to read some other
file, append: -s filename
default output is written to stdout, for writing
to some file, append: -d filename
Author: Johannes Hubertz
Date: 2017-11-16
Version: see __init__.version
License: GNU General Public License version 3 or later
Apache License Version 2.0
Have Fun!
"""
from __future__ import print_function
try:
from collections import UserDict
except ImportError:
from UserDict import UserDict
from optparse import OptionParser
import re
import os
import sys
from .__init__ import __version__
class ConverterError(Exception):
pass
class Chains(UserDict):
""" chains are grouped in iptables
:param str name: chain group name, 'filter', 'nat', ...
:param list tables: list of chains
:param bool sloppy: needs '-N'(default) or not
:return: object representing chain group
:rtype: Chains
:raises ConverterError: on some illegal conditions
"""
def __init__(self, name, tables, sloppy=False):
""" init Chains object
"""
UserDict.__init__(self)
self.name = name
self.tables = tables
self.predef = tables
self.sloppy = sloppy
self.reset() # name, tables)
def put_into_fgr(self, content):
""" fill this line into this tabular
:param str content: one line of inputfile
:return: None
:raises ConverterError: on some illegal conditions
"""
self.length += 1
if len(content) == 0:
return
elements = content.split()
action = elements[0]
if "-t" in action:
elements.pop(0) # remove 1st: -t
fname = elements.pop(0)
legals = ["filter", "nat", "raw", "mangle"]
if fname not in legals:
msg = "Valid is one of %s, got: %s" % (legals, fname)
raise ConverterError(msg)
action = elements[0]
content = "" # rebuild content from here
for elem in elements:
content = content + elem + " "
if len(elements) > 1:
chain_name = elements[1]
if "-F" in action:
self.reset()
return
if "-P" in action:
elements.pop(0)
cha = elements.pop(0)
new = elements.pop(0)
if new not in ["ACCEPT", "DROP", "REJECT"]:
msg = "Illegal policy: % s" % (new)
raise ConverterError(msg)
self.poli[cha] = new
return
if "-X" in action:
predef = ['INPUT', 'FORWARD', 'OUTPUT',
'PREROUTING', 'POSTROUTING']
rem_chain_name = elements.pop(1)
if rem_chain_name in predef:
msg = "Cannot remove predefined chain"
raise ConverterError(msg)
if rem_chain_name in self.data:
self.data[rem_chain_name] = [] # empty list
self.poli[rem_chain_name] = "-" # empty policy, no need
self.data.pop(rem_chain_name)
return
if "-N" in action:
new_chain_name = elements.pop(1)
existing = self.data.keys()
if new_chain_name in existing:
msg = "Chain %s already exists" % (new_chain_name)
raise ConverterError(msg)
self.data[new_chain_name] = [] # empty list
self.poli[new_chain_name] = "-" # empty policy, no need
return
if "-I" in action:
chain_name = elements[1]
existing = self.data.keys()
if chain_name not in existing:
msg = "invalid chain name: %s" % (chain_name)
if not self.sloppy:
raise ConverterError(msg)
else:
new_chain_name = elements[1]
self.data[new_chain_name] = []
self.poli[new_chain_name] = '-'
stuff = self.data[chain_name]
if len(stuff) > 0:
stuff.insert(0, content)
else:
msg = "Empty chain %s allows append only!" % (chain_name)
raise ConverterError(msg)
self.data[chain_name] = stuff
return
if "-A" in action:
chain_name = elements[1]
existing = self.data.keys()
if chain_name not in existing:
msg = "invalid chain name: %s" % (chain_name)
if not self.sloppy:
raise ConverterError(msg)
else:
new_chain_name = elements[1]
self.data[new_chain_name] = []
self.poli[new_chain_name] = '-'
stuff = self.data[chain_name]
stuff.append(content)
self.data[chain_name] = stuff
return
msg = "Unknown filter command in input:" + content
raise ConverterError(msg)
def reset(self):
""" action method for iptables -F
"""
self.poli = {} # empty dict
self.length = 0
self.policy = "-"
for tabular in self.tables:
self.data[tabular] = []
self.poli[tabular] = "ACCEPT"
class Tables(UserDict):
""" some chaingroups in tables are predef: filter, nat, mangle, raw
:param str destfile: which file or pathname is to be written
:param str sourcefile: which file or pathname is to be read
:param bool sloppy: '-N' is needed(default) or not
:param int ipversion: 4(default) or 6
:return: Tables after read sourcefile written into destfile
:rtype: Tables
:raises ConverterError: on some illegal conditions
"""
def __init__(self,
destfile,
sourcefile="reference-one",
sloppy=False,
ipversion=4
):
"""init Tables Object is easy going"""
UserDict.__init__(self)
self.destfile = destfile
self.sourcefile = sourcefile
self.sloppy = sloppy
self.linecounter = 0
self.tblctr = 0
self.patterns = ""
self.reset(sourcefile, ipversion)
def reset(self, sourcefile, ipversion):
"""all predefined Chains aka lists are setup as new here
:param str sourcefile: file to be read
:param int ipversion: 4 or 6
:return: None
"""
self.patterns = ['^iptables', '^/sbin/iptables', ]
if ipversion == 6:
self.patterns = ['^ip6tables', '^/sbin/ip6tables', ]
filt = ["INPUT", "FORWARD", "OUTPUT"]
filters = Chains("filter", filt, self.sloppy)
mang = ["PREROUTING", "INPUT", "FORWARD", "OUTPUT", "POSTROUTING", ]
mangle = Chains("mangle", mang, self.sloppy)
# kernel 2.6.32 has no INPUT in NAT!
nats = ["PREROUTING", "OUTPUT", "POSTROUTING"]
nat = Chains("nat", nats, self.sloppy)
raws = ["PREROUTING", "OUTPUT", ]
raw = Chains("raw", raws, self.sloppy)
self.data["filter"] = filters
self.data["mangle"] = mangle
self.data["nat"] = nat
self.data["raw"] = raw
if len(sourcefile) > 0:
self.linecounter = self.read_file(sourcefile)
def table_printout(self):
"""printout nonempty tabulars in fixed sequence"""
self.destfile.write("# generated from: %s\n" % (self.sourcefile))
for key in ["raw", "nat", "mangle", "filter"]:
count = self.data[key].length
if count > -1:
self.destfile.write("*%s\n" % (self.data[key].name))
for chain in self.data[key].keys():
poli = self.data[key].poli[chain]
self.destfile.write(":%s %s [0:0]\n" % (chain, poli))
for chain in self.data[key].values():
for elem in chain:
self.destfile.write(elem)
self.destfile.write('\n')
self.destfile.write("COMMIT\n")
def put_into_tables(self, line):
"""put line into matching Chains-object
:param line: one line of inputfile
:return: None
"""
elements = line.split()
elements.pop(0) # we always know, it's iptables
rest = ""
for elem in elements: # remove redirects and the like
if ">" not in elem:
rest = rest + elem + " " # string again with single blanks
fam = "filter"
if "-t nat" in line: # nat filter group
fam = "nat"
elif "-t mangle" in line: # mangle filter group
fam = "mangle"
elif "-t raw" in line: # raw filter group
fam = "raw"
fam_dict = self.data[fam] # select the group dictionary
fam_dict.put_into_fgr(rest) # do action thers
def read_file(self, sourcefile):
""" open file or error
:param sourcefile: file or pathname of file to be read
:return: file_descriptor
:raises ConverterError: on IOError
"""
try:
with open(sourcefile, 'r') as file_descriptor:
return self.read(file_descriptor)
except IOError as err:
raise ConverterError(str(err))
def read(self, file_descriptor):
"""read data from file like object into Tables-object
:param file_descriptor: filedescriptor of file to be read
:return: None
:raises ConverterError: on some illegal conditions
"""
self.linecounter = 0
self.tblctr = 0
try:
for this_line in file_descriptor:
line = str(this_line.strip())
self.linecounter += 1
if line.startswith('#'):
continue
for element in ['\$', '\(', '\)', ]:
if re.search(element, line):
mstart = "Line %d:\n%s\nplain files only, " % \
(self.linecounter, line)
if element in ['\(', '\)', ]:
merr = "unable to convert shell functions, abort"
else:
merr = "unable to resolve shell variables, abort"
msg = mstart + merr
raise ConverterError(msg)
for pattern in self.patterns:
if re.search(pattern, line):
self.tblctr += 1
self.put_into_tables(line)
except ValueError as err:
raise ConverterError(str(err))
def my_options():
""" commandline options assembly
:returns: :class: OptionParser
"""
version = "version %s" % __version__
usage = "usage: %prog --help | -h \n\n\t%prog: " + version
usage = usage + "\tHave Fun!"
parser = OptionParser(usage)
parser.disable_interspersed_args()
parser.add_option("-d", "--dest-file", dest="destfile",
type="string",
help="output filename, default: stdout\n")
parser.add_option("-s", "--source-file", dest="sourcefile",
type="string",
help="file with iptables commands, default: rules\n")
parser.add_option("--sloppy", "", dest="sloppy",
action="store_true", default=False,
help="-N name-of-userchain is inserted automatically,\n"
"by default -N is neccessary in input\n")
(options, _) = parser.parse_args()
return options
def main():
""" main parses options, filnames and the like
option -s needs input-filename to be read,
if it is not given, it defaults to: rules.
option -d needs output-filename to be written,
if it is not given, it defaults to: sys.stdout
"""
options = my_options()
if options.sourcefile is None:
options.sourcefile = "rules"
sourcefile = options.sourcefile
if options.destfile is not None:
destfile = open(options.destfile, 'w')
else:
destfile = sys.stdout
ipversion = 4
if os.path.basename(sys.argv[0]).startswith("ip6"):
ipversion = 6
try:
chains = Tables(destfile,
sourcefile,
options.sloppy,
ipversion=ipversion
)
chains.table_printout()
except ConverterError as err:
print(str(err), file=sys.stderr)
return 1
finally:
if destfile != sys.stdout:
destfile.close()
return 0
conv-0.9.11/man/ 0000775 0000000 0000000 00000000000 13332131607 0013321 5 ustar 00root root 0000000 0000000 conv-0.9.11/man/ip6tables-converter.8 0000664 0000000 0000000 00000004751 13332131607 0017317 0 ustar 00root root 0000000 0000000
.\"Created with GNOME Manpages Editor Wizard gmanedit
.TH ip6tables-converter 8 "August 2018" "Johannes Hubertz" " "
.SH NAME
ip6tables-converter \- program to convert ip6tables commands from file to ip6tables-restore format
.SH SYNOPSIS
.B ip6tables-converter [options]
.SH DESCRIPTION
The
.B ip6tables-converter
takes a regular file containing a series of iptables
invocations and converts such a sequence to a format compatible with
the
.B ip6tables-restore
command. No attempt is made to reorder the sequence of the commands,
especially nothing in the input is interpreted in any way.
All input lines not starting with "ip6tables" or "/sbin/ip6tables"
are ignored. Any input lines starting with "#" are treated as comments
and therefore are ignored.
.PP
if \fBip6tables-converter\fP is run without any arguments, it tries to read a file named
.B "rules"
in workdir. Output is written to
.B stdout
That's the tribute to my way of doing.
.PP
Something needs to be mentioned:
.B iptables -E
intellectually still is an unsolved problem and not implemented for now, sorry.
Thank you for any hints of how to do it, I can't imagine because of some lacks in my
brain.
.SH EXIT STATUS
Normally ip6tables-converter returns a value of 0. In accidental case of
.B errors
exit status 1 is returned. For example, if there are shell variables or shell functions
in the inputfile, these are treated as error, which is reported. To avoid these,
execute your scripts and feed their output as a file to ip6tables-converter.
.SH VERSIONS
ip6tables-converter
.B should
be compatibe to any iptables implementations out in the wild. If not, keep me
informed, thanks. I'll do my very best.
.SH OPTIONS
.B -d filename
or
.B --dest-file=Destinationfile
This options argument defines the destination filename, where the output is written to.
If omitted, output is written to
.B stdout
for your convienience and nowhere else. So you can inspect it and write to file
for later feeding the ip6tables-restore command.
.B -s filename
or
.B --source-file=Sourcefile
This options argument names the source file, where input is read from. If omitted, the
default filename is "rules".
.B --sloppy
This indicates '-N UserChain' is not required prior to mentioning any UserChain
input or append, the chain is build on the fly. It was build in for special user
request.
.SH AUTHOR
Johannes Hubertz wrote this from 2013 to 2018.
Any comments welcome anytime.
.SH "SEE ALSO"
.BR iptables (8)
.BR iptables-save (8)
.BR iptables-restore (8)
conv-0.9.11/man/iptables-converter.8 0000664 0000000 0000000 00000004733 13332131607 0017231 0 ustar 00root root 0000000 0000000
.\"Created with GNOME Manpages Editor Wizard gmanedit
.TH iptables-converter 8 "August 2018" "Johannes Hubertz" " "
.SH NAME
iptables-converter \- program to convert iptables commands from file to iptables-restore format
.SH SYNOPSIS
.B iptables-converter [options]
.SH DESCRIPTION
The
.B iptables-converter
takes a regular file containing a series of iptables
invocations and converts such a sequence to a format compatible with
the
.B iptables-restore
command. No attempt is made to reorder the sequence of the commands,
especially nothing in the input is interpreted in any way.
All input lines not starting with "iptables" or "/sbin/iptables"
are ignored. Any input lines starting with "#" are treated as comments
and therefore are ignored.
.PP
If \fBiptables-converter\fP is run without any arguments, it tries to read a file named
.B "rules"
in workdir. Output is written to
.B stdout
That's the tribute to my way of doing.
.PP
Something needs to be mentioned:
.B iptables -E
intellectually still is an unsolved problem and not implemented for now, sorry.
Thank you for any hints of how to do it, I can't imagine because of some lacks in my
brain.
.SH EXIT STATUS
Normally iptables-converter returns a value of 0. In accidental case of
.B errors
exit status 1 is returned. For example, if there are shell variables or shell functions
in the inputfile, these are treated as error, which is reported. To avoid these,
execute your scripts and feed their output as a file to iptables-converter.
.SH VERSIONS
iptables-converter
.B should
be compatibe to any iptables implementations out in the wild. If not, keep me
informed, thanks. I'll do my very best.
.SH OPTIONS
.B -d filename
or
.B --dest-file=Destinationfile
This options argument defines the destination filename, where the output is written to.
If omitted, output is written to
.B stdout
for your convienience and nowhere else. So you can inspect it and write to file
for later feeding the iptables-restore command.
.B -s filename
or
.B --source-file=Sourcefile
This options argument names the source file, where input is read from. If omitted, the
default filename is "rules".
.B --sloppy
This indicates '-N UserChain' is not required prior to mentioning any UserChain
input or append, the chain is build on the fly. It was build in for special user
request.
.SH AUTHOR
Johannes Hubertz wrote this from 2013 to 2018.
Any comments welcome anytime.
.SH "SEE ALSO"
.BR iptables (8)
.BR iptables-save (8)
.BR iptables-restore (8)
conv-0.9.11/re6ference-one 0000664 0000000 0000000 00000000621 13332131607 0015273 0 ustar 00root root 0000000 0000000 ip6tables -F
ip6tables -t nat -F
ip6tables -N USER_CHAIN
ip6tables -A INPUT -p tcp --dport 23 -j ACCEPT
ip6tables -A USER_CHAIN -p icmp -j DROP
ip6tables -P INPUT DROP
ip6tables -t nat -A POSTROUTING -s 2001:db8:dead::/64 -p tcp --dport 80 -j SNAT --to-source 2001:db8:feed::1
ip6tables -t nat -A PREROUTING -d 2001:db8:feed::1/128 -p tcp --dport 443 -j DNAT --to-destination 2001:db8:feed::1:1500
conv-0.9.11/re6ference-sloppy-one 0000664 0000000 0000000 00000000654 13332131607 0016625 0 ustar 00root root 0000000 0000000 ip6tables -F
ip6tables -t nat -F
# sloppy == no need to use ip6tables -N USER_CHAIN
ip6tables -A INPUT -p tcp --dport 23 -j ACCEPT
ip6tables -A USER_CHAIN -p icmp -j DROP
ip6tables -P INPUT DROP
ip6tables -t nat -A POSTROUTING -s 2001:db8:dead::/64 -p tcp --dport 80 -j SNAT --to-source 2001:db8:feed::1
ip6tables -t nat -A PREROUTING -d 2001:db8:feed::1/128 -p tcp --dport 443 -j DNAT --to-destination 2001:db8:feed::1:1500
conv-0.9.11/reference-one 0000664 0000000 0000000 00000000556 13332131607 0015214 0 ustar 00root root 0000000 0000000 iptables -F
iptables -t nat -F
iptables -N USER_CHAIN
iptables -A INPUT -p tcp --dport 23 -j ACCEPT
iptables -A USER_CHAIN -p icmp -j DROP
iptables -P INPUT DROP
iptables -t nat -A POSTROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15
iptables -t nat -A PREROUTING -d 192.0.2.5/32 -p tcp --dport 443 -j DNAT --to-destination 10.0.0.5:1500
conv-0.9.11/reference-sloppy-one 0000664 0000000 0000000 00000001013 13332131607 0016525 0 ustar 00root root 0000000 0000000 iptables -F
iptables -t nat -F
# sloppy == no need to use iptables -N USER_CHAIN
iptables -A INPUT -p tcp --dport 23 -j ACCEPT
iptables -A USER_CHAIN -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A USER_CHAIN -p icmp -j DROP
iptables -I USER_CHAIN -p icmp --icmp-type echo-request -j ACCEPT
iptables -P INPUT DROP
iptables -t nat -A POSTROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15
iptables -t nat -A PREROUTING -d 192.0.2.5/32 -p tcp --dport 443 -j DNAT --to-destination 10.0.0.5:1500
conv-0.9.11/setup.cfg 0000664 0000000 0000000 00000000424 13332131607 0014367 0 ustar 00root root 0000000 0000000 [bdist_wheel]
universal = 1
[flake8]
# E501: ignore line length
# E265: block comment should start with '# '
ignore=E501,E265
exclude=docs,setup.py
[build_sphinx]
source-dir = docs/source
build-dir = docs/build
all_files = 1
[upload_sphinx]
upload-dir = docs/build/html
conv-0.9.11/setup.py 0000664 0000000 0000000 00000003454 13332131607 0014266 0 ustar 00root root 0000000 0000000 """ setup.py for iptables-converter
"""
import os
import sys
import iptables_conv
from setuptools import setup, find_packages
if sys.argv[-1] == 'test':
dev_requirements = [
'pytest',
'flake8',
'coverage'
]
try:
_ = map(__import__, dev_requirements)
except ImportError as err:
err_msg = err.message.replace("No module named ", "")
msg = "%s is not installed. Install your test requirments." % err_msg
raise ImportError(msg)
os.system('flake8 iptables_conv tests')
os.system('py.test')
sys.exit()
setup(name='iptables-converter',
description='convert set of iptables-commands to iptables-save format',
long_description=open('README.rst').read(),
version=iptables_conv.__version__,
license=iptables_conv.__license__,
author=iptables_conv.__author__,
author_email=iptables_conv.__author_email__,
url=iptables_conv.__url__,
platforms=['Linux', ],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: '
'GNU General Public License v3 or later (GPLv3+)',
'License :: OSI Approved :: Apache Software License',
'Intended Audience :: System Administrators',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Security',
'Topic :: System :: Networking :: Firewalls',
'Topic :: Utilities',
],
packages=find_packages(exclude=['tests', ]),
entry_points={
'console_scripts': [
'iptables-converter=iptables_conv.iptables_converter:main',
'ip6tables-converter=iptables_conv.iptables_converter:main',
],
},
)
conv-0.9.11/tests/ 0000775 0000000 0000000 00000000000 13332131607 0013710 5 ustar 00root root 0000000 0000000 conv-0.9.11/tests/__init__.py 0000664 0000000 0000000 00000000000 13332131607 0016007 0 ustar 00root root 0000000 0000000 conv-0.9.11/tests/data/ 0000775 0000000 0000000 00000000000 13332131607 0014621 5 ustar 00root root 0000000 0000000 conv-0.9.11/tests/data/test-debian-bug-no-748638 0000664 0000000 0000000 00000000472 13332131607 0020714 0 ustar 00root root 0000000 0000000 # debian bugreport #748638
#
# Thanks to Guido, who found and reported this failure.
#
#
block () {
/sbin/iptables -A INPUT -i eth0 -p udp -j REJECT -s 10.0.0.0/16 -d 10.0.0.1 --dport ipp
}
allow () {
/sbin/iptables -A INPUT -i eth0 -p udp -j ACCEPT -s 10.0.0.0/16 -d 10.0.0.1 --dport ipp
}
allow
block
#
# EoF
conv-0.9.11/tests/data/test-shell-variables 0000664 0000000 0000000 00000000426 13332131607 0020600 0 ustar 00root root 0000000 0000000 # test to raise failure on shell variables
#
#
POLICY_A="ACCEPT"
POLICY_R="REJECT"
#
#
/sbin/iptables -A INPUT -i eth0 -p udp -j $POLICY_A -s 10.0.0.0/16 -d 10.0.0.1 --dport ipp
/sbin/iptables -A INPUT -i eth0 -p udp -j $POLICY_R -s 10.0.0.0/16 -d 10.0.0.1 --dport ipp
#
# EoF
conv-0.9.11/tests/test_iptables_converter.py 0000664 0000000 0000000 00000036210 13332131607 0021215 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
#encoding:utf8
from iptables_conv.iptables_converter import Chains, Tables, ConverterError
import unittest
import sys
dst = sys.stdout
class Chains_Test(unittest.TestCase):
'''some tests for class Chain'''
def test_01_create_a_chain_object(self):
"""
Chain 01: create a Filter group, f.e. filter
"""
self.assertIsInstance(Chains("filter",
["INPUT", "FORWARD", "OUTPUT"]), Chains)
self.assertEqual({}, Chains("filter", []))
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
self.assertEqual("filter", filter.name)
self.assertEqual(['INPUT', 'FORWARD', 'OUTPUT'], filter.tables)
self.assertEqual("-", filter.policy)
self.assertEqual(0, filter.length)
self.assertEqual(
{'FORWARD': 'ACCEPT', 'INPUT': 'ACCEPT', 'OUTPUT': 'ACCEPT'},
filter.poli)
def test_02_prove_policies(self):
"""
Chain 02: check 3 valid policies, 1 exception
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-P INPUT DROP")
self.assertEqual(
{'FORWARD': 'ACCEPT', 'INPUT': 'DROP', 'OUTPUT': 'ACCEPT'},
filter.poli)
filter.put_into_fgr("-P FORWARD REJECT")
self.assertEqual(
{'FORWARD': 'REJECT', 'INPUT': 'DROP', 'OUTPUT': 'ACCEPT'},
filter.poli)
filter.put_into_fgr("-P OUTPUT DROP")
self.assertEqual(
{'FORWARD': 'REJECT', 'INPUT': 'DROP', 'OUTPUT': 'DROP'},
filter.poli)
with self.assertRaises(ConverterError):
filter.put_into_fgr("-P OUTPUT FAIL")
def test_03_tables_names(self):
"""
Chain 03: 3 cases OK, 1 Exception
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-t filter -A INPUT -i sl0 -j ACCEPT")
self.assertEqual(['-A INPUT -i sl0 -j ACCEPT '], filter.data["INPUT"])
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-t nat -A OUTPUT -j ACCEPT")
self.assertEqual(['-A OUTPUT -j ACCEPT '], filter.data["OUTPUT"])
filter.put_into_fgr("-t nat -A FORWARD -j ACCEPT")
self.assertEqual(['-A FORWARD -j ACCEPT '], filter.data["FORWARD"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-t na -A INPUT")
def test_04_flush(self):
"""
Chain 04: flush filter group, 2 rules and an invalid chain
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-t filter -A INPUT -i sl0 -j ACCEPT")
self.assertEqual(['-A INPUT -i sl0 -j ACCEPT '],
filter.data["INPUT"])
filter.put_into_fgr("-A OUTPUT -o sl1 -j ACCEPT")
self.assertEqual(['-A OUTPUT -o sl1 -j ACCEPT'],
filter.data["OUTPUT"])
filter.put_into_fgr("-F")
self.assertEqual([], filter.data["INPUT"])
self.assertEqual([], filter.data["OUTPUT"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-t inval -F")
def test_05_new_chain(self):
"""
Chain 05: create a new chain in filtergroup,
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-N NEWCHAIN")
self.assertEqual(
{'FORWARD': [], 'INPUT': [], 'NEWCHAIN': [], 'OUTPUT': []},
filter.data)
def test_06_new_existing_chain_fails(self):
"""
Chain 06: create an exsiting chain should fail
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-N INPUT")
def test_07_insert_rule_fail(self):
"""
Chain 07: insert a rule into an empty chain fails
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-I INPUT -j ACCEPT")
def test_08_insert_rule_fail(self):
"""
Chain 08: insert a rule into a non_existing chain fails
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-I PUT -j ACCEPT")
def test_09_insert_rule_works(self):
"""
Chain 09: insert a rule into a nonempty chain works at start
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-A INPUT -p tcp -j ACCEPT")
filter.put_into_fgr("-I INPUT -p udp -j ACCEPT")
filter.put_into_fgr("-I INPUT -p esp -j ACCEPT")
expect = ['-I INPUT -p esp -j ACCEPT',
'-I INPUT -p udp -j ACCEPT',
'-A INPUT -p tcp -j ACCEPT']
self.assertEqual(expect, filter.data["INPUT"])
def test_10_append_rule(self):
"""
Chain 10: append a rule to a chain
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-A INPUT -p tcp -j ACCEPT")
self.assertEqual(['-A INPUT -p tcp -j ACCEPT'], filter.data["INPUT"])
filter.put_into_fgr("-A INPUT -p udp -j ACCEPT")
filter.put_into_fgr("-A INPUT -p esp -j ACCEPT")
expect = ['-A INPUT -p tcp -j ACCEPT',
'-A INPUT -p udp -j ACCEPT',
'-A INPUT -p esp -j ACCEPT']
self.assertEqual(expect, filter.data["INPUT"])
def test_11_remove_predef_chain(self):
"""
Chain 11: try to remove a prefined chain
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-X INPUT")
def test_12_remove_chain(self):
"""
Chain 12: try to remove an existing chain
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
filter.put_into_fgr("-N NEWCHAIN")
self.assertEqual(
{'FORWARD': [], 'INPUT': [], 'NEWCHAIN': [], 'OUTPUT': []},
filter.data)
filter.put_into_fgr("-X NEWCHAIN")
self.assertEqual(
{'FORWARD': [], 'INPUT': [], 'OUTPUT': []},
filter.data)
def test_13_illegal_command(self):
"""
Chain 13: try an ilegal command
"""
filter = Chains("filter", ["INPUT", "FORWARD", "OUTPUT"])
with self.assertRaises(ConverterError):
filter.put_into_fgr("-Y USERCHAIN")
class Tables_Test(unittest.TestCase):
'''
Tables: some first tests for the class
'''
def test_01_create_a_tables_object(self):
"""
Tables 01: create a Tables object, check chains
"""
self.assertIsInstance(Tables(dst, ""), Tables)
tables = Tables(dst, "")
expect = {'filter': {'FORWARD': [], 'INPUT': [], 'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [],
'POSTROUTING': [], 'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [], 'PREROUTING': [], 'POSTROUTING': []}}
self.assertEqual(expect, tables.data)
def test_02_nat_prerouting(self):
"""
Tables 02: nat PREROUTING entry
"""
tables = Tables(dst, "")
line = "iptables -t nat -A PREROUTING -s 10.0.0.0/21"
line = line + " -p tcp --dport 80 -j SNAT --to-source 192.168.1.15"
tables.put_into_tables(line)
expect = ['-A PREROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15 ']
self.assertEqual(expect, tables.data["nat"]["PREROUTING"])
def test_03_mangle_table(self):
"""
Tables 03: mangle INPUT entry
"""
tables = Tables(dst, "")
line = "iptables -t mangle -A INPUT"
line = line + " -p tcp --dport 80 -j ACCEPT"
tables.put_into_tables(line)
expect = ['-A INPUT -p tcp --dport 80 -j ACCEPT ']
self.assertEqual(expect, tables.data["mangle"]["INPUT"])
def test_04_raw_table(self):
"""
Tables 04: raw OUTPUT entry
"""
tables = Tables(dst, "")
line = "iptables -t raw -A OUTPUT"
line = line + " -p tcp --dport 80 -j ACCEPT"
tables.put_into_tables(line)
expect = ['-A OUTPUT -p tcp --dport 80 -j ACCEPT ']
self.assertEqual(expect, tables.data["raw"]["OUTPUT"])
def test_05_not_existing_chain(self):
"""
Tables 05: INPUT to not existing chain
"""
line = "iptables -t raw -A NONEXIST -p tcp --dport 80 -j ACCEPT"
with self.assertRaises(ConverterError):
Tables(dst, "").put_into_tables(line)
def test_06_read_not_existing_file(self):
"""
Tables 06: read non existing file
"""
with self.assertRaises(ConverterError):
Tables(dst, "not-exist-is-ok")
def test_07_read_empty_file(self):
"""
Tables 07: read empty file (in relation to iptables-commands)
"""
filename = "MANIFEST.in"
tables = Tables(dst, filename)
expect = {'filter': {'FORWARD': [], 'INPUT': [], 'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [], 'POSTROUTING': [],
'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [], 'PREROUTING': [], 'POSTROUTING': []}}
self.assertEqual(expect, tables.data)
def test_08_reference_one(self):
"""
Tables 08: read default file: reference-one, check chains
"""
tables = Tables(dst)
expect = {
'filter': {'FORWARD': [],
'INPUT': ['-A INPUT -p tcp --dport 23 -j ACCEPT '],
'USER_CHAIN': ['-A USER_CHAIN -p icmp -j DROP '],
'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [], 'POSTROUTING': [],
'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [],
'POSTROUTING': ['-A POSTROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15 '],
'PREROUTING': ['-A PREROUTING -d 192.0.2.5/32 -p tcp --dport 443 -j DNAT --to-destination 10.0.0.5:1500 ']}}
self.maxDiff = None
self.assertEqual(expect, tables.data)
def test_09_shell_variables(self):
"""
Tables 09: read buggy file with shell variables
"""
expect = "Line 8:"
with self.assertRaisesRegexp(ConverterError, expect):
Tables(dst, 'tests/data/test-shell-variables')
def test_10_shell_functions(self):
"""
Tables 10: read buggy file with shell functions
"""
expect = "Line 6:"
with self.assertRaisesRegexp(ConverterError, expect):
Tables(dst, 'tests/data/test-debian-bug-no-748638')
def test_11_reference_sloppy_one(self):
"""
Tables 11: read sloppy input file: reference-sloppy-one, check chains
"""
tables = Tables(dst, 'reference-sloppy-one', True)
expect = {
'filter':
{'FORWARD': [], 'INPUT': ['-A INPUT -p tcp --dport 23 -j ACCEPT '],
'USER_CHAIN': ['-I USER_CHAIN -p icmp --icmp-type echo-request -j ACCEPT ',
'-A USER_CHAIN -p icmp --icmp-type echo-reply -j ACCEPT ',
'-A USER_CHAIN -p icmp -j DROP '], 'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [], 'POSTROUTING': [], 'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [],
'PREROUTING': ['-A PREROUTING -d 192.0.2.5/32 -p tcp --dport 443 -j DNAT --to-destination 10.0.0.5:1500 '],
'POSTROUTING': ['-A POSTROUTING -s 10.0.0.0/21 -p tcp --dport 80 -j SNAT --to-source 192.168.1.15 ']}
}
self.maxDiff = None
self.assertEqual(expect, tables.data)
def test_12_create_a_tables6_object(self):
"""
Tables 12: create an ipv6 Tables object, check chains
"""
self.assertIsInstance(Tables(dst, "", ipversion=6), Tables)
tables = Tables(dst, "", ipversion=6)
expect = {'filter': {'FORWARD': [], 'INPUT': [], 'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [],
'POSTROUTING': [], 'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [], 'PREROUTING': [], 'POSTROUTING': []}}
self.assertEqual(expect, tables.data)
def test_13_re6ference_one(self):
"""
Tables 13: read default file: re6ference-one, check chains
"""
tables = Tables(dst, "re6ference-one", ipversion=6)
expect = {
'filter': {'FORWARD': [],
'INPUT': ['-A INPUT -p tcp --dport 23 -j ACCEPT '],
'USER_CHAIN': ['-A USER_CHAIN -p icmp -j DROP '], 'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [], 'POSTROUTING': [], 'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [], 'PREROUTING': ['-A PREROUTING -d 2001:db8:feed::1/128 -p tcp --dport 443 -j DNAT --to-destination 2001:db8:feed::1:1500 '], 'POSTROUTING': ['-A POSTROUTING -s 2001:db8:dead::/64 -p tcp --dport 80 -j SNAT --to-source 2001:db8:feed::1 ']}
}
self.maxDiff = None
self.assertEqual(expect, tables.data)
def test_14_re6ference_sloppy_one(self):
"""
Tables 14: read sloppy input file: re6ference-sloppy-one, check chains
"""
tables = Tables(dst, 're6ference-sloppy-one', sloppy=True, ipversion=6)
expect = {
'filter':
{'FORWARD': [], 'INPUT': ['-A INPUT -p tcp --dport 23 -j ACCEPT '],
'USER_CHAIN': ['-A USER_CHAIN -p icmp -j DROP '], 'OUTPUT': []},
'raw': {'OUTPUT': [], 'PREROUTING': []},
'mangle': {'FORWARD': [], 'INPUT': [], 'POSTROUTING': [], 'PREROUTING': [], 'OUTPUT': []},
'nat': {'OUTPUT': [],
'PREROUTING':
['-A PREROUTING -d 2001:db8:feed::1/128 -p tcp --dport 443 -j DNAT --to-destination 2001:db8:feed::1:1500 '],
'POSTROUTING':
['-A POSTROUTING -s 2001:db8:dead::/64 -p tcp --dport 80 -j SNAT --to-source 2001:db8:feed::1 ']}
}
self.maxDiff = None
self.assertEqual(expect, tables.data)
def test_15_tables_printout(capsys):
"""
Tables 15: check table_printout as well
"""
tables = Tables(sys.stdout, 'reference-one')
tables.table_printout()
out, err = capsys.readouterr()
assert len(err) == 0
words = ['*raw', '*nat', '*mangle', '*filter', 'COMMIT', 'from:',
'INPUT', 'FORWARD', 'USER_CHAIN', '192.0.2.5', ]
absents = ['iptables', '-t raw', '-t mangle', 'udp', ]
for word in words:
assert word in out
for absent in absents:
assert absent not in out
if __name__ == "__main__":
unittest.main()
conv-0.9.11/tests/test_iptables_options.py 0000664 0000000 0000000 00000006227 13332131607 0020706 0 ustar 00root root 0000000 0000000 import pytest
import sys
from iptables_conv.iptables_converter import my_options, main
def test_01_iptables_converter_option_h(capsys):
""" check ip6tablesmy_options returns help text
"""
sys.argv = ['ip6tables-converter', '-h', ]
with pytest.raises(SystemExit) as execinfo:
options = my_options()
print(':' + str(options) + ':')
out, err = capsys.readouterr()
assert ': SystemExit' in str(execinfo)
items = ['Options', 'SOURCEFILE', 'DESTFILE', 'version', '--help',
'--dest-file', '--source-file', '--sloppy',
'Have Fun!', ]
for item in items:
assert item in out
assert len(err) == 0
def test_02_iptables_converter_option_s():
""" check my_options sloppy and sourcefile name returning
"""
sys.argv = ['iptab', '-s', 'reference-one', '--sloppy', ]
options = my_options()
assert options == {'destfile': None,
'sourcefile': 'reference-one',
'sloppy': True}
def test_03_iptables_converter_option_d():
""" check my_options, destfile name returning
"""
sys.argv = ['ip6tab', '-d', 'one', ]
options = my_options()
assert options == {'destfile': 'one',
'sourcefile': None,
'sloppy': False}
def test_04_iptables_converter_option_sd():
""" check my_options returns source- and destfile
"""
sys.argv = ['bla', '-s', 'one', '-d', 'two']
options = my_options()
assert options == {'destfile': 'two',
'sourcefile': 'one',
'sloppy': False}
def test_05_iptables_converter_main_dlft(capsys):
""" check main behavior on default file not found
"""
sys.argv = ['ip6tab', ]
result = main()
out, err = capsys.readouterr()
assert 'Errno 2' in err
assert 'No such file or directory:' in err
assert 'rules' in err
assert result == 1
def test_06_iptables_converter_main_ok(capsys):
""" check main reads a named file
"""
sys.argv = ['ip6tab', '-s', 'reference-one', ]
result = main()
out, err = capsys.readouterr()
# print(':' + out + ':')
assert '# generated from: reference-one' in out
assert result == 0
def test_07_iptables_converter_main_write(capsys):
""" check main reads and writes w/o error
"""
sys.argv = ['ip6tab', '-s', 'reference-one', '-d', '/dev/null', ]
result = main()
out, err = capsys.readouterr()
assert len(out) == 0
assert len(err) == 0
assert result == 0
def test_08_iptables_converter_option_dest_file():
""" check my_options, destfile name returning
"""
sys.argv = ['ip6tab', '--dest-file', 'one', ]
options = my_options()
assert options == {'destfile': 'one',
'sourcefile': None,
'sloppy': False}
def test_09_iptables_converter_option_source_file():
""" check my_options sloppy and sourcefile name returning
"""
sys.argv = ['iptab', '-s', 'reference-one', '--sloppy', ]
options = my_options()
assert options == {'destfile': None,
'sourcefile': 'reference-one',
'sloppy': True}
conv-0.9.11/tox.ini 0000664 0000000 0000000 00000001761 13332131607 0014066 0 ustar 00root root 0000000 0000000 # Tox (http://tox.testrun.org/) is a tool for running tests
# in multiple virtualenvs. This configuration file will run the
# test suite on all supported python versions. To use it, "pip install tox"
# and then run "tox" from this directory.
[tox]
envlist = py27, py35, py36, flake8, docs
[testenv]
deps =
pytest
flake8
commands =
pytest
flake8
[testenv:py27]
basepython =
python2.7
commands =
python setup.py clean
python setup.py build
py.test -v
[testenv:py35]
basepython =
python3.5
commands =
python3.5 setup.py clean
python3.5 setup.py build
py.test -v
[testenv:py36]
basepython =
python3.6
commands =
python3.6 setup.py clean
python3.6 setup.py build
py.test -v
[testenv:flake8]
commands = flake8 iptables_conv/iptables_converter.py
[testenv:docs]
basepython =
python3.6
changedir = docs/source
deps =
pytest
sphinx
sphinx_rtd_theme
commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . {envtmpdir}/html