Compare commits

..

47 Commits

Author SHA1 Message Date
Jan Engelhardt
e87dc5d5e1 Xtables-addons 1.5.7 2008-09-01 15:35:51 -04:00
Jan Engelhardt
a0d3ee45ea xt_SYSRQ: add missing aliases 2008-09-01 15:33:28 -04:00
Jan Engelhardt
38343af9e6 xt_portscan: IPv6 support 2008-09-01 15:32:15 -04:00
Jan Engelhardt
53abb1e735 src: remove redundant return statements 2008-09-01 15:31:10 -04:00
Jan Engelhardt
8a7354d8d5 build: remove dependency on netinet/in6.h 2008-09-01 15:27:43 -04:00
Jan Engelhardt
f30793f591 DHCP address match and mangler 2008-09-01 15:27:43 -04:00
Jan Engelhardt
ab27472eb4 src: move to a pskb-based API
It occurred that skb reallocation does happen on older kernels, and
those kernels should really be supported, since the patch is really
minimal.
2008-09-01 15:27:43 -04:00
Jan Engelhardt
213acdffda xt_condition: ues glue-provided init_net__proc_net 2008-09-01 15:27:43 -04:00
Jan Engelhardt
a47e6623b8 Merge reworked fuzzy extension 2008-09-01 15:27:11 -04:00
Jan Engelhardt
d894a3dd15 fuzzy: IPv6 support 2008-09-01 15:26:51 -04:00
Jan Engelhardt
75e9afbc4a fuzzy: misc cleanup 2008-09-01 15:26:47 -04:00
Jan Engelhardt
003591fe6f fuzzy: remove unneeded spinlock 2008-09-01 15:22:22 -04:00
Jan Engelhardt
fd83fefad1 fuzzy: import 20050627 code base 2008-09-01 15:22:16 -04:00
Jan Engelhardt
e601fd61f9 Automatically run depmod -a 2008-08-29 07:53:06 -04:00
James King
8fe612e43f ipset: adjust semaphore.h include for kernel >= 2.6.27
As of Linux kernel commit 2351ec533ed0dd56052ab96988d2161d5ecc8ed9,
semaphore.h was moved from asm/ to linux/, which breaks building of
ipset. Add compat glue to ip_set.c to fix building on 2.6.27 an
onwards.
2008-08-28 20:27:09 -04:00
Jan Engelhardt
6737682e82 xt_SYSRQ: fix compilation for Linux kernel version <= 2.6.19 2008-08-28 20:27:09 -04:00
Jan Engelhardt
fd9c6ffb03 Clear hotdrop before use
Must make sure that hotdrop is properly initialized. GCC
unfortunately did not warn.
2008-08-24 16:44:07 -04:00
Jan Engelhardt
4f25eab39d libxt_geoip: reorder option parsing code 2008-08-24 12:34:31 -04:00
Jan Engelhardt
006147a21e build: prepare make tarball for git 1.6.0 2008-08-21 09:26:05 -04:00
Jan Engelhardt
c18fae4f2f Xtables-addons 1.5.5 2008-08-03 16:29:33 -04:00
Jan Engelhardt
b4784a48e8 cleanup [KM]build layout 2008-08-03 12:30:49 -04:00
Jan Engelhardt
039741e022 SYSRQ target 2008-08-03 12:26:09 -04:00
Jan Engelhardt
74880dd6ca Update license texts 2008-08-02 13:08:48 -04:00
Jan Engelhardt
5956a3354e compat: properly clamp return value from skb_make_writable() 2008-08-02 13:07:22 -04:00
Jan Engelhardt
419006eff9 src: compile fixes after libiptc dependency throwout 2008-07-30 09:19:07 -04:00
Jan Engelhardt
f43ac442e1 Remove dependency on CONFIG_NETWORK_SECMARK 2008-07-07 21:34:52 +02:00
Jan Engelhardt
1c902893b5 Merge branch 'ipset' 2008-07-07 18:00:48 +02:00
Jan Engelhardt
b1b6180e0b Merge branch 'quota2' 2008-07-07 18:00:46 +02:00
Jan Engelhardt
5120ab0079 xt_quota2: minor fixes, merge into main config files 2008-07-07 17:56:20 +02:00
Jan Engelhardt
35783b5c51 ipset: fixup compile errors with 2.6.18.x and 2.6.20 warnings 2008-07-07 11:07:15 +02:00
Jan Engelhardt
29aea5a87b ipset: fixup compile warnings
And add a few const here and there.
2008-07-07 10:36:35 +02:00
Jan Engelhardt
e456c864c1 xt_quota2: support packet counting; add manpage 2008-07-07 01:19:10 +02:00
Jan Engelhardt
df6d795d22 build: properly recognize external Kbuild/Mbuild files 2008-07-06 22:00:54 +02:00
Jan Engelhardt
e987e2118c xt_quota2: allow for multiple rules to share one counter 2008-07-06 22:00:54 +02:00
Jan Engelhardt
a1e915a984 Add xt_quota2
Support for inversion, upcounting, and changing the quota/counter
through sysfs.
2008-07-06 22:00:54 +02:00
Jan Engelhardt
74b20f5b73 ipp2p: bump version to indicate this is newer than 0.8.2 2008-07-05 19:41:23 +02:00
Jan Engelhardt
6d80c3adfe src: update netfilter.h to unifdef'ed variant
From Linux kernel, c8942f1f0a7e2160ebf2e51ba89e50ee5895a1e7.
2008-07-04 19:08:10 +02:00
Jan Engelhardt
9d696b727a Import ipset-2.3.2a (userspace components) 2008-07-04 18:38:58 +02:00
Jan Engelhardt
98e88e2d01 Import ipset-2.3.2 (kernel components) 2008-07-02 16:35:07 +02:00
Jan Engelhardt
a48469ec5b Import ipset-2.3.1a-20080617 2008-07-02 15:53:37 +02:00
Jan Engelhardt
ca482e8add Update README, .gitignore 2008-06-30 23:46:26 +02:00
Jan Engelhardt
38198b257d Update manpages of CHAOS, IPMARK 2008-06-27 22:56:42 +02:00
Jan Engelhardt
0959b60b07 Xtables-addons 1.5.4.1 2008-04-26 12:57:08 +02:00
Jan Engelhardt
02a65e0af8 Fix compilation error for 2.6.18-stable
The prototype of ip_route_me_harder changed in 2.6.18.5, so I think
Xtables-addons should account for it. This renders compilation on
anything below it impossible. (2.6.17 is not supported in general.)
2008-04-25 20:46:39 +02:00
Jan Engelhardt
84624f66cb Update .gitignore 2008-04-16 21:35:02 +02:00
Jan Engelhardt
5f098b2c5a configure.ac: AC_SUBST must be separate 2008-04-15 09:15:44 +02:00
Jan Engelhardt
086c8def12 condition: use PF_UNSPEC in vtable 2008-04-12 05:58:08 +02:00
97 changed files with 15146 additions and 477 deletions

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@
.libs
Makefile
Makefile.in
GNUmakefile
/downloads

22
INSTALL
View File

@@ -12,9 +12,16 @@ in combination with the kernel's Kbuild system.
Prerequirements
===============
* xtables(-devel) 1.5.2
* a recent iptables snapshot
- from the "xtables" git repository at dev.medozas.de
(minimum as per git-describe: v1.4.0-77)
- or the subversion repository at netfilter.org (minimum: r7502)
- or the xtables-combined tarball that is currently distributed
* kernel-source >= 2.6.18 with prepared build/output directory
* kernel-source >= 2.6.18.5 with prepared build/output directory
- CONFIG_NF_CONNTRACK or CONFIG_IP_NF_CONNTRACK
- CONFIG_NF_CONNTRACK_MARK or CONFIG_IP_NF_CONNTRACK_MARK
enabled =y or as module (=m)
Selecting extensions
@@ -36,15 +43,6 @@ Configuring and compiling
/lib/modules/$(running version)/build, which usually points to
the right directory. (If not, you need to install something.)
--with-ksource=
Specifies the path to the kernel source directory. This is
currently needed for building the userspace extensions because
we use unsanitized kernel headers, but the option MAY
DISAPPEAR IN FUTURE.
--with-ksource=/usr/src/linux
--with-xtables=
Specifies the path to the directory where we may find
@@ -77,5 +75,5 @@ Note to distribution packagers
Except for --with-kbuild, distributions should not have a need to
supply any other flags (besides --prefix=/usr and perhaps
--libdir=/usr/lib64, etc.) to configure when all prerequired packages
are installed. If xtables-devel is installed, necessary headers should
are installed. If iptables-devel is installed, necessary headers should
be in /usr/include, so --with-xtables is not needed.

339
LICENSE Normal file
View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This 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.

View File

@@ -1,7 +1,7 @@
# -*- Makefile -*-
AUTOMAKE_OPTIONS = foreign subdir-objects
SUBDIRS = extensions
SUBDIRS = extensions extensions/ipset
man_MANS := xtables-addons.8
@@ -11,10 +11,13 @@ xtables-addons.8: ${srcdir}/xtables-addons.8.in extensions/matches.man extension
extensions/%:
${MAKE} ${AM_MAKEFLAGS} -C $(@D) $(@F)
install-exec-local:
depmod -a || :;
.PHONY: tarball
tarball:
rm -Rf /tmp/xtables-addons-${PACKAGE_VERSION};
pushd ${top_srcdir} && git-archive --prefix=xtables-addons-${PACKAGE_VERSION}/ HEAD | tar -C /tmp -x && popd;
pushd ${top_srcdir} && git archive --prefix=xtables-addons-${PACKAGE_VERSION}/ HEAD | tar -C /tmp -x && popd;
pushd /tmp/xtables-addons-${PACKAGE_VERSION} && ./autogen.sh && popd;
tar -C /tmp -cjf xtables-addons-${PACKAGE_VERSION}.tar.bz2 --owner=root --group=root xtables-addons-${PACKAGE_VERSION}/;
rm -Rf /tmp/xtables-addons-${PACKAGE_VERSION};

34
README
View File

@@ -5,31 +5,43 @@ Xtables-addons is the proclaimed successor to patch-o-matic(-ng). It
contains extensions that were not accepted in the main Xtables
package.
Xtables-addons is different from patch-o-matic in that you do not have
to patch or recompile either kernel or Xtables(iptables). But please
see the INSTALL file for the minimum requirements of this package.
Xtables-addons is different from patch-o-matic in that you do not
have to patch or recompile either kernel or Xtables(iptables). But
please see the INSTALL file for the minimum requirements of this
package.
All code imported from patch-o-matic has been reviewed and all
apparent bugs like binary stability across multiarches, missing
sanity checks and incorrect endianess handling have been fixed,
simplified, and sped up.
Inclusion into a kernel tree
============================
External extensions
===================
The program "xa-download-more" can be used to download more extensions
from 3rd parties into the source tree. The URLs are listed in the
"sources" file. If the "sources" file contains an entry like
The program "xa-download-more" can be used to download more
extensions from 3rd parties into the source tree. The URLs are listed
in the "sources" file. If the "sources" file contains an entry like
http://foobar.org/xa/
xa-download-more will inspect http://foobar.org/xa/xa-index.txt for files
to download. That file may contain
xa-download-more will inspect http://foobar.org/xa/xa-index.txt for
files to download. That file may contain
foobar.tar.bz2
and xa-download-more will then retrieve and unpack
http://foobar.org/xa/foobar.tar.bz2.
Files that should be contained in the tarball are an mconfig and Kbuild
files to control building the extension, libxt_foobar.c for the userspace
extension and xt_foobar.c for the kernel extension.
Files that should be contained in the tarball are an mconfig and
Kbuild files to control building the extension, libxt_foobar.c for
the userspace extension and xt_foobar.c for the kernel extension.
mconfig.foobar
extensions/Kbuild.foobar

View File

@@ -1,5 +1,5 @@
AC_INIT([xtables-addons], [1.5.4])
AC_INIT([xtables-addons], [1.5.7])
AC_CONFIG_HEADERS([config.h])
AC_PROG_INSTALL
AM_INIT_AUTOMAKE
@@ -27,8 +27,6 @@ AC_ARG_WITH([xtlibdir],
[xtlibdir="$withval"],
[xtlibdir='${libexecdir}/xtables'])
AC_CHECK_HEADER([netinet/ip6.h], [], [AC_MSG_ERROR(but we need that for IPv6)])
AC_MSG_CHECKING([xtables.h presence])
if [[ -n "$xtables_location" ]]; then
if [[ -f "$xtables_location/xtables.h" ]]; then
@@ -59,8 +57,10 @@ if [[ -n "$ksourcedir" ]]; then
kinclude_CFLAGS="$kinclude_CFLAGS -I $ksourcedir/include";
fi;
AC_SUBST([regular_CFLAGS xtables_CFLAGS kinclude_CFLAGS])
AC_SUBST([regular_CFLAGS])
AC_SUBST([xtables_CFLAGS])
AC_SUBST([kinclude_CFLAGS])
AC_SUBST([kbuilddir])
AC_SUBST([ksourcedir])
AC_SUBST([xtlibdir])
AC_OUTPUT([Makefile extensions/GNUmakefile])
AC_OUTPUT([Makefile extensions/GNUmakefile extensions/ipset/GNUmakefile])

12
extensions/.gitignore vendored
View File

@@ -1,13 +1,13 @@
.*.cmd
.*.d
.manpages.lst
.tmp_versions
*.ko
*.mod.c
*.so
*.oo
GNUmakefile
Module.symvers
modules.order
matches.man
targets.man
/*.so
/*.oo
/matches.man
/targets.man
/.manpages.lst

View File

@@ -46,6 +46,8 @@ endif
include ${top_srcdir}/mconfig
-include ${top_srcdir}/mconfig.*
include ${srcdir}/Mbuild
-include ${srcdir}/Mbuild.*
-include ${srcdir}/*.Mbuild
#
@@ -58,7 +60,9 @@ targets_install := ${obj-m}
.PHONY: all install clean distclean FORCE
all: modules ${targets} matches.man targets.man
all: modules user matches.man targets.man
user: ${targets}
install: modules_install ${targets_install}
@mkdir -p "${DESTDIR}${xtlibdir}";

View File

@@ -3,18 +3,24 @@
include ${XA_TOPSRCDIR}/mconfig
-include ${XA_TOPSRCDIR}/mconfig.*
obj-m += compat_xtables.o
obj-m += compat_xtables.o
obj-${build_CHAOS} += xt_CHAOS.o
obj-${build_DELUDE} += xt_DELUDE.o
obj-${build_ECHO} += xt_ECHO.o
obj-${build_IPMARK} += xt_IPMARK.o
obj-${build_LOGMARK} += xt_LOGMARK.o
obj-${build_TARPIT} += xt_TARPIT.o
obj-${build_TEE} += xt_TEE.o
obj-${build_condition} += xt_condition.o
obj-${build_geoip} += xt_geoip.o
obj-${build_ipp2p} += xt_ipp2p.o
obj-${build_portscan} += xt_portscan.o
obj-${build_CHAOS} += xt_CHAOS.o
obj-${build_DELUDE} += xt_DELUDE.o
obj-${build_DHCPADDR} += xt_DHCPADDR.o
obj-${build_ECHO} += xt_ECHO.o
obj-${build_IPMARK} += xt_IPMARK.o
obj-${build_LOGMARK} += xt_LOGMARK.o
obj-${build_SYSRQ} += xt_SYSRQ.o
obj-${build_TARPIT} += xt_TARPIT.o
obj-${build_TEE} += xt_TEE.o
obj-${build_condition} += xt_condition.o
obj-${build_fuzzy} += xt_fuzzy.o
obj-${build_geoip} += xt_geoip.o
obj-${build_ipp2p} += xt_ipp2p.o
obj-${build_ipset} += ipset/
obj-${build_portscan} += xt_portscan.o
obj-${build_quota2} += xt_quota2.o
-include ${M}/*.Kbuild
-include ${M}/Kbuild.*

View File

@@ -1,11 +1,15 @@
obj-${build_CHAOS} += libxt_CHAOS.so
obj-${build_DELUDE} += libxt_DELUDE.so
obj-${build_ECHO} += libxt_ECHO.so
obj-${build_IPMARK} += libxt_IPMARK.so
obj-${build_LOGMARK} += libxt_LOGMARK.so
obj-${build_TARPIT} += libxt_TARPIT.so
obj-${build_TEE} += libxt_TEE.so
obj-${build_condition} += libxt_condition.so
obj-${build_geoip} += libxt_geoip.so
obj-${build_ipp2p} += libxt_ipp2p.so
obj-${build_portscan} += libxt_portscan.so
obj-${build_CHAOS} += libxt_CHAOS.so
obj-${build_DELUDE} += libxt_DELUDE.so
obj-${build_DHCPADDR} += libxt_DHCPADDR.so libxt_dhcpaddr.so
obj-${build_ECHO} += libxt_ECHO.so
obj-${build_IPMARK} += libxt_IPMARK.so
obj-${build_LOGMARK} += libxt_LOGMARK.so
obj-${build_SYSRQ} += libxt_SYSRQ.so
obj-${build_TARPIT} += libxt_TARPIT.so
obj-${build_TEE} += libxt_TEE.so
obj-${build_condition} += libxt_condition.so
obj-${build_fuzzy} += libxt_fuzzy.so
obj-${build_geoip} += libxt_geoip.so
obj-${build_ipp2p} += libxt_ipp2p.so
obj-${build_portscan} += libxt_portscan.so
obj-${build_quota2} += libxt_quota2.so

View File

@@ -10,6 +10,12 @@ struct udphdr;
# define skb_nfmark(skb) (((struct sk_buff *)(skb))->mark)
#endif
#ifdef CONFIG_NETWORK_SECMARK
# define skb_secmark(skb) ((skb)->secmark)
#else
# define skb_secmark(skb) 0
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 21)
# define ip_hdr(skb) ((skb)->nh.iph)
# define ip_hdrlen(skb) (ip_hdr(skb)->ihl * 4)

View File

@@ -1,3 +1,11 @@
/*
* API compat layer
* written by Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, either
* version 2 of the License, or any later version.
*/
#include <linux/ip.h>
#include <linux/kernel.h>
#include <linux/list.h>
@@ -12,14 +20,6 @@
#include "compat_skbuff.h"
#include "compat_xtnu.h"
static inline int unable(const char *cause)
{
if (net_ratelimit())
printk(KERN_ERR KBUILD_MODNAME
": compat layer limits reached (%s) - dropping packets\n", cause);
return -1;
}
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 22)
static int xtnu_match_run(const struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
@@ -27,7 +27,7 @@ static int xtnu_match_run(const struct sk_buff *skb,
unsigned int protoff, int *hotdrop)
{
struct xtnu_match *nm = xtcompat_numatch(cm);
bool lo_drop, lo_ret;
bool lo_drop = false, lo_ret;
if (nm == NULL || nm->match == NULL)
return false;
@@ -152,15 +152,21 @@ static unsigned int xtnu_target_run(struct sk_buff **pskb,
static unsigned int xtnu_target_run(struct sk_buff **pskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *ct, const void *targinfo)
#else
static unsigned int xtnu_target_run(struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *ct, const void *targinfo)
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
{
struct xtnu_target *nt = xtcompat_nutarget(ct);
if (nt != NULL && nt->target != NULL)
return nt->target(*pskb, in, out, hooknum, nt, targinfo);
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
return nt->target(pskb, in, out, hooknum, nt, targinfo);
#else
return nt->target(&skb, in, out, hooknum, nt, targinfo);
#endif
return XT_CONTINUE;
}
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
static int xtnu_target_check(const char *table, const void *entry,
@@ -169,11 +175,10 @@ static int xtnu_target_check(const char *table, const void *entry,
#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 22)
static int xtnu_target_check(const char *table, const void *entry,
const struct xt_target *ct, void *targinfo, unsigned int hook_mask)
#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
#else
static bool xtnu_target_check(const char *table, const void *entry,
const struct xt_target *ct, void *targinfo, unsigned int hook_mask)
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
{
struct xtnu_target *nt = xtcompat_nutarget(ct);
if (nt == NULL)
@@ -183,23 +188,19 @@ static bool xtnu_target_check(const char *table, const void *entry,
return true;
return nt->checkentry(table, entry, nt, targinfo, hook_mask);
}
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
static void xtnu_target_destroy(const struct xt_target *ct, void *targinfo,
unsigned int targinfosize)
#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
#else
static void xtnu_target_destroy(const struct xt_target *ct, void *targinfo)
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
{
struct xtnu_target *nt = xtcompat_nutarget(ct);
if (nt != NULL && nt->destroy != NULL)
nt->destroy(nt, targinfo);
}
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
int xtnu_register_target(struct xtnu_target *nt)
{
struct xt_target *ct;
@@ -267,7 +268,6 @@ void xtnu_unregister_targets(struct xtnu_target *nt, unsigned int num)
xtnu_unregister_target(&nt[i]);
}
EXPORT_SYMBOL_GPL(xtnu_unregister_targets);
#endif
struct xt_match *xtnu_request_find_match(unsigned int af, const char *name,
uint8_t revision)
@@ -293,35 +293,28 @@ struct xt_match *xtnu_request_find_match(unsigned int af, const char *name,
}
EXPORT_SYMBOL_GPL(xtnu_request_find_match);
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
int xtnu_ip_route_me_harder(struct sk_buff *skb, unsigned int addr_type)
int xtnu_ip_route_me_harder(struct sk_buff **pskb, unsigned int addr_type)
{
struct sk_buff *nskb = skb;
int ret;
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
ret = ip_route_me_harder(&skb);
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 17)
/* Actually this one is valid up to 2.6.18.4, but changed in 2.6.18.5 */
return ip_route_me_harder(pskb);
#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
ret = ip_route_me_harder(&nskb, addr_type);
return ip_route_me_harder(pskb, addr_type);
#else
return ip_route_me_harder(*pskb, addr_type);
#endif
if (nskb != skb)
return unable(__func__);
return ret;
}
EXPORT_SYMBOL_GPL(xtnu_ip_route_me_harder);
int xtnu_skb_make_writable(struct sk_buff *skb, unsigned int len)
int xtnu_skb_make_writable(struct sk_buff **pskb, unsigned int len)
{
struct sk_buff *nskb = skb;
int ret;
ret = skb_make_writable(&skb, len);
if (nskb != skb)
return unable(__func__);
return ret;
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
return skb_make_writable(pskb, len);
#else
return skb_make_writable(*pskb, len);
#endif
}
EXPORT_SYMBOL_GPL(xtnu_skb_make_writable);
#endif
#if LINUX_VERSION_CODE == KERNEL_VERSION(2, 6, 24)
static int __xtnu_ip_local_out(struct sk_buff *skb)
@@ -390,6 +383,19 @@ int xtnu_neigh_hh_output(struct hh_cache *hh, struct sk_buff *skb)
return hh->hh_output(skb);
}
EXPORT_SYMBOL_GPL(xtnu_neigh_hh_output);
static inline void csum_replace4(__sum16 *sum, __be32 from, __be32 to)
{
__be32 diff[] = {~from, to};
*sum = csum_fold(csum_partial((char *)diff, sizeof(diff),
~csum_unfold(*sum)));
}
void xtnu_csum_replace2(__sum16 *sum, __be16 from, __be16 to)
{
csum_replace4(sum, (__force __be32)from, (__force __be32)to);
}
EXPORT_SYMBOL_GPL(xtnu_csum_replace2);
#endif
MODULE_LICENSE("GPL");

View File

@@ -6,17 +6,17 @@
#include "compat_xtnu.h"
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18)
# warning Kernels below 2.6.18 not supported.
# warning Kernels below 2.6.18.5 not supported.
#endif
#if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE)
# if !defined(CONFIG_NF_CONNTRACK_MARK) || !defined(CONFIG_NF_CONNTRACK_SECMARK)
# warning You have CONFIG_NF_CONNTRACK enabled, but CONFIG_NF_CONNTRACK_MARK or CONFIG_NF_CONNTRACK_SECMARK are not (please enable).
# if !defined(CONFIG_NF_CONNTRACK_MARK)
# warning You have CONFIG_NF_CONNTRACK enabled, but CONFIG_NF_CONNTRACK_MARK is not (please enable).
# endif
# include <net/netfilter/nf_conntrack.h>
#elif defined(CONFIG_IP_NF_CONNTRACK) || defined(CONFIG_IP_NF_CONNTRACK_MODULE)
# if !defined(CONFIG_IP_NF_CONNTRACK_MARK) || !defined(CONFIG_IP_NF_CONNTRACK_SECMARK)
# warning You have CONFIG_IP_NF_CONNTRACK enabled, but CONFIG_IP_NF_CONNTRACK_MARK or CONFIG_IP_NF_CONNTRACK_SECMARK are not (please enable).
# if !defined(CONFIG_IP_NF_CONNTRACK_MARK)
# warning You have CONFIG_IP_NF_CONNTRACK enabled, but CONFIG_IP_NF_CONNTRACK_MARK is not (please enable).
# endif
# include <linux/netfilter_ipv4/ip_conntrack.h>
# define nf_conn ip_conntrack
@@ -28,6 +28,7 @@
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 19)
# define neigh_hh_output xtnu_neigh_hh_output
# define IPPROTO_UDPLITE 136
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 24)
@@ -44,8 +45,10 @@
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
# define init_net xtnu_ip_route_output_key /* yes */
# define init_net__loopback_dev (&loopback_dev)
# define init_net__proc_net proc_net
#else
# define init_net__loopback_dev init_net.loopback_dev
# define init_net__proc_net init_net.proc_net
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 22)
@@ -56,16 +59,20 @@
# define xt_unregister_matches xtnu_unregister_matches
#endif
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
# define xt_target xtnu_target
# define ip_route_me_harder xtnu_ip_route_me_harder
# define skb_make_writable xtnu_skb_make_writable
# define xt_register_target xtnu_register_target
# define xt_unregister_target xtnu_unregister_target
# define xt_register_targets xtnu_register_targets
# define xt_unregister_targets xtnu_unregister_targets
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 19)
# define csum_replace2 xtnu_csum_replace2
#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 24)
# define csum_replace2 nf_csum_replace2
#endif
#define ip_route_me_harder xtnu_ip_route_me_harder
#define skb_make_writable xtnu_skb_make_writable
#define xt_target xtnu_target
#define xt_register_target xtnu_register_target
#define xt_unregister_target xtnu_unregister_target
#define xt_register_targets xtnu_register_targets
#define xt_unregister_targets xtnu_unregister_targets
#define xt_request_find_match xtnu_request_find_match
#endif /* _XTABLES_COMPAT_H */

View File

@@ -38,7 +38,7 @@ struct xtnu_match {
struct xtnu_target {
struct list_head list;
char name[XT_FUNCTION_MAXNAMELEN - 1 - sizeof(void *)];
unsigned int (*target)(struct sk_buff *, const struct net_device *,
unsigned int (*target)(struct sk_buff **, const struct net_device *,
const struct net_device *, unsigned int,
const struct xtnu_target *, const void *);
bool (*checkentry)(const char *, const void *,
@@ -68,8 +68,8 @@ static inline struct xtnu_target *xtcompat_nutarget(const struct xt_target *t)
}
extern int xtnu_ip_local_out(struct sk_buff *);
extern int xtnu_ip_route_me_harder(struct sk_buff *, unsigned int);
extern int xtnu_skb_make_writable(struct sk_buff *, unsigned int);
extern int xtnu_ip_route_me_harder(struct sk_buff **, unsigned int);
extern int xtnu_skb_make_writable(struct sk_buff **, unsigned int);
extern int xtnu_register_match(struct xtnu_match *);
extern int xtnu_ip_route_output_key(void *, struct rtable **, struct flowi *);
extern void xtnu_unregister_match(struct xtnu_match *);

3
extensions/ipset/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
*.oo
*.so
/ipset

View File

@@ -0,0 +1,84 @@
# -*- Makefile -*-
top_srcdir := @top_srcdir@
srcdir := @srcdir@
abstop_srcdir := $(shell readlink -e ${top_srcdir})
abssrcdir := $(shell readlink -e ${srcdir})
ifeq (${abstop_srcdir},)
$(error Path resolution of ${top_srcdir} failed)
endif
ifeq (${abssrcdir},)
$(error Path resolution of ${srcdir} failed)
endif
prefix := @prefix@
exec_prefix := @exec_prefix@
sbindir := @sbindir@
libdir := @libdir@
libexecdir := @libexecdir@
xtlibdir := @xtlibdir@
kbuilddir := @kbuilddir@
man8dir := @mandir@/man8
CC := @CC@
CCLD := ${CC}
CFLAGS := @CFLAGS@
LDFLAGS := @LDFLAGS@
regular_CFLAGS := @regular_CFLAGS@
kinclude_CFLAGS := @kinclude_CFLAGS@
xtables_CFLAGS := @xtables_CFLAGS@
AM_CFLAGS := ${regular_CFLAGS} -I${top_srcdir}/include ${xtables_CFLAGS} ${kinclude_CFLAGS} -DXTABLES_LIBDIR=\"${xtlibdir}\"
AM_DEPFLAGS = -Wp,-MMD,$(@D)/.$(@F).d,-MT,$@
ifeq (${V},)
AM_LIBTOOL_SILENT = --silent
AM_VERBOSE_CC = @echo " CC " $@;
AM_VERBOSE_CCLD = @echo " CCLD " $@;
AM_VERBOSE_CXX = @echo " CXX " $@;
AM_VERBOSE_CXXLD = @echo " CXXLD " $@;
AM_VERBOSE_AR = @echo " AR " $@;
AM_VERBOSE_GEN = @echo " GEN " $@;
endif
#
# Building blocks
#
targets := $(addsuffix .so,$(addprefix libipset_,iphash ipmap ipporthash iptree iptreemap macipmap nethash portmap))
.SECONDARY:
.PHONY: all install clean distclean FORCE
all: ipset ${targets}
install: all
@mkdir -p "${DESTDIR}${sbindir}" "${DESTDIR}${xtlibdir}" "${DESTDIR}${man8dir}";
install -pm0755 ipset "${DESTDIR}${sbindir}/";
install -pm0755 ${targets} "${DESTDIR}${xtlibdir}/";
install -pm0644 ipset.8 "${DESTDIR}${man8dir}/";
clean:
rm -f *.oo *.so *.o ipset;
distclean: clean
rm -f .*.d;
-include .*.d
ipset: ipset.o
${AM_VERBOSE_CCLD} ${CCLD} ${AM_LDFLAGS} ${LDFLAGS} -o $@ $< -ldl -rdynamic;
#
# Shared libraries
#
lib%.so: lib%.oo
${AM_VERBOSE_CCLD} ${CCLD} ${AM_LDFLAGS} -shared ${LDFLAGS} -o $@ $<;
libipset_%.oo: ${srcdir}/ipset_%.c
${AM_VERBOSE_CC} ${CC} ${AM_DEPFLAGS} ${AM_CFLAGS} -DPIC -fPIC ${CFLAGS} -o $@ -c $<;
%.o: %.c
${AM_VERBOSE_CC} ${CC} ${AM_DEPFLAGS} ${AM_CFLAGS} ${CFLAGS} -o $@ -c $<;

6
extensions/ipset/Kbuild Normal file
View File

@@ -0,0 +1,6 @@
# -*- Makefile -*-
obj-m += ipt_set.o ipt_SET.o
obj-m += ip_set.o ip_set_ipmap.o ip_set_portmap.o ip_set_macipmap.o
obj-m += ip_set_iphash.o ip_set_nethash.o ip_set_ipporthash.o
obj-m += ip_set_iptree.o ip_set_iptreemap.o

1985
extensions/ipset/ip_set.c Normal file

File diff suppressed because it is too large Load Diff

506
extensions/ipset/ip_set.h Normal file
View File

@@ -0,0 +1,506 @@
#ifndef _IP_SET_H
#define _IP_SET_H
/* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
* Patrick Schaaf <bof@bof.de>
* Martin Josefsson <gandalf@wlug.westbo.se>
* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef CONFIG_IP_NF_SET_MAX
/* from 2 to 65534 */
# define CONFIG_IP_NF_SET_MAX 256
#endif
#ifndef CONFIG_IP_NF_SET_HASHSIZE
# define CONFIG_IP_NF_SET_HASHSIZE 1024
#endif
#if 0
#define IP_SET_DEBUG
#endif
/*
* A sockopt of such quality has hardly ever been seen before on the open
* market! This little beauty, hardly ever used: above 64, so it's
* traditionally used for firewalling, not touched (even once!) by the
* 2.0, 2.2 and 2.4 kernels!
*
* Comes with its own certificate of authenticity, valid anywhere in the
* Free world!
*
* Rusty, 19.4.2000
*/
#define SO_IP_SET 83
/*
* Heavily modify by Joakim Axelsson 08.03.2002
* - Made it more modulebased
*
* Additional heavy modifications by Jozsef Kadlecsik 22.02.2004
* - bindings added
* - in order to "deal with" backward compatibility, renamed to ipset
*/
/*
* Used so that the kernel module and ipset-binary can match their versions
*/
#define IP_SET_PROTOCOL_VERSION 2
#define IP_SET_MAXNAMELEN 32 /* set names and set typenames */
/* Lets work with our own typedef for representing an IP address.
* We hope to make the code more portable, possibly to IPv6...
*
* The representation works in HOST byte order, because most set types
* will perform arithmetic operations and compare operations.
*
* For now the type is an uint32_t.
*
* Make sure to ONLY use the functions when translating and parsing
* in order to keep the host byte order and make it more portable:
* parse_ip()
* parse_mask()
* parse_ipandmask()
* ip_tostring()
* (Joakim: where are they???)
*/
typedef uint32_t ip_set_ip_t;
/* Sets are identified by an id in kernel space. Tweak with ip_set_id_t
* and IP_SET_INVALID_ID if you want to increase the max number of sets.
*/
typedef uint16_t ip_set_id_t;
#define IP_SET_INVALID_ID 65535
/* How deep we follow bindings */
#define IP_SET_MAX_BINDINGS 6
/*
* Option flags for kernel operations (ipt_set_info)
*/
#define IPSET_SRC 0x01 /* Source match/add */
#define IPSET_DST 0x02 /* Destination match/add */
#define IPSET_MATCH_INV 0x04 /* Inverse matching */
/*
* Set features
*/
#define IPSET_TYPE_IP 0x01 /* IP address type of set */
#define IPSET_TYPE_PORT 0x02 /* Port type of set */
#define IPSET_DATA_SINGLE 0x04 /* Single data storage */
#define IPSET_DATA_DOUBLE 0x08 /* Double data storage */
/* Reserved keywords */
#define IPSET_TOKEN_DEFAULT ":default:"
#define IPSET_TOKEN_ALL ":all:"
/* SO_IP_SET operation constants, and their request struct types.
*
* Operation ids:
* 0-99: commands with version checking
* 100-199: add/del/test/bind/unbind
* 200-299: list, save, restore
*/
/* Single shot operations:
* version, create, destroy, flush, rename and swap
*
* Sets are identified by name.
*/
#define IP_SET_REQ_STD \
unsigned op; \
unsigned version; \
char name[IP_SET_MAXNAMELEN]
#define IP_SET_OP_CREATE 0x00000001 /* Create a new (empty) set */
struct ip_set_req_create {
IP_SET_REQ_STD;
char typename[IP_SET_MAXNAMELEN];
};
#define IP_SET_OP_DESTROY 0x00000002 /* Remove a (empty) set */
struct ip_set_req_std {
IP_SET_REQ_STD;
};
#define IP_SET_OP_FLUSH 0x00000003 /* Remove all IPs in a set */
/* Uses ip_set_req_std */
#define IP_SET_OP_RENAME 0x00000004 /* Rename a set */
/* Uses ip_set_req_create */
#define IP_SET_OP_SWAP 0x00000005 /* Swap two sets */
/* Uses ip_set_req_create */
union ip_set_name_index {
char name[IP_SET_MAXNAMELEN];
ip_set_id_t index;
};
#define IP_SET_OP_GET_BYNAME 0x00000006 /* Get set index by name */
struct ip_set_req_get_set {
unsigned op;
unsigned version;
union ip_set_name_index set;
};
#define IP_SET_OP_GET_BYINDEX 0x00000007 /* Get set name by index */
/* Uses ip_set_req_get_set */
#define IP_SET_OP_VERSION 0x00000100 /* Ask kernel version */
struct ip_set_req_version {
unsigned op;
unsigned version;
};
/* Double shots operations:
* add, del, test, bind and unbind.
*
* First we query the kernel to get the index and type of the target set,
* then issue the command. Validity of IP is checked in kernel in order
* to minimalize sockopt operations.
*/
/* Get minimal set data for add/del/test/bind/unbind IP */
#define IP_SET_OP_ADT_GET 0x00000010 /* Get set and type */
struct ip_set_req_adt_get {
unsigned op;
unsigned version;
union ip_set_name_index set;
char typename[IP_SET_MAXNAMELEN];
};
#define IP_SET_REQ_BYINDEX \
unsigned op; \
ip_set_id_t index;
struct ip_set_req_adt {
IP_SET_REQ_BYINDEX;
};
#define IP_SET_OP_ADD_IP 0x00000101 /* Add an IP to a set */
/* Uses ip_set_req_adt, with type specific addage */
#define IP_SET_OP_DEL_IP 0x00000102 /* Remove an IP from a set */
/* Uses ip_set_req_adt, with type specific addage */
#define IP_SET_OP_TEST_IP 0x00000103 /* Test an IP in a set */
/* Uses ip_set_req_adt, with type specific addage */
#define IP_SET_OP_BIND_SET 0x00000104 /* Bind an IP to a set */
/* Uses ip_set_req_bind, with type specific addage */
struct ip_set_req_bind {
IP_SET_REQ_BYINDEX;
char binding[IP_SET_MAXNAMELEN];
};
#define IP_SET_OP_UNBIND_SET 0x00000105 /* Unbind an IP from a set */
/* Uses ip_set_req_bind, with type speficic addage
* index = 0 means unbinding for all sets */
#define IP_SET_OP_TEST_BIND_SET 0x00000106 /* Test binding an IP to a set */
/* Uses ip_set_req_bind, with type specific addage */
/* Multiple shots operations: list, save, restore.
*
* - check kernel version and query the max number of sets
* - get the basic information on all sets
* and size required for the next step
* - get actual set data: header, data, bindings
*/
/* Get max_sets and the index of a queried set
*/
#define IP_SET_OP_MAX_SETS 0x00000020
struct ip_set_req_max_sets {
unsigned op;
unsigned version;
ip_set_id_t max_sets; /* max_sets */
ip_set_id_t sets; /* real number of sets */
union ip_set_name_index set; /* index of set if name used */
};
/* Get the id and name of the sets plus size for next step */
#define IP_SET_OP_LIST_SIZE 0x00000201
#define IP_SET_OP_SAVE_SIZE 0x00000202
struct ip_set_req_setnames {
unsigned op;
ip_set_id_t index; /* set to list/save */
size_t size; /* size to get setdata/bindings */
/* followed by sets number of struct ip_set_name_list */
};
struct ip_set_name_list {
char name[IP_SET_MAXNAMELEN];
char typename[IP_SET_MAXNAMELEN];
ip_set_id_t index;
ip_set_id_t id;
};
/* The actual list operation */
#define IP_SET_OP_LIST 0x00000203
struct ip_set_req_list {
IP_SET_REQ_BYINDEX;
/* sets number of struct ip_set_list in reply */
};
struct ip_set_list {
ip_set_id_t index;
ip_set_id_t binding;
u_int32_t ref;
size_t header_size; /* Set header data of header_size */
size_t members_size; /* Set members data of members_size */
size_t bindings_size; /* Set bindings data of bindings_size */
};
struct ip_set_hash_list {
ip_set_ip_t ip;
ip_set_id_t binding;
};
/* The save operation */
#define IP_SET_OP_SAVE 0x00000204
/* Uses ip_set_req_list, in the reply replaced by
* sets number of struct ip_set_save plus a marker
* ip_set_save followed by ip_set_hash_save structures.
*/
struct ip_set_save {
ip_set_id_t index;
ip_set_id_t binding;
size_t header_size; /* Set header data of header_size */
size_t members_size; /* Set members data of members_size */
};
/* At restoring, ip == 0 means default binding for the given set: */
struct ip_set_hash_save {
ip_set_ip_t ip;
ip_set_id_t id;
ip_set_id_t binding;
};
/* The restore operation */
#define IP_SET_OP_RESTORE 0x00000205
/* Uses ip_set_req_setnames followed by ip_set_restore structures
* plus a marker ip_set_restore, followed by ip_set_hash_save
* structures.
*/
struct ip_set_restore {
char name[IP_SET_MAXNAMELEN];
char typename[IP_SET_MAXNAMELEN];
ip_set_id_t index;
size_t header_size; /* Create data of header_size */
size_t members_size; /* Set members data of members_size */
};
static inline int bitmap_bytes(ip_set_ip_t a, ip_set_ip_t b)
{
return 4 * ((((b - a + 8) / 8) + 3) / 4);
}
#ifdef __KERNEL__
#define ip_set_printk(format, args...) \
do { \
printk("%s: %s: ", __FILE__, __FUNCTION__); \
printk(format "\n" , ## args); \
} while (0)
#if defined(IP_SET_DEBUG)
#define DP(format, args...) \
do { \
printk("%s: %s (DBG): ", __FILE__, __FUNCTION__);\
printk(format "\n" , ## args); \
} while (0)
#define IP_SET_ASSERT(x) \
do { \
if (!(x)) \
printk("IP_SET_ASSERT: %s:%i(%s)\n", \
__FILE__, __LINE__, __FUNCTION__); \
} while (0)
#else
#define DP(format, args...)
#define IP_SET_ASSERT(x)
#endif
struct ip_set;
/*
* The ip_set_type definition - one per set type, e.g. "ipmap".
*
* Each individual set has a pointer, set->type, going to one
* of these structures. Function pointers inside the structure implement
* the real behaviour of the sets.
*
* If not mentioned differently, the implementation behind the function
* pointers of a set_type, is expected to return 0 if ok, and a negative
* errno (e.g. -EINVAL) on error.
*/
struct ip_set_type {
struct list_head list; /* next in list of set types */
/* test for IP in set (kernel: iptables -m set src|dst)
* return 0 if not in set, 1 if in set.
*/
int (*testip_kernel) (struct ip_set *set,
const struct sk_buff * skb,
ip_set_ip_t *ip,
const u_int32_t *flags,
unsigned char index);
/* test for IP in set (userspace: ipset -T set IP)
* return 0 if not in set, 1 if in set.
*/
int (*testip) (struct ip_set *set,
const void *data, size_t size,
ip_set_ip_t *ip);
/*
* Size of the data structure passed by when
* adding/deletin/testing an entry.
*/
size_t reqsize;
/* Add IP into set (userspace: ipset -A set IP)
* Return -EEXIST if the address is already in the set,
* and -ERANGE if the address lies outside the set bounds.
* If the address was not already in the set, 0 is returned.
*/
int (*addip) (struct ip_set *set,
const void *data, size_t size,
ip_set_ip_t *ip);
/* Add IP into set (kernel: iptables ... -j SET set src|dst)
* Return -EEXIST if the address is already in the set,
* and -ERANGE if the address lies outside the set bounds.
* If the address was not already in the set, 0 is returned.
*/
int (*addip_kernel) (struct ip_set *set,
const struct sk_buff * skb,
ip_set_ip_t *ip,
const u_int32_t *flags,
unsigned char index);
/* remove IP from set (userspace: ipset -D set --entry x)
* Return -EEXIST if the address is NOT in the set,
* and -ERANGE if the address lies outside the set bounds.
* If the address really was in the set, 0 is returned.
*/
int (*delip) (struct ip_set *set,
const void *data, size_t size,
ip_set_ip_t *ip);
/* remove IP from set (kernel: iptables ... -j SET --entry x)
* Return -EEXIST if the address is NOT in the set,
* and -ERANGE if the address lies outside the set bounds.
* If the address really was in the set, 0 is returned.
*/
int (*delip_kernel) (struct ip_set *set,
const struct sk_buff * skb,
ip_set_ip_t *ip,
const u_int32_t *flags,
unsigned char index);
/* new set creation - allocated type specific items
*/
int (*create) (struct ip_set *set,
const void *data, size_t size);
/* retry the operation after successfully tweaking the set
*/
int (*retry) (struct ip_set *set);
/* set destruction - free type specific items
* There is no return value.
* Can be called only when child sets are destroyed.
*/
void (*destroy) (struct ip_set *set);
/* set flushing - reset all bits in the set, or something similar.
* There is no return value.
*/
void (*flush) (struct ip_set *set);
/* Listing: size needed for header
*/
size_t header_size;
/* Listing: Get the header
*
* Fill in the information in "data".
* This function is always run after list_header_size() under a
* writelock on the set. Therefor is the length of "data" always
* correct.
*/
void (*list_header) (const struct ip_set *set,
void *data);
/* Listing: Get the size for the set members
*/
int (*list_members_size) (const struct ip_set *set);
/* Listing: Get the set members
*
* Fill in the information in "data".
* This function is always run after list_member_size() under a
* writelock on the set. Therefor is the length of "data" always
* correct.
*/
void (*list_members) (const struct ip_set *set,
void *data);
char typename[IP_SET_MAXNAMELEN];
unsigned char features;
int protocol_version;
/* Set this to THIS_MODULE if you are a module, otherwise NULL */
struct module *me;
};
extern int ip_set_register_set_type(struct ip_set_type *set_type);
extern void ip_set_unregister_set_type(struct ip_set_type *set_type);
/* A generic ipset */
struct ip_set {
char name[IP_SET_MAXNAMELEN]; /* the name of the set */
rwlock_t lock; /* lock for concurrency control */
ip_set_id_t id; /* set id for swapping */
ip_set_id_t binding; /* default binding for the set */
atomic_t ref; /* in kernel and in hash references */
struct ip_set_type *type; /* the set types */
void *data; /* pooltype specific data */
};
/* Structure to bind set elements to sets */
struct ip_set_hash {
struct list_head list; /* list of clashing entries in hash */
ip_set_ip_t ip; /* ip from set */
ip_set_id_t id; /* set id */
ip_set_id_t binding; /* set we bind the element to */
};
/* register and unregister set references */
extern ip_set_id_t ip_set_get_byname(const char name[IP_SET_MAXNAMELEN]);
extern ip_set_id_t ip_set_get_byindex(ip_set_id_t id);
extern void ip_set_put(ip_set_id_t id);
/* API for iptables set match, and SET target */
extern void ip_set_addip_kernel(ip_set_id_t id,
const struct sk_buff *skb,
const u_int32_t *flags);
extern void ip_set_delip_kernel(ip_set_id_t id,
const struct sk_buff *skb,
const u_int32_t *flags);
extern int ip_set_testip_kernel(ip_set_id_t id,
const struct sk_buff *skb,
const u_int32_t *flags);
#endif /* __KERNEL__ */
#endif /*_IP_SET_H*/

View File

@@ -0,0 +1,425 @@
/* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an ip hash set */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/jhash.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <linux/random.h>
#include <net/ip.h>
#include "ip_set_malloc.h"
#include "ip_set_iphash.h"
static int limit = MAX_RANGE;
static inline __u32
jhash_ip(const struct ip_set_iphash *map, uint16_t i, ip_set_ip_t ip)
{
return jhash_1word(ip, *(((uint32_t *) map->initval) + i));
}
static inline __u32
hash_id(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_iphash *map = set->data;
__u32 id;
u_int16_t i;
ip_set_ip_t *elem;
*hash_ip = ip & map->netmask;
DP("set: %s, ip:%u.%u.%u.%u, %u.%u.%u.%u, %u.%u.%u.%u",
set->name, HIPQUAD(ip), HIPQUAD(*hash_ip), HIPQUAD(map->netmask));
for (i = 0; i < map->probes; i++) {
id = jhash_ip(map, i, *hash_ip) % map->hashsize;
DP("hash key: %u", id);
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, id);
if (*elem == *hash_ip)
return id;
/* No shortcut at testing - there can be deleted
* entries. */
}
return UINT_MAX;
}
static inline int
__testip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
return (ip && hash_id(set, ip, hash_ip) != UINT_MAX);
}
static int
testip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iphash *req = data;
if (size != sizeof(struct ip_set_req_iphash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iphash),
size);
return -EINVAL;
}
return __testip(set, req->ip, hash_ip);
}
static int
testip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __testip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static inline int
__addip(struct ip_set_iphash *map, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
__u32 probe;
u_int16_t i;
ip_set_ip_t *elem;
if (!ip || map->elements >= limit)
return -ERANGE;
*hash_ip = ip & map->netmask;
for (i = 0; i < map->probes; i++) {
probe = jhash_ip(map, i, *hash_ip) % map->hashsize;
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, probe);
if (*elem == *hash_ip)
return -EEXIST;
if (!*elem) {
*elem = *hash_ip;
map->elements++;
return 0;
}
}
/* Trigger rehashing */
return -EAGAIN;
}
static int
addip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iphash *req = data;
if (size != sizeof(struct ip_set_req_iphash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iphash),
size);
return -EINVAL;
}
return __addip(set->data, req->ip, hash_ip);
}
static int
addip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __addip((struct ip_set_iphash *) set->data,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static int retry(struct ip_set *set)
{
struct ip_set_iphash *map = set->data;
ip_set_ip_t hash_ip, *elem;
void *members;
u_int32_t i, hashsize = map->hashsize;
int res;
struct ip_set_iphash *tmp;
if (map->resize == 0)
return -ERANGE;
again:
res = 0;
/* Calculate new hash size */
hashsize += (hashsize * map->resize)/100;
if (hashsize == map->hashsize)
hashsize++;
ip_set_printk("rehashing of set %s triggered: "
"hashsize grows from %u to %u",
set->name, map->hashsize, hashsize);
tmp = kmalloc(sizeof(struct ip_set_iphash)
+ map->probes * sizeof(uint32_t), GFP_ATOMIC);
if (!tmp) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_iphash)
+ map->probes * sizeof(uint32_t));
return -ENOMEM;
}
tmp->members = harray_malloc(hashsize, sizeof(ip_set_ip_t), GFP_ATOMIC);
if (!tmp->members) {
DP("out of memory for %d bytes", hashsize * sizeof(ip_set_ip_t));
kfree(tmp);
return -ENOMEM;
}
tmp->hashsize = hashsize;
tmp->elements = 0;
tmp->probes = map->probes;
tmp->resize = map->resize;
tmp->netmask = map->netmask;
memcpy(tmp->initval, map->initval, map->probes * sizeof(uint32_t));
write_lock_bh(&set->lock);
map = set->data; /* Play safe */
for (i = 0; i < map->hashsize && res == 0; i++) {
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, i);
if (*elem)
res = __addip(tmp, *elem, &hash_ip);
}
if (res) {
/* Failure, try again */
write_unlock_bh(&set->lock);
harray_free(tmp->members);
kfree(tmp);
goto again;
}
/* Success at resizing! */
members = map->members;
map->hashsize = tmp->hashsize;
map->members = tmp->members;
write_unlock_bh(&set->lock);
harray_free(members);
kfree(tmp);
return 0;
}
static inline int
__delip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_iphash *map = set->data;
ip_set_ip_t id, *elem;
if (!ip)
return -ERANGE;
id = hash_id(set, ip, hash_ip);
if (id == UINT_MAX)
return -EEXIST;
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, id);
*elem = 0;
map->elements--;
return 0;
}
static int
delip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iphash *req = data;
if (size != sizeof(struct ip_set_req_iphash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iphash),
size);
return -EINVAL;
}
return __delip(set, req->ip, hash_ip);
}
static int
delip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __delip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static int create(struct ip_set *set, const void *data, size_t size)
{
const struct ip_set_req_iphash_create *req = data;
struct ip_set_iphash *map;
uint16_t i;
if (size != sizeof(struct ip_set_req_iphash_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iphash_create),
size);
return -EINVAL;
}
if (req->hashsize < 1) {
ip_set_printk("hashsize too small");
return -ENOEXEC;
}
if (req->probes < 1) {
ip_set_printk("probes too small");
return -ENOEXEC;
}
map = kmalloc(sizeof(struct ip_set_iphash)
+ req->probes * sizeof(uint32_t), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_iphash)
+ req->probes * sizeof(uint32_t));
return -ENOMEM;
}
for (i = 0; i < req->probes; i++)
get_random_bytes(((uint32_t *) map->initval)+i, 4);
map->elements = 0;
map->hashsize = req->hashsize;
map->probes = req->probes;
map->resize = req->resize;
map->netmask = req->netmask;
map->members = harray_malloc(map->hashsize, sizeof(ip_set_ip_t), GFP_KERNEL);
if (!map->members) {
DP("out of memory for %d bytes", map->hashsize * sizeof(ip_set_ip_t));
kfree(map);
return -ENOMEM;
}
set->data = map;
return 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_iphash *map = set->data;
harray_free(map->members);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_iphash *map = set->data;
harray_flush(map->members, map->hashsize, sizeof(ip_set_ip_t));
map->elements = 0;
}
static void list_header(const struct ip_set *set, void *data)
{
struct ip_set_iphash *map = set->data;
struct ip_set_req_iphash_create *header = data;
header->hashsize = map->hashsize;
header->probes = map->probes;
header->resize = map->resize;
header->netmask = map->netmask;
}
static int list_members_size(const struct ip_set *set)
{
const struct ip_set_iphash *map = set->data;
return (map->hashsize * sizeof(ip_set_ip_t));
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_iphash *map = set->data;
ip_set_ip_t i, *elem;
for (i = 0; i < map->hashsize; i++) {
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, i);
((ip_set_ip_t *)data)[i] = *elem;
}
}
static struct ip_set_type ip_set_iphash = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_iphash),
.addip = &addip,
.addip_kernel = &addip_kernel,
.retry = &retry,
.delip = &delip,
.delip_kernel = &delip_kernel,
.testip = &testip,
.testip_kernel = &testip_kernel,
.header_size = sizeof(struct ip_set_req_iphash_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("iphash type of IP sets");
module_param(limit, int, 0600);
MODULE_PARM_DESC(limit, "maximal number of elements stored in the sets");
static int __init ip_set_iphash_init(void)
{
init_max_page_size();
return ip_set_register_set_type(&ip_set_iphash);
}
static void __exit ip_set_iphash_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_iphash);
}
module_init(ip_set_iphash_init);
module_exit(ip_set_iphash_fini);

View File

@@ -0,0 +1,30 @@
#ifndef __IP_SET_IPHASH_H
#define __IP_SET_IPHASH_H
#include "ip_set.h"
#define SETTYPE_NAME "iphash"
#define MAX_RANGE 0x0000FFFF
struct ip_set_iphash {
ip_set_ip_t *members; /* the iphash proper */
uint32_t elements; /* number of elements */
uint32_t hashsize; /* hash size */
uint16_t probes; /* max number of probes */
uint16_t resize; /* resize factor in percent */
ip_set_ip_t netmask; /* netmask */
void *initval[0]; /* initvals for jhash_1word */
};
struct ip_set_req_iphash_create {
uint32_t hashsize;
uint16_t probes;
uint16_t resize;
ip_set_ip_t netmask;
};
struct ip_set_req_iphash {
ip_set_ip_t ip;
};
#endif /* __IP_SET_IPHASH_H */

View File

@@ -0,0 +1,331 @@
/* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
* Patrick Schaaf <bof@bof.de>
* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an IP set type: the single bitmap type */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include "ip_set_ipmap.h"
static inline ip_set_ip_t
ip_to_id(const struct ip_set_ipmap *map, ip_set_ip_t ip)
{
return (ip - map->first_ip)/map->hosts;
}
static inline int
__testip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_ipmap *map = set->data;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
*hash_ip = ip & map->netmask;
DP("set: %s, ip:%u.%u.%u.%u, %u.%u.%u.%u",
set->name, HIPQUAD(ip), HIPQUAD(*hash_ip));
return !!test_bit(ip_to_id(map, *hash_ip), map->members);
}
static int
testip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_ipmap *req = data;
if (size != sizeof(struct ip_set_req_ipmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipmap),
size);
return -EINVAL;
}
return __testip(set, req->ip, hash_ip);
}
static int
testip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
int res = __testip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
return (res < 0 ? 0 : res);
}
static inline int
__addip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_ipmap *map = set->data;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
*hash_ip = ip & map->netmask;
DP("%u.%u.%u.%u, %u.%u.%u.%u", HIPQUAD(ip), HIPQUAD(*hash_ip));
if (test_and_set_bit(ip_to_id(map, *hash_ip), map->members))
return -EEXIST;
return 0;
}
static int
addip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_ipmap *req = data;
if (size != sizeof(struct ip_set_req_ipmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipmap),
size);
return -EINVAL;
}
DP("%u.%u.%u.%u", HIPQUAD(req->ip));
return __addip(set, req->ip, hash_ip);
}
static int
addip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __addip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static inline int
__delip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_ipmap *map = set->data;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
*hash_ip = ip & map->netmask;
DP("%u.%u.%u.%u, %u.%u.%u.%u", HIPQUAD(ip), HIPQUAD(*hash_ip));
if (!test_and_clear_bit(ip_to_id(map, *hash_ip), map->members))
return -EEXIST;
return 0;
}
static int
delip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_ipmap *req = data;
if (size != sizeof(struct ip_set_req_ipmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipmap),
size);
return -EINVAL;
}
return __delip(set, req->ip, hash_ip);
}
static int
delip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __delip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static int create(struct ip_set *set, const void *data, size_t size)
{
int newbytes;
const struct ip_set_req_ipmap_create *req = data;
struct ip_set_ipmap *map;
if (size != sizeof(struct ip_set_req_ipmap_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipmap_create),
size);
return -EINVAL;
}
DP("from %u.%u.%u.%u to %u.%u.%u.%u",
HIPQUAD(req->from), HIPQUAD(req->to));
if (req->from > req->to) {
DP("bad ip range");
return -ENOEXEC;
}
map = kmalloc(sizeof(struct ip_set_ipmap), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_ipmap));
return -ENOMEM;
}
map->first_ip = req->from;
map->last_ip = req->to;
map->netmask = req->netmask;
if (req->netmask == 0xFFFFFFFF) {
map->hosts = 1;
map->sizeid = map->last_ip - map->first_ip + 1;
} else {
unsigned int mask_bits, netmask_bits;
ip_set_ip_t mask;
map->first_ip &= map->netmask; /* Should we better bark? */
mask = range_to_mask(map->first_ip, map->last_ip, &mask_bits);
netmask_bits = mask_to_bits(map->netmask);
if ((!mask && (map->first_ip || map->last_ip != 0xFFFFFFFF))
|| netmask_bits <= mask_bits)
return -ENOEXEC;
DP("mask_bits %u, netmask_bits %u",
mask_bits, netmask_bits);
map->hosts = 2 << (32 - netmask_bits - 1);
map->sizeid = 2 << (netmask_bits - mask_bits - 1);
}
if (map->sizeid > MAX_RANGE + 1) {
ip_set_printk("range too big (max %d addresses)",
MAX_RANGE+1);
kfree(map);
return -ENOEXEC;
}
DP("hosts %u, sizeid %u", map->hosts, map->sizeid);
newbytes = bitmap_bytes(0, map->sizeid - 1);
map->members = kmalloc(newbytes, GFP_KERNEL);
if (!map->members) {
DP("out of memory for %d bytes", newbytes);
kfree(map);
return -ENOMEM;
}
memset(map->members, 0, newbytes);
set->data = map;
return 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_ipmap *map = set->data;
kfree(map->members);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_ipmap *map = set->data;
memset(map->members, 0, bitmap_bytes(0, map->sizeid - 1));
}
static void list_header(const struct ip_set *set, void *data)
{
const struct ip_set_ipmap *map = set->data;
struct ip_set_req_ipmap_create *header = data;
header->from = map->first_ip;
header->to = map->last_ip;
header->netmask = map->netmask;
}
static int list_members_size(const struct ip_set *set)
{
const struct ip_set_ipmap *map = set->data;
return bitmap_bytes(0, map->sizeid - 1);
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_ipmap *map = set->data;
int bytes = bitmap_bytes(0, map->sizeid - 1);
memcpy(data, map->members, bytes);
}
static struct ip_set_type ip_set_ipmap = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_ipmap),
.addip = &addip,
.addip_kernel = &addip_kernel,
.delip = &delip,
.delip_kernel = &delip_kernel,
.testip = &testip,
.testip_kernel = &testip_kernel,
.header_size = sizeof(struct ip_set_req_ipmap_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("ipmap type of IP sets");
static int __init ip_set_ipmap_init(void)
{
return ip_set_register_set_type(&ip_set_ipmap);
}
static void __exit ip_set_ipmap_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_ipmap);
}
module_init(ip_set_ipmap_init);
module_exit(ip_set_ipmap_fini);

View File

@@ -0,0 +1,56 @@
#ifndef __IP_SET_IPMAP_H
#define __IP_SET_IPMAP_H
#include "ip_set.h"
#define SETTYPE_NAME "ipmap"
#define MAX_RANGE 0x0000FFFF
struct ip_set_ipmap {
void *members; /* the ipmap proper */
ip_set_ip_t first_ip; /* host byte order, included in range */
ip_set_ip_t last_ip; /* host byte order, included in range */
ip_set_ip_t netmask; /* subnet netmask */
ip_set_ip_t sizeid; /* size of set in IPs */
ip_set_ip_t hosts; /* number of hosts in a subnet */
};
struct ip_set_req_ipmap_create {
ip_set_ip_t from;
ip_set_ip_t to;
ip_set_ip_t netmask;
};
struct ip_set_req_ipmap {
ip_set_ip_t ip;
};
static unsigned int
mask_to_bits(ip_set_ip_t mask)
{
unsigned int bits = 32;
ip_set_ip_t maskaddr;
if (mask == 0xFFFFFFFF)
return bits;
maskaddr = 0xFFFFFFFE;
while (--bits >= 0 && maskaddr != mask)
maskaddr <<= 1;
return bits;
}
static ip_set_ip_t
range_to_mask(ip_set_ip_t from, ip_set_ip_t to, unsigned int *bits)
{
ip_set_ip_t mask = 0xFFFFFFFE;
*bits = 32;
while (--(*bits) >= 0 && mask && (to & mask) != from)
mask <<= 1;
return mask;
}
#endif /* __IP_SET_IPMAP_H */

View File

@@ -0,0 +1,575 @@
/* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an ip+port hash set */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/jhash.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <linux/random.h>
#include <net/ip.h>
#include "ip_set_malloc.h"
#include "ip_set_ipporthash.h"
static int limit = MAX_RANGE;
/* We must handle non-linear skbs */
static inline ip_set_ip_t
get_port(const struct sk_buff *skb, u_int32_t flags)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
struct iphdr *iph = ip_hdr(skb);
#else
struct iphdr *iph = skb->nh.iph;
#endif
u_int16_t offset = ntohs(iph->frag_off) & IP_OFFSET;
switch (iph->protocol) {
case IPPROTO_TCP: {
struct tcphdr tcph;
/* See comments at tcp_match in ip_tables.c */
if (offset)
return INVALID_PORT;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
if (skb_copy_bits(skb, ip_hdr(skb)->ihl*4, &tcph, sizeof(tcph)) < 0)
#else
if (skb_copy_bits(skb, skb->nh.iph->ihl*4, &tcph, sizeof(tcph)) < 0)
#endif
/* No choice either */
return INVALID_PORT;
return ntohs(flags & IPSET_SRC ?
tcph.source : tcph.dest);
}
case IPPROTO_UDP: {
struct udphdr udph;
if (offset)
return INVALID_PORT;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
if (skb_copy_bits(skb, ip_hdr(skb)->ihl*4, &udph, sizeof(udph)) < 0)
#else
if (skb_copy_bits(skb, skb->nh.iph->ihl*4, &udph, sizeof(udph)) < 0)
#endif
/* No choice either */
return INVALID_PORT;
return ntohs(flags & IPSET_SRC ?
udph.source : udph.dest);
}
default:
return INVALID_PORT;
}
}
static inline __u32
jhash_ip(const struct ip_set_ipporthash *map, uint16_t i, ip_set_ip_t ip)
{
return jhash_1word(ip, *(((uint32_t *) map->initval) + i));
}
#define HASH_IP(map, ip, port) (port + ((ip - ((map)->first_ip)) << 16))
static inline __u32
hash_id(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t port,
ip_set_ip_t *hash_ip)
{
struct ip_set_ipporthash *map = set->data;
__u32 id;
u_int16_t i;
ip_set_ip_t *elem;
*hash_ip = HASH_IP(map, ip, port);
DP("set: %s, ipport:%u.%u.%u.%u:%u, %u.%u.%u.%u",
set->name, HIPQUAD(ip), port, HIPQUAD(*hash_ip));
for (i = 0; i < map->probes; i++) {
id = jhash_ip(map, i, *hash_ip) % map->hashsize;
DP("hash key: %u", id);
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, id);
if (*elem == *hash_ip)
return id;
/* No shortcut at testing - there can be deleted
* entries. */
}
return UINT_MAX;
}
static inline int
__testip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t port,
ip_set_ip_t *hash_ip)
{
struct ip_set_ipporthash *map = set->data;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
return (hash_id(set, ip, port, hash_ip) != UINT_MAX);
}
static int
testip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_ipporthash *req = data;
if (size != sizeof(struct ip_set_req_ipporthash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipporthash),
size);
return -EINVAL;
}
return __testip(set, req->ip, req->port, hash_ip);
}
static int
testip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
ip_set_ip_t port;
int res;
if (flags[index+1] == 0)
return 0;
port = get_port(skb, flags[index+1]);
DP("flag: %s src: %u.%u.%u.%u dst: %u.%u.%u.%u",
flags[index] & IPSET_SRC ? "SRC" : "DST",
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
NIPQUAD(ip_hdr(skb)->saddr),
NIPQUAD(ip_hdr(skb)->daddr));
#else
NIPQUAD(skb->nh.iph->saddr),
NIPQUAD(skb->nh.iph->daddr));
#endif
DP("flag %s port %u",
flags[index+1] & IPSET_SRC ? "SRC" : "DST",
port);
if (port == INVALID_PORT)
return 0;
res = __testip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
port,
hash_ip);
return (res < 0 ? 0 : res);
}
static inline int
__add_haship(struct ip_set_ipporthash *map, ip_set_ip_t hash_ip)
{
__u32 probe;
u_int16_t i;
ip_set_ip_t *elem;
for (i = 0; i < map->probes; i++) {
probe = jhash_ip(map, i, hash_ip) % map->hashsize;
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, probe);
if (*elem == hash_ip)
return -EEXIST;
if (!*elem) {
*elem = hash_ip;
map->elements++;
return 0;
}
}
/* Trigger rehashing */
return -EAGAIN;
}
static inline int
__addip(struct ip_set_ipporthash *map, ip_set_ip_t ip, ip_set_ip_t port,
ip_set_ip_t *hash_ip)
{
if (map->elements > limit)
return -ERANGE;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
*hash_ip = HASH_IP(map, ip, port);
return __add_haship(map, *hash_ip);
}
static int
addip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_ipporthash *req = data;
if (size != sizeof(struct ip_set_req_ipporthash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipporthash),
size);
return -EINVAL;
}
return __addip(set->data, req->ip, req->port, hash_ip);
}
static int
addip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
ip_set_ip_t port;
if (flags[index+1] == 0)
return -EINVAL;
port = get_port(skb, flags[index+1]);
DP("flag: %s src: %u.%u.%u.%u dst: %u.%u.%u.%u",
flags[index] & IPSET_SRC ? "SRC" : "DST",
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
NIPQUAD(ip_hdr(skb)->saddr),
NIPQUAD(ip_hdr(skb)->daddr));
#else
NIPQUAD(skb->nh.iph->saddr),
NIPQUAD(skb->nh.iph->daddr));
#endif
DP("flag %s port %u",
flags[index+1] & IPSET_SRC ? "SRC" : "DST",
port);
if (port == INVALID_PORT)
return -EINVAL;
return __addip(set->data,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
port,
hash_ip);
}
static int retry(struct ip_set *set)
{
struct ip_set_ipporthash *map = set->data;
ip_set_ip_t *elem;
void *members;
u_int32_t i, hashsize = map->hashsize;
int res;
struct ip_set_ipporthash *tmp;
if (map->resize == 0)
return -ERANGE;
again:
res = 0;
/* Calculate new hash size */
hashsize += (hashsize * map->resize)/100;
if (hashsize == map->hashsize)
hashsize++;
ip_set_printk("rehashing of set %s triggered: "
"hashsize grows from %u to %u",
set->name, map->hashsize, hashsize);
tmp = kmalloc(sizeof(struct ip_set_ipporthash)
+ map->probes * sizeof(uint32_t), GFP_ATOMIC);
if (!tmp) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_ipporthash)
+ map->probes * sizeof(uint32_t));
return -ENOMEM;
}
tmp->members = harray_malloc(hashsize, sizeof(ip_set_ip_t), GFP_ATOMIC);
if (!tmp->members) {
DP("out of memory for %d bytes", hashsize * sizeof(ip_set_ip_t));
kfree(tmp);
return -ENOMEM;
}
tmp->hashsize = hashsize;
tmp->elements = 0;
tmp->probes = map->probes;
tmp->resize = map->resize;
tmp->first_ip = map->first_ip;
tmp->last_ip = map->last_ip;
memcpy(tmp->initval, map->initval, map->probes * sizeof(uint32_t));
write_lock_bh(&set->lock);
map = set->data; /* Play safe */
for (i = 0; i < map->hashsize && res == 0; i++) {
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, i);
if (*elem)
res = __add_haship(tmp, *elem);
}
if (res) {
/* Failure, try again */
write_unlock_bh(&set->lock);
harray_free(tmp->members);
kfree(tmp);
goto again;
}
/* Success at resizing! */
members = map->members;
map->hashsize = tmp->hashsize;
map->members = tmp->members;
write_unlock_bh(&set->lock);
harray_free(members);
kfree(tmp);
return 0;
}
static inline int
__delip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t port,
ip_set_ip_t *hash_ip)
{
struct ip_set_ipporthash *map = set->data;
ip_set_ip_t id;
ip_set_ip_t *elem;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
id = hash_id(set, ip, port, hash_ip);
if (id == UINT_MAX)
return -EEXIST;
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, id);
*elem = 0;
map->elements--;
return 0;
}
static int
delip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_ipporthash *req = data;
if (size != sizeof(struct ip_set_req_ipporthash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipporthash),
size);
return -EINVAL;
}
return __delip(set, req->ip, req->port, hash_ip);
}
static int
delip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
ip_set_ip_t port;
if (flags[index+1] == 0)
return -EINVAL;
port = get_port(skb, flags[index+1]);
DP("flag: %s src: %u.%u.%u.%u dst: %u.%u.%u.%u",
flags[index] & IPSET_SRC ? "SRC" : "DST",
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
NIPQUAD(ip_hdr(skb)->saddr),
NIPQUAD(ip_hdr(skb)->daddr));
#else
NIPQUAD(skb->nh.iph->saddr),
NIPQUAD(skb->nh.iph->daddr));
#endif
DP("flag %s port %u",
flags[index+1] & IPSET_SRC ? "SRC" : "DST",
port);
if (port == INVALID_PORT)
return -EINVAL;
return __delip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
port,
hash_ip);
}
static int create(struct ip_set *set, const void *data, size_t size)
{
const struct ip_set_req_ipporthash_create *req = data;
struct ip_set_ipporthash *map;
uint16_t i;
if (size != sizeof(struct ip_set_req_ipporthash_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_ipporthash_create),
size);
return -EINVAL;
}
if (req->hashsize < 1) {
ip_set_printk("hashsize too small");
return -ENOEXEC;
}
if (req->probes < 1) {
ip_set_printk("probes too small");
return -ENOEXEC;
}
map = kmalloc(sizeof(struct ip_set_ipporthash)
+ req->probes * sizeof(uint32_t), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_ipporthash)
+ req->probes * sizeof(uint32_t));
return -ENOMEM;
}
for (i = 0; i < req->probes; i++)
get_random_bytes(((uint32_t *) map->initval)+i, 4);
map->elements = 0;
map->hashsize = req->hashsize;
map->probes = req->probes;
map->resize = req->resize;
map->first_ip = req->from;
map->last_ip = req->to;
map->members = harray_malloc(map->hashsize, sizeof(ip_set_ip_t), GFP_KERNEL);
if (!map->members) {
DP("out of memory for %d bytes", map->hashsize * sizeof(ip_set_ip_t));
kfree(map);
return -ENOMEM;
}
set->data = map;
return 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_ipporthash *map = set->data;
harray_free(map->members);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_ipporthash *map = set->data;
harray_flush(map->members, map->hashsize, sizeof(ip_set_ip_t));
map->elements = 0;
}
static void list_header(const struct ip_set *set, void *data)
{
const struct ip_set_ipporthash *map = set->data;
struct ip_set_req_ipporthash_create *header = data;
header->hashsize = map->hashsize;
header->probes = map->probes;
header->resize = map->resize;
header->from = map->first_ip;
header->to = map->last_ip;
}
static int list_members_size(const struct ip_set *set)
{
const struct ip_set_ipporthash *map = set->data;
return (map->hashsize * sizeof(ip_set_ip_t));
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_ipporthash *map = set->data;
ip_set_ip_t i, *elem;
for (i = 0; i < map->hashsize; i++) {
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, i);
((ip_set_ip_t *)data)[i] = *elem;
}
}
static struct ip_set_type ip_set_ipporthash = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_TYPE_PORT | IPSET_DATA_DOUBLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_ipporthash),
.addip = &addip,
.addip_kernel = &addip_kernel,
.retry = &retry,
.delip = &delip,
.delip_kernel = &delip_kernel,
.testip = &testip,
.testip_kernel = &testip_kernel,
.header_size = sizeof(struct ip_set_req_ipporthash_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("ipporthash type of IP sets");
module_param(limit, int, 0600);
MODULE_PARM_DESC(limit, "maximal number of elements stored in the sets");
static int __init ip_set_ipporthash_init(void)
{
init_max_page_size();
return ip_set_register_set_type(&ip_set_ipporthash);
}
static void __exit ip_set_ipporthash_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_ipporthash);
}
module_init(ip_set_ipporthash_init);
module_exit(ip_set_ipporthash_fini);

View File

@@ -0,0 +1,34 @@
#ifndef __IP_SET_IPPORTHASH_H
#define __IP_SET_IPPORTHASH_H
#include "ip_set.h"
#define SETTYPE_NAME "ipporthash"
#define MAX_RANGE 0x0000FFFF
#define INVALID_PORT (MAX_RANGE + 1)
struct ip_set_ipporthash {
ip_set_ip_t *members; /* the ipporthash proper */
uint32_t elements; /* number of elements */
uint32_t hashsize; /* hash size */
uint16_t probes; /* max number of probes */
uint16_t resize; /* resize factor in percent */
ip_set_ip_t first_ip; /* host byte order, included in range */
ip_set_ip_t last_ip; /* host byte order, included in range */
void *initval[0]; /* initvals for jhash_1word */
};
struct ip_set_req_ipporthash_create {
uint32_t hashsize;
uint16_t probes;
uint16_t resize;
ip_set_ip_t from;
ip_set_ip_t to;
};
struct ip_set_req_ipporthash {
ip_set_ip_t ip;
ip_set_ip_t port;
};
#endif /* __IP_SET_IPPORTHASH_H */

View File

@@ -0,0 +1,607 @@
/* Copyright (C) 2005 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an IP set type: the iptree type */
#include <linux/version.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
/* Backward compatibility */
#ifndef __nocast
#define __nocast
#endif
#include "ip_set_iptree.h"
static int limit = MAX_RANGE;
/* Garbage collection interval in seconds: */
#define IPTREE_GC_TIME 5*60
/* Sleep so many milliseconds before trying again
* to delete the gc timer at destroying/flushing a set */
#define IPTREE_DESTROY_SLEEP 100
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
static struct kmem_cache *branch_cachep;
static struct kmem_cache *leaf_cachep;
#else
static kmem_cache_t *branch_cachep;
static kmem_cache_t *leaf_cachep;
#endif
#if defined(__LITTLE_ENDIAN)
#define ABCD(a,b,c,d,addrp) do { \
a = ((unsigned char *)addrp)[3]; \
b = ((unsigned char *)addrp)[2]; \
c = ((unsigned char *)addrp)[1]; \
d = ((unsigned char *)addrp)[0]; \
} while (0)
#elif defined(__BIG_ENDIAN)
#define ABCD(a,b,c,d,addrp) do { \
a = ((unsigned char *)addrp)[0]; \
b = ((unsigned char *)addrp)[1]; \
c = ((unsigned char *)addrp)[2]; \
d = ((unsigned char *)addrp)[3]; \
} while (0)
#else
#error "Please fix asm/byteorder.h"
#endif /* __LITTLE_ENDIAN */
#define TESTIP_WALK(map, elem, branch) do { \
if ((map)->tree[elem]) { \
branch = (map)->tree[elem]; \
} else \
return 0; \
} while (0)
static inline int
__testip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_iptree *map = set->data;
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned char a,b,c,d;
if (!ip)
return -ERANGE;
*hash_ip = ip;
ABCD(a, b, c, d, hash_ip);
DP("%u %u %u %u timeout %u", a, b, c, d, map->timeout);
TESTIP_WALK(map, a, btree);
TESTIP_WALK(btree, b, ctree);
TESTIP_WALK(ctree, c, dtree);
DP("%lu %lu", dtree->expires[d], jiffies);
return dtree->expires[d]
&& (!map->timeout
|| time_after(dtree->expires[d], jiffies));
}
static int
testip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iptree *req = data;
if (size != sizeof(struct ip_set_req_iptree)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iptree),
size);
return -EINVAL;
}
return __testip(set, req->ip, hash_ip);
}
static int
testip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
int res;
DP("flag: %s src: %u.%u.%u.%u dst: %u.%u.%u.%u",
flags[index] & IPSET_SRC ? "SRC" : "DST",
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
NIPQUAD(ip_hdr(skb)->saddr),
NIPQUAD(ip_hdr(skb)->daddr));
#else
NIPQUAD(skb->nh.iph->saddr),
NIPQUAD(skb->nh.iph->daddr));
#endif
res = __testip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
return (res < 0 ? 0 : res);
}
#define ADDIP_WALK(map, elem, branch, type, cachep) do { \
if ((map)->tree[elem]) { \
DP("found %u", elem); \
branch = (map)->tree[elem]; \
} else { \
branch = (type *) \
kmem_cache_alloc(cachep, GFP_ATOMIC); \
if (branch == NULL) \
return -ENOMEM; \
memset(branch, 0, sizeof(*branch)); \
(map)->tree[elem] = branch; \
DP("alloc %u", elem); \
} \
} while (0)
static inline int
__addip(struct ip_set *set, ip_set_ip_t ip, unsigned int timeout,
ip_set_ip_t *hash_ip)
{
struct ip_set_iptree *map = set->data;
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned char a,b,c,d;
int ret = 0;
if (!ip || map->elements >= limit)
/* We could call the garbage collector
* but it's probably overkill */
return -ERANGE;
*hash_ip = ip;
ABCD(a, b, c, d, hash_ip);
DP("%u %u %u %u timeout %u", a, b, c, d, timeout);
ADDIP_WALK(map, a, btree, struct ip_set_iptreeb, branch_cachep);
ADDIP_WALK(btree, b, ctree, struct ip_set_iptreec, branch_cachep);
ADDIP_WALK(ctree, c, dtree, struct ip_set_iptreed, leaf_cachep);
if (dtree->expires[d]
&& (!map->timeout || time_after(dtree->expires[d], jiffies)))
ret = -EEXIST;
dtree->expires[d] = map->timeout ? (timeout * HZ + jiffies) : 1;
/* Lottery: I won! */
if (dtree->expires[d] == 0)
dtree->expires[d] = 1;
DP("%u %lu", d, dtree->expires[d]);
if (ret == 0)
map->elements++;
return ret;
}
static int
addip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
struct ip_set_iptree *map = set->data;
const struct ip_set_req_iptree *req = data;
if (size != sizeof(struct ip_set_req_iptree)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iptree),
size);
return -EINVAL;
}
DP("%u.%u.%u.%u %u", HIPQUAD(req->ip), req->timeout);
return __addip(set, req->ip,
req->timeout ? req->timeout : map->timeout,
hash_ip);
}
static int
addip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
struct ip_set_iptree *map = set->data;
return __addip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
map->timeout,
hash_ip);
}
#define DELIP_WALK(map, elem, branch) do { \
if ((map)->tree[elem]) { \
branch = (map)->tree[elem]; \
} else \
return -EEXIST; \
} while (0)
static inline int
__delip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_iptree *map = set->data;
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned char a,b,c,d;
if (!ip)
return -ERANGE;
*hash_ip = ip;
ABCD(a, b, c, d, hash_ip);
DELIP_WALK(map, a, btree);
DELIP_WALK(btree, b, ctree);
DELIP_WALK(ctree, c, dtree);
if (dtree->expires[d]) {
dtree->expires[d] = 0;
map->elements--;
return 0;
}
return -EEXIST;
}
static int
delip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iptree *req = data;
if (size != sizeof(struct ip_set_req_iptree)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iptree),
size);
return -EINVAL;
}
return __delip(set, req->ip, hash_ip);
}
static int
delip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __delip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
#define LOOP_WALK_BEGIN(map, i, branch) \
for (i = 0; i < 256; i++) { \
if (!(map)->tree[i]) \
continue; \
branch = (map)->tree[i]
#define LOOP_WALK_END }
static void ip_tree_gc(unsigned long ul_set)
{
struct ip_set *set = (struct ip_set *) ul_set;
struct ip_set_iptree *map = set->data;
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned int a,b,c,d;
unsigned char i,j,k;
i = j = k = 0;
DP("gc: %s", set->name);
write_lock_bh(&set->lock);
LOOP_WALK_BEGIN(map, a, btree);
LOOP_WALK_BEGIN(btree, b, ctree);
LOOP_WALK_BEGIN(ctree, c, dtree);
for (d = 0; d < 256; d++) {
if (dtree->expires[d]) {
DP("gc: %u %u %u %u: expires %lu jiffies %lu",
a, b, c, d,
dtree->expires[d], jiffies);
if (map->timeout
&& time_before(dtree->expires[d], jiffies)) {
dtree->expires[d] = 0;
map->elements--;
} else
k = 1;
}
}
if (k == 0) {
DP("gc: %s: leaf %u %u %u empty",
set->name, a, b, c);
kmem_cache_free(leaf_cachep, dtree);
ctree->tree[c] = NULL;
} else {
DP("gc: %s: leaf %u %u %u not empty",
set->name, a, b, c);
j = 1;
k = 0;
}
LOOP_WALK_END;
if (j == 0) {
DP("gc: %s: branch %u %u empty",
set->name, a, b);
kmem_cache_free(branch_cachep, ctree);
btree->tree[b] = NULL;
} else {
DP("gc: %s: branch %u %u not empty",
set->name, a, b);
i = 1;
j = k = 0;
}
LOOP_WALK_END;
if (i == 0) {
DP("gc: %s: branch %u empty",
set->name, a);
kmem_cache_free(branch_cachep, btree);
map->tree[a] = NULL;
} else {
DP("gc: %s: branch %u not empty",
set->name, a);
i = j = k = 0;
}
LOOP_WALK_END;
write_unlock_bh(&set->lock);
map->gc.expires = jiffies + map->gc_interval * HZ;
add_timer(&map->gc);
}
static inline void init_gc_timer(struct ip_set *set)
{
struct ip_set_iptree *map = set->data;
/* Even if there is no timeout for the entries,
* we still have to call gc because delete
* do not clean up empty branches */
map->gc_interval = IPTREE_GC_TIME;
init_timer(&map->gc);
map->gc.data = (unsigned long) set;
map->gc.function = ip_tree_gc;
map->gc.expires = jiffies + map->gc_interval * HZ;
add_timer(&map->gc);
}
static int create(struct ip_set *set, const void *data, size_t size)
{
const struct ip_set_req_iptree_create *req = data;
struct ip_set_iptree *map;
if (size != sizeof(struct ip_set_req_iptree_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_iptree_create),
size);
return -EINVAL;
}
map = kmalloc(sizeof(struct ip_set_iptree), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_iptree));
return -ENOMEM;
}
memset(map, 0, sizeof(*map));
map->timeout = req->timeout;
map->elements = 0;
set->data = map;
init_gc_timer(set);
return 0;
}
static void __flush(struct ip_set_iptree *map)
{
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned int a,b,c;
LOOP_WALK_BEGIN(map, a, btree);
LOOP_WALK_BEGIN(btree, b, ctree);
LOOP_WALK_BEGIN(ctree, c, dtree);
kmem_cache_free(leaf_cachep, dtree);
LOOP_WALK_END;
kmem_cache_free(branch_cachep, ctree);
LOOP_WALK_END;
kmem_cache_free(branch_cachep, btree);
LOOP_WALK_END;
map->elements = 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_iptree *map = set->data;
/* gc might be running */
while (!del_timer(&map->gc))
msleep(IPTREE_DESTROY_SLEEP);
__flush(map);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_iptree *map = set->data;
unsigned int timeout = map->timeout;
/* gc might be running */
while (!del_timer(&map->gc))
msleep(IPTREE_DESTROY_SLEEP);
__flush(map);
memset(map, 0, sizeof(*map));
map->timeout = timeout;
init_gc_timer(set);
}
static void list_header(const struct ip_set *set, void *data)
{
const struct ip_set_iptree *map = set->data;
struct ip_set_req_iptree_create *header = data;
header->timeout = map->timeout;
}
static int list_members_size(const struct ip_set *set)
{
const struct ip_set_iptree *map = set->data;
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned int a,b,c,d;
unsigned int count = 0;
LOOP_WALK_BEGIN(map, a, btree);
LOOP_WALK_BEGIN(btree, b, ctree);
LOOP_WALK_BEGIN(ctree, c, dtree);
for (d = 0; d < 256; d++) {
if (dtree->expires[d]
&& (!map->timeout || time_after(dtree->expires[d], jiffies)))
count++;
}
LOOP_WALK_END;
LOOP_WALK_END;
LOOP_WALK_END;
DP("members %u", count);
return (count * sizeof(struct ip_set_req_iptree));
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_iptree *map = set->data;
struct ip_set_iptreeb *btree;
struct ip_set_iptreec *ctree;
struct ip_set_iptreed *dtree;
unsigned int a,b,c,d;
size_t offset = 0;
struct ip_set_req_iptree *entry;
LOOP_WALK_BEGIN(map, a, btree);
LOOP_WALK_BEGIN(btree, b, ctree);
LOOP_WALK_BEGIN(ctree, c, dtree);
for (d = 0; d < 256; d++) {
if (dtree->expires[d]
&& (!map->timeout || time_after(dtree->expires[d], jiffies))) {
entry = data + offset;
entry->ip = ((a << 24) | (b << 16) | (c << 8) | d);
entry->timeout = !map->timeout ? 0
: (dtree->expires[d] - jiffies)/HZ;
offset += sizeof(struct ip_set_req_iptree);
}
}
LOOP_WALK_END;
LOOP_WALK_END;
LOOP_WALK_END;
}
static struct ip_set_type ip_set_iptree = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_iptree),
.addip = &addip,
.addip_kernel = &addip_kernel,
.delip = &delip,
.delip_kernel = &delip_kernel,
.testip = &testip,
.testip_kernel = &testip_kernel,
.header_size = sizeof(struct ip_set_req_iptree_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("iptree type of IP sets");
module_param(limit, int, 0600);
MODULE_PARM_DESC(limit, "maximal number of elements stored in the sets");
static int __init ip_set_iptree_init(void)
{
int ret;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
branch_cachep = kmem_cache_create("ip_set_iptreeb",
sizeof(struct ip_set_iptreeb),
0, 0, NULL);
#else
branch_cachep = kmem_cache_create("ip_set_iptreeb",
sizeof(struct ip_set_iptreeb),
0, 0, NULL, NULL);
#endif
if (!branch_cachep) {
printk(KERN_ERR "Unable to create ip_set_iptreeb slab cache\n");
ret = -ENOMEM;
goto out;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
leaf_cachep = kmem_cache_create("ip_set_iptreed",
sizeof(struct ip_set_iptreed),
0, 0, NULL);
#else
leaf_cachep = kmem_cache_create("ip_set_iptreed",
sizeof(struct ip_set_iptreed),
0, 0, NULL, NULL);
#endif
if (!leaf_cachep) {
printk(KERN_ERR "Unable to create ip_set_iptreed slab cache\n");
ret = -ENOMEM;
goto free_branch;
}
ret = ip_set_register_set_type(&ip_set_iptree);
if (ret == 0)
goto out;
kmem_cache_destroy(leaf_cachep);
free_branch:
kmem_cache_destroy(branch_cachep);
out:
return ret;
}
static void __exit ip_set_iptree_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_iptree);
kmem_cache_destroy(leaf_cachep);
kmem_cache_destroy(branch_cachep);
}
module_init(ip_set_iptree_init);
module_exit(ip_set_iptree_fini);

View File

@@ -0,0 +1,40 @@
#ifndef __IP_SET_IPTREE_H
#define __IP_SET_IPTREE_H
#include "ip_set.h"
#define SETTYPE_NAME "iptree"
#define MAX_RANGE 0x0000FFFF
struct ip_set_iptreed {
unsigned long expires[256]; /* x.x.x.ADDR */
};
struct ip_set_iptreec {
struct ip_set_iptreed *tree[256]; /* x.x.ADDR.* */
};
struct ip_set_iptreeb {
struct ip_set_iptreec *tree[256]; /* x.ADDR.*.* */
};
struct ip_set_iptree {
unsigned int timeout;
unsigned int gc_interval;
#ifdef __KERNEL__
uint32_t elements; /* number of elements */
struct timer_list gc;
struct ip_set_iptreeb *tree[256]; /* ADDR.*.*.* */
#endif
};
struct ip_set_req_iptree_create {
unsigned int timeout;
};
struct ip_set_req_iptree {
ip_set_ip_t ip;
unsigned int timeout;
};
#endif /* __IP_SET_IPTREE_H */

View File

@@ -0,0 +1,827 @@
/* Copyright (C) 2007 Sven Wegener <sven.wegener@stealer.net>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
/* This modules implements the iptreemap ipset type. It uses bitmaps to
* represent every single IPv4 address as a bit. The bitmaps are managed in a
* tree structure, where the first three octets of an address are used as an
* index to find the bitmap and the last octet is used as the bit number.
*/
#include <linux/version.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include "ip_set_iptreemap.h"
#define IPTREEMAP_DEFAULT_GC_TIME (5 * 60)
#define IPTREEMAP_DESTROY_SLEEP (100)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
static struct kmem_cache *cachep_b;
static struct kmem_cache *cachep_c;
static struct kmem_cache *cachep_d;
#else
static kmem_cache_t *cachep_b;
static kmem_cache_t *cachep_c;
static kmem_cache_t *cachep_d;
#endif
static struct ip_set_iptreemap_d *fullbitmap_d;
static struct ip_set_iptreemap_c *fullbitmap_c;
static struct ip_set_iptreemap_b *fullbitmap_b;
#if defined(__LITTLE_ENDIAN)
#define ABCD(a, b, c, d, addr) \
do { \
a = ((unsigned char *)addr)[3]; \
b = ((unsigned char *)addr)[2]; \
c = ((unsigned char *)addr)[1]; \
d = ((unsigned char *)addr)[0]; \
} while (0)
#elif defined(__BIG_ENDIAN)
#define ABCD(a,b,c,d,addrp) do { \
a = ((unsigned char *)addrp)[0]; \
b = ((unsigned char *)addrp)[1]; \
c = ((unsigned char *)addrp)[2]; \
d = ((unsigned char *)addrp)[3]; \
} while (0)
#else
#error "Please fix asm/byteorder.h"
#endif /* __LITTLE_ENDIAN */
#define TESTIP_WALK(map, elem, branch, full) \
do { \
branch = (map)->tree[elem]; \
if (!branch) \
return 0; \
else if (branch == full) \
return 1; \
} while (0)
#define ADDIP_WALK(map, elem, branch, type, cachep, full) \
do { \
branch = (map)->tree[elem]; \
if (!branch) { \
branch = (type *) kmem_cache_alloc(cachep, GFP_ATOMIC); \
if (!branch) \
return -ENOMEM; \
memset(branch, 0, sizeof(*branch)); \
(map)->tree[elem] = branch; \
} else if (branch == full) { \
return -EEXIST; \
} \
} while (0)
#define ADDIP_RANGE_LOOP(map, a, a1, a2, hint, branch, full, cachep, free) \
for (a = a1; a <= a2; a++) { \
branch = (map)->tree[a]; \
if (branch != full) { \
if ((a > a1 && a < a2) || (hint)) { \
if (branch) \
free(branch); \
(map)->tree[a] = full; \
continue; \
} else if (!branch) { \
branch = kmem_cache_alloc(cachep, GFP_ATOMIC); \
if (!branch) \
return -ENOMEM; \
memset(branch, 0, sizeof(*branch)); \
(map)->tree[a] = branch; \
}
#define ADDIP_RANGE_LOOP_END() \
} \
}
#define DELIP_WALK(map, elem, branch, cachep, full, flags) \
do { \
branch = (map)->tree[elem]; \
if (!branch) { \
return -EEXIST; \
} else if (branch == full) { \
branch = kmem_cache_alloc(cachep, flags); \
if (!branch) \
return -ENOMEM; \
memcpy(branch, full, sizeof(*full)); \
(map)->tree[elem] = branch; \
} \
} while (0)
#define DELIP_RANGE_LOOP(map, a, a1, a2, hint, branch, full, cachep, free, flags) \
for (a = a1; a <= a2; a++) { \
branch = (map)->tree[a]; \
if (branch) { \
if ((a > a1 && a < a2) || (hint)) { \
if (branch != full) \
free(branch); \
(map)->tree[a] = NULL; \
continue; \
} else if (branch == full) { \
branch = kmem_cache_alloc(cachep, flags); \
if (!branch) \
return -ENOMEM; \
memcpy(branch, full, sizeof(*branch)); \
(map)->tree[a] = branch; \
}
#define DELIP_RANGE_LOOP_END() \
} \
}
#define LOOP_WALK_BEGIN(map, i, branch) \
for (i = 0; i < 256; i++) { \
branch = (map)->tree[i]; \
if (likely(!branch)) \
continue;
#define LOOP_WALK_END() \
}
#define LOOP_WALK_BEGIN_GC(map, i, branch, full, cachep, count) \
count = -256; \
for (i = 0; i < 256; i++) { \
branch = (map)->tree[i]; \
if (likely(!branch)) \
continue; \
count++; \
if (branch == full) { \
count++; \
continue; \
}
#define LOOP_WALK_END_GC(map, i, branch, full, cachep, count) \
if (-256 == count) { \
kmem_cache_free(cachep, branch); \
(map)->tree[i] = NULL; \
} else if (256 == count) { \
kmem_cache_free(cachep, branch); \
(map)->tree[i] = full; \
} \
}
#define LOOP_WALK_BEGIN_COUNT(map, i, branch, inrange, count) \
for (i = 0; i < 256; i++) { \
if (!(map)->tree[i]) { \
if (inrange) { \
count++; \
inrange = 0; \
} \
continue; \
} \
branch = (map)->tree[i];
#define LOOP_WALK_END_COUNT() \
}
#define GETVALUE1(a, a1, b1, r) \
(a == a1 ? b1 : r)
#define GETVALUE2(a, b, a1, b1, c1, r) \
(a == a1 && b == b1 ? c1 : r)
#define GETVALUE3(a, b, c, a1, b1, c1, d1, r) \
(a == a1 && b == b1 && c == c1 ? d1 : r)
#define CHECK1(a, a1, a2, b1, b2, c1, c2, d1, d2) \
( \
GETVALUE1(a, a1, b1, 0) == 0 \
&& GETVALUE1(a, a2, b2, 255) == 255 \
&& c1 == 0 \
&& c2 == 255 \
&& d1 == 0 \
&& d2 == 255 \
)
#define CHECK2(a, b, a1, a2, b1, b2, c1, c2, d1, d2) \
( \
GETVALUE2(a, b, a1, b1, c1, 0) == 0 \
&& GETVALUE2(a, b, a2, b2, c2, 255) == 255 \
&& d1 == 0 \
&& d2 == 255 \
)
#define CHECK3(a, b, c, a1, a2, b1, b2, c1, c2, d1, d2) \
( \
GETVALUE3(a, b, c, a1, b1, c1, d1, 0) == 0 \
&& GETVALUE3(a, b, c, a2, b2, c2, d2, 255) == 255 \
)
static inline void
free_d(struct ip_set_iptreemap_d *map)
{
kmem_cache_free(cachep_d, map);
}
static inline void
free_c(struct ip_set_iptreemap_c *map)
{
struct ip_set_iptreemap_d *dtree;
unsigned int i;
LOOP_WALK_BEGIN(map, i, dtree) {
if (dtree != fullbitmap_d)
free_d(dtree);
} LOOP_WALK_END();
kmem_cache_free(cachep_c, map);
}
static inline void
free_b(struct ip_set_iptreemap_b *map)
{
struct ip_set_iptreemap_c *ctree;
unsigned int i;
LOOP_WALK_BEGIN(map, i, ctree) {
if (ctree != fullbitmap_c)
free_c(ctree);
} LOOP_WALK_END();
kmem_cache_free(cachep_b, map);
}
static inline int
__testip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned char a, b, c, d;
*hash_ip = ip;
ABCD(a, b, c, d, hash_ip);
TESTIP_WALK(map, a, btree, fullbitmap_b);
TESTIP_WALK(btree, b, ctree, fullbitmap_c);
TESTIP_WALK(ctree, c, dtree, fullbitmap_d);
return !!test_bit(d, (void *) dtree->bitmap);
}
static int
testip(struct ip_set *set, const void *data, size_t size, ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iptreemap *req = data;
if (size != sizeof(struct ip_set_req_iptreemap)) {
ip_set_printk("data length wrong (want %zu, have %zu)", sizeof(struct ip_set_req_iptreemap), size);
return -EINVAL;
}
return __testip(set, req->start, hash_ip);
}
static int
testip_kernel(struct ip_set *set, const struct sk_buff *skb, ip_set_ip_t *hash_ip, const u_int32_t *flags, unsigned char index)
{
int res;
res = __testip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
return (res < 0 ? 0 : res);
}
static inline int
__addip_single(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_iptreemap *map = (struct ip_set_iptreemap *) set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned char a, b, c, d;
*hash_ip = ip;
ABCD(a, b, c, d, hash_ip);
ADDIP_WALK(map, a, btree, struct ip_set_iptreemap_b, cachep_b, fullbitmap_b);
ADDIP_WALK(btree, b, ctree, struct ip_set_iptreemap_c, cachep_c, fullbitmap_c);
ADDIP_WALK(ctree, c, dtree, struct ip_set_iptreemap_d, cachep_d, fullbitmap_d);
if (__test_and_set_bit(d, (void *) dtree->bitmap))
return -EEXIST;
__set_bit(b, (void *) btree->dirty);
return 0;
}
static inline int
__addip_range(struct ip_set *set, ip_set_ip_t start, ip_set_ip_t end, ip_set_ip_t *hash_ip)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned int a, b, c, d;
unsigned char a1, b1, c1, d1;
unsigned char a2, b2, c2, d2;
if (start == end)
return __addip_single(set, start, hash_ip);
*hash_ip = start;
ABCD(a1, b1, c1, d1, &start);
ABCD(a2, b2, c2, d2, &end);
/* This is sooo ugly... */
ADDIP_RANGE_LOOP(map, a, a1, a2, CHECK1(a, a1, a2, b1, b2, c1, c2, d1, d2), btree, fullbitmap_b, cachep_b, free_b) {
ADDIP_RANGE_LOOP(btree, b, GETVALUE1(a, a1, b1, 0), GETVALUE1(a, a2, b2, 255), CHECK2(a, b, a1, a2, b1, b2, c1, c2, d1, d2), ctree, fullbitmap_c, cachep_c, free_c) {
ADDIP_RANGE_LOOP(ctree, c, GETVALUE2(a, b, a1, b1, c1, 0), GETVALUE2(a, b, a2, b2, c2, 255), CHECK3(a, b, c, a1, a2, b1, b2, c1, c2, d1, d2), dtree, fullbitmap_d, cachep_d, free_d) {
for (d = GETVALUE3(a, b, c, a1, b1, c1, d1, 0); d <= GETVALUE3(a, b, c, a2, b2, c2, d2, 255); d++)
__set_bit(d, (void *) dtree->bitmap);
__set_bit(b, (void *) btree->dirty);
} ADDIP_RANGE_LOOP_END();
} ADDIP_RANGE_LOOP_END();
} ADDIP_RANGE_LOOP_END();
return 0;
}
static int
addip(struct ip_set *set, const void *data, size_t size, ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iptreemap *req = data;
if (size != sizeof(struct ip_set_req_iptreemap)) {
ip_set_printk("data length wrong (want %zu, have %zu)", sizeof(struct ip_set_req_iptreemap), size);
return -EINVAL;
}
return __addip_range(set, min(req->start, req->end), max(req->start, req->end), hash_ip);
}
static int
addip_kernel(struct ip_set *set, const struct sk_buff *skb, ip_set_ip_t *hash_ip, const u_int32_t *flags, unsigned char index)
{
return __addip_single(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static inline int
__delip_single(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip, unsigned int __nocast flags)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned char a,b,c,d;
*hash_ip = ip;
ABCD(a, b, c, d, hash_ip);
DELIP_WALK(map, a, btree, cachep_b, fullbitmap_b, flags);
DELIP_WALK(btree, b, ctree, cachep_c, fullbitmap_c, flags);
DELIP_WALK(ctree, c, dtree, cachep_d, fullbitmap_d, flags);
if (!__test_and_clear_bit(d, (void *) dtree->bitmap))
return -EEXIST;
__set_bit(b, (void *) btree->dirty);
return 0;
}
static inline int
__delip_range(struct ip_set *set, ip_set_ip_t start, ip_set_ip_t end, ip_set_ip_t *hash_ip, unsigned int __nocast flags)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned int a, b, c, d;
unsigned char a1, b1, c1, d1;
unsigned char a2, b2, c2, d2;
if (start == end)
return __delip_single(set, start, hash_ip, flags);
*hash_ip = start;
ABCD(a1, b1, c1, d1, &start);
ABCD(a2, b2, c2, d2, &end);
/* This is sooo ugly... */
DELIP_RANGE_LOOP(map, a, a1, a2, CHECK1(a, a1, a2, b1, b2, c1, c2, d1, d2), btree, fullbitmap_b, cachep_b, free_b, flags) {
DELIP_RANGE_LOOP(btree, b, GETVALUE1(a, a1, b1, 0), GETVALUE1(a, a2, b2, 255), CHECK2(a, b, a1, a2, b1, b2, c1, c2, d1, d2), ctree, fullbitmap_c, cachep_c, free_c, flags) {
DELIP_RANGE_LOOP(ctree, c, GETVALUE2(a, b, a1, b1, c1, 0), GETVALUE2(a, b, a2, b2, c2, 255), CHECK3(a, b, c, a1, a2, b1, b2, c1, c2, d1, d2), dtree, fullbitmap_d, cachep_d, free_d, flags) {
for (d = GETVALUE3(a, b, c, a1, b1, c1, d1, 0); d <= GETVALUE3(a, b, c, a2, b2, c2, d2, 255); d++)
__clear_bit(d, (void *) dtree->bitmap);
__set_bit(b, (void *) btree->dirty);
} DELIP_RANGE_LOOP_END();
} DELIP_RANGE_LOOP_END();
} DELIP_RANGE_LOOP_END();
return 0;
}
static int
delip(struct ip_set *set, const void *data, size_t size, ip_set_ip_t *hash_ip)
{
const struct ip_set_req_iptreemap *req = data;
if (size != sizeof(struct ip_set_req_iptreemap)) {
ip_set_printk("data length wrong (want %zu, have %zu)", sizeof(struct ip_set_req_iptreemap), size);
return -EINVAL;
}
return __delip_range(set, min(req->start, req->end), max(req->start, req->end), hash_ip, GFP_KERNEL);
}
static int
delip_kernel(struct ip_set *set, const struct sk_buff *skb, ip_set_ip_t *hash_ip, const u_int32_t *flags, unsigned char index)
{
return __delip_single(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip,
GFP_ATOMIC);
}
/* Check the status of the bitmap
* -1 == all bits cleared
* 1 == all bits set
* 0 == anything else
*/
static inline int
bitmap_status(struct ip_set_iptreemap_d *dtree)
{
unsigned char first = dtree->bitmap[0];
int a;
for (a = 1; a < 32; a++)
if (dtree->bitmap[a] != first)
return 0;
return (first == 0 ? -1 : (first == 255 ? 1 : 0));
}
static void
gc(unsigned long addr)
{
struct ip_set *set = (struct ip_set *) addr;
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned int a, b, c;
int i, j, k;
write_lock_bh(&set->lock);
LOOP_WALK_BEGIN_GC(map, a, btree, fullbitmap_b, cachep_b, i) {
LOOP_WALK_BEGIN_GC(btree, b, ctree, fullbitmap_c, cachep_c, j) {
if (!__test_and_clear_bit(b, (void *) btree->dirty))
continue;
LOOP_WALK_BEGIN_GC(ctree, c, dtree, fullbitmap_d, cachep_d, k) {
switch (bitmap_status(dtree)) {
case -1:
kmem_cache_free(cachep_d, dtree);
ctree->tree[c] = NULL;
k--;
break;
case 1:
kmem_cache_free(cachep_d, dtree);
ctree->tree[c] = fullbitmap_d;
k++;
break;
}
} LOOP_WALK_END();
} LOOP_WALK_END_GC(btree, b, ctree, fullbitmap_c, cachep_c, k);
} LOOP_WALK_END_GC(map, a, btree, fullbitmap_b, cachep_b, j);
write_unlock_bh(&set->lock);
map->gc.expires = jiffies + map->gc_interval * HZ;
add_timer(&map->gc);
}
static inline void
init_gc_timer(struct ip_set *set)
{
struct ip_set_iptreemap *map = set->data;
init_timer(&map->gc);
map->gc.data = (unsigned long) set;
map->gc.function = gc;
map->gc.expires = jiffies + map->gc_interval * HZ;
add_timer(&map->gc);
}
static int create(struct ip_set *set, const void *data, size_t size)
{
const struct ip_set_req_iptreemap_create *req = data;
struct ip_set_iptreemap *map;
if (size != sizeof(struct ip_set_req_iptreemap_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)", sizeof(struct ip_set_req_iptreemap_create), size);
return -EINVAL;
}
map = kzalloc(sizeof(*map), GFP_KERNEL);
if (!map)
return -ENOMEM;
map->gc_interval = req->gc_interval ? req->gc_interval : IPTREEMAP_DEFAULT_GC_TIME;
set->data = map;
init_gc_timer(set);
return 0;
}
static inline void __flush(struct ip_set_iptreemap *map)
{
struct ip_set_iptreemap_b *btree;
unsigned int a;
LOOP_WALK_BEGIN(map, a, btree);
if (btree != fullbitmap_b)
free_b(btree);
LOOP_WALK_END();
}
static void destroy(struct ip_set *set)
{
struct ip_set_iptreemap *map = set->data;
while (!del_timer(&map->gc))
msleep(IPTREEMAP_DESTROY_SLEEP);
__flush(map);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_iptreemap *map = set->data;
while (!del_timer(&map->gc))
msleep(IPTREEMAP_DESTROY_SLEEP);
__flush(map);
memset(map, 0, sizeof(*map));
init_gc_timer(set);
}
static void list_header(const struct ip_set *set, void *data)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_req_iptreemap_create *header = data;
header->gc_interval = map->gc_interval;
}
static int list_members_size(const struct ip_set *set)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned int a, b, c, d, inrange = 0, count = 0;
LOOP_WALK_BEGIN_COUNT(map, a, btree, inrange, count) {
LOOP_WALK_BEGIN_COUNT(btree, b, ctree, inrange, count) {
LOOP_WALK_BEGIN_COUNT(ctree, c, dtree, inrange, count) {
for (d = 0; d < 256; d++) {
if (test_bit(d, (void *) dtree->bitmap)) {
inrange = 1;
} else if (inrange) {
count++;
inrange = 0;
}
}
} LOOP_WALK_END_COUNT();
} LOOP_WALK_END_COUNT();
} LOOP_WALK_END_COUNT();
if (inrange)
count++;
return (count * sizeof(struct ip_set_req_iptreemap));
}
static inline size_t add_member(void *data, size_t offset, ip_set_ip_t start, ip_set_ip_t end)
{
struct ip_set_req_iptreemap *entry = data + offset;
entry->start = start;
entry->end = end;
return sizeof(*entry);
}
static void list_members(const struct ip_set *set, void *data)
{
struct ip_set_iptreemap *map = set->data;
struct ip_set_iptreemap_b *btree;
struct ip_set_iptreemap_c *ctree;
struct ip_set_iptreemap_d *dtree;
unsigned int a, b, c, d, inrange = 0;
size_t offset = 0;
ip_set_ip_t start = 0, end = 0, ip;
LOOP_WALK_BEGIN(map, a, btree) {
LOOP_WALK_BEGIN(btree, b, ctree) {
LOOP_WALK_BEGIN(ctree, c, dtree) {
for (d = 0; d < 256; d++) {
if (test_bit(d, (void *) dtree->bitmap)) {
ip = ((a << 24) | (b << 16) | (c << 8) | d);
if (!inrange) {
inrange = 1;
start = ip;
} else if (end < ip - 1) {
offset += add_member(data, offset, start, end);
start = ip;
}
end = ip;
} else if (inrange) {
offset += add_member(data, offset, start, end);
inrange = 0;
}
}
} LOOP_WALK_END();
} LOOP_WALK_END();
} LOOP_WALK_END();
if (inrange)
add_member(data, offset, start, end);
}
static struct ip_set_type ip_set_iptreemap = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = create,
.destroy = destroy,
.flush = flush,
.reqsize = sizeof(struct ip_set_req_iptreemap),
.addip = addip,
.addip_kernel = addip_kernel,
.delip = delip,
.delip_kernel = delip_kernel,
.testip = testip,
.testip_kernel = testip_kernel,
.header_size = sizeof(struct ip_set_req_iptreemap_create),
.list_header = list_header,
.list_members_size = list_members_size,
.list_members = list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Sven Wegener <sven.wegener@stealer.net>");
MODULE_DESCRIPTION("iptreemap type of IP sets");
static int __init ip_set_iptreemap_init(void)
{
int ret = -ENOMEM;
int a;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
cachep_b = kmem_cache_create("ip_set_iptreemap_b",
sizeof(struct ip_set_iptreemap_b),
0, 0, NULL);
#else
cachep_b = kmem_cache_create("ip_set_iptreemap_b",
sizeof(struct ip_set_iptreemap_b),
0, 0, NULL, NULL);
#endif
if (!cachep_b) {
ip_set_printk("Unable to create ip_set_iptreemap_b slab cache");
goto out;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
cachep_c = kmem_cache_create("ip_set_iptreemap_c",
sizeof(struct ip_set_iptreemap_c),
0, 0, NULL);
#else
cachep_c = kmem_cache_create("ip_set_iptreemap_c",
sizeof(struct ip_set_iptreemap_c),
0, 0, NULL, NULL);
#endif
if (!cachep_c) {
ip_set_printk("Unable to create ip_set_iptreemap_c slab cache");
goto outb;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
cachep_d = kmem_cache_create("ip_set_iptreemap_d",
sizeof(struct ip_set_iptreemap_d),
0, 0, NULL);
#else
cachep_d = kmem_cache_create("ip_set_iptreemap_d",
sizeof(struct ip_set_iptreemap_d),
0, 0, NULL, NULL);
#endif
if (!cachep_d) {
ip_set_printk("Unable to create ip_set_iptreemap_d slab cache");
goto outc;
}
fullbitmap_d = kmem_cache_alloc(cachep_d, GFP_KERNEL);
if (!fullbitmap_d)
goto outd;
fullbitmap_c = kmem_cache_alloc(cachep_c, GFP_KERNEL);
if (!fullbitmap_c)
goto outbitmapd;
fullbitmap_b = kmem_cache_alloc(cachep_b, GFP_KERNEL);
if (!fullbitmap_b)
goto outbitmapc;
ret = ip_set_register_set_type(&ip_set_iptreemap);
if (0 > ret)
goto outbitmapb;
/* Now init our global bitmaps */
memset(fullbitmap_d->bitmap, 0xff, sizeof(fullbitmap_d->bitmap));
for (a = 0; a < 256; a++)
fullbitmap_c->tree[a] = fullbitmap_d;
for (a = 0; a < 256; a++)
fullbitmap_b->tree[a] = fullbitmap_c;
memset(fullbitmap_b->dirty, 0, sizeof(fullbitmap_b->dirty));
return 0;
outbitmapb:
kmem_cache_free(cachep_b, fullbitmap_b);
outbitmapc:
kmem_cache_free(cachep_c, fullbitmap_c);
outbitmapd:
kmem_cache_free(cachep_d, fullbitmap_d);
outd:
kmem_cache_destroy(cachep_d);
outc:
kmem_cache_destroy(cachep_c);
outb:
kmem_cache_destroy(cachep_b);
out:
return ret;
}
static void __exit ip_set_iptreemap_fini(void)
{
ip_set_unregister_set_type(&ip_set_iptreemap);
kmem_cache_free(cachep_d, fullbitmap_d);
kmem_cache_free(cachep_c, fullbitmap_c);
kmem_cache_free(cachep_b, fullbitmap_b);
kmem_cache_destroy(cachep_d);
kmem_cache_destroy(cachep_c);
kmem_cache_destroy(cachep_b);
}
module_init(ip_set_iptreemap_init);
module_exit(ip_set_iptreemap_fini);

View File

@@ -0,0 +1,40 @@
#ifndef __IP_SET_IPTREEMAP_H
#define __IP_SET_IPTREEMAP_H
#include "ip_set.h"
#define SETTYPE_NAME "iptreemap"
#ifdef __KERNEL__
struct ip_set_iptreemap_d {
unsigned char bitmap[32]; /* x.x.x.y */
};
struct ip_set_iptreemap_c {
struct ip_set_iptreemap_d *tree[256]; /* x.x.y.x */
};
struct ip_set_iptreemap_b {
struct ip_set_iptreemap_c *tree[256]; /* x.y.x.x */
unsigned char dirty[32];
};
#endif
struct ip_set_iptreemap {
unsigned int gc_interval;
#ifdef __KERNEL__
struct timer_list gc;
struct ip_set_iptreemap_b *tree[256]; /* y.x.x.x */
#endif
};
struct ip_set_req_iptreemap_create {
unsigned int gc_interval;
};
struct ip_set_req_iptreemap {
ip_set_ip_t start;
ip_set_ip_t end;
};
#endif /* __IP_SET_IPTREEMAP_H */

View File

@@ -0,0 +1,148 @@
#ifndef _LINUX_IPSET_JHASH_H
#define _LINUX_IPSET_JHASH_H
/* This is a copy of linux/jhash.h but the types u32/u8 are changed
* to __u32/__u8 so that the header file can be included into
* userspace code as well. Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*/
/* jhash.h: Jenkins hash support.
*
* Copyright (C) 1996 Bob Jenkins (bob_jenkins@burtleburtle.net)
*
* http://burtleburtle.net/bob/hash/
*
* These are the credits from Bob's sources:
*
* lookup2.c, by Bob Jenkins, December 1996, Public Domain.
* hash(), hash2(), hash3, and mix() are externally useful functions.
* Routines to test the hash are included if SELF_TEST is defined.
* You can use this free for any purpose. It has no warranty.
*
* Copyright (C) 2003 David S. Miller (davem@redhat.com)
*
* I've modified Bob's hash to be useful in the Linux kernel, and
* any bugs present are surely my fault. -DaveM
*/
/* NOTE: Arguments are modified. */
#define __jhash_mix(a, b, c) \
{ \
a -= b; a -= c; a ^= (c>>13); \
b -= c; b -= a; b ^= (a<<8); \
c -= a; c -= b; c ^= (b>>13); \
a -= b; a -= c; a ^= (c>>12); \
b -= c; b -= a; b ^= (a<<16); \
c -= a; c -= b; c ^= (b>>5); \
a -= b; a -= c; a ^= (c>>3); \
b -= c; b -= a; b ^= (a<<10); \
c -= a; c -= b; c ^= (b>>15); \
}
/* The golden ration: an arbitrary value */
#define JHASH_GOLDEN_RATIO 0x9e3779b9
/* The most generic version, hashes an arbitrary sequence
* of bytes. No alignment or length assumptions are made about
* the input key.
*/
static inline __u32 jhash(void *key, __u32 length, __u32 initval)
{
__u32 a, b, c, len;
__u8 *k = key;
len = length;
a = b = JHASH_GOLDEN_RATIO;
c = initval;
while (len >= 12) {
a += (k[0] +((__u32)k[1]<<8) +((__u32)k[2]<<16) +((__u32)k[3]<<24));
b += (k[4] +((__u32)k[5]<<8) +((__u32)k[6]<<16) +((__u32)k[7]<<24));
c += (k[8] +((__u32)k[9]<<8) +((__u32)k[10]<<16)+((__u32)k[11]<<24));
__jhash_mix(a,b,c);
k += 12;
len -= 12;
}
c += length;
switch (len) {
case 11: c += ((__u32)k[10]<<24);
case 10: c += ((__u32)k[9]<<16);
case 9 : c += ((__u32)k[8]<<8);
case 8 : b += ((__u32)k[7]<<24);
case 7 : b += ((__u32)k[6]<<16);
case 6 : b += ((__u32)k[5]<<8);
case 5 : b += k[4];
case 4 : a += ((__u32)k[3]<<24);
case 3 : a += ((__u32)k[2]<<16);
case 2 : a += ((__u32)k[1]<<8);
case 1 : a += k[0];
};
__jhash_mix(a,b,c);
return c;
}
/* A special optimized version that handles 1 or more of __u32s.
* The length parameter here is the number of __u32s in the key.
*/
static inline __u32 jhash2(__u32 *k, __u32 length, __u32 initval)
{
__u32 a, b, c, len;
a = b = JHASH_GOLDEN_RATIO;
c = initval;
len = length;
while (len >= 3) {
a += k[0];
b += k[1];
c += k[2];
__jhash_mix(a, b, c);
k += 3; len -= 3;
}
c += length * 4;
switch (len) {
case 2 : b += k[1];
case 1 : a += k[0];
};
__jhash_mix(a,b,c);
return c;
}
/* A special ultra-optimized versions that knows they are hashing exactly
* 3, 2 or 1 word(s).
*
* NOTE: In partilar the "c += length; __jhash_mix(a,b,c);" normally
* done at the end is not done here.
*/
static inline __u32 jhash_3words(__u32 a, __u32 b, __u32 c, __u32 initval)
{
a += JHASH_GOLDEN_RATIO;
b += JHASH_GOLDEN_RATIO;
c += initval;
__jhash_mix(a, b, c);
return c;
}
static inline __u32 jhash_2words(__u32 a, __u32 b, __u32 initval)
{
return jhash_3words(a, b, 0, initval);
}
static inline __u32 jhash_1word(__u32 a, __u32 initval)
{
return jhash_3words(a, 0, 0, initval);
}
#endif /* _LINUX_IPSET_JHASH_H */

View File

@@ -0,0 +1,360 @@
/* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
* Patrick Schaaf <bof@bof.de>
* Martin Josefsson <gandalf@wlug.westbo.se>
* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an IP set type: the macipmap type */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include <linux/if_ether.h>
#include <linux/vmalloc.h>
#include "ip_set_malloc.h"
#include "ip_set_macipmap.h"
static int
testip(struct ip_set *set, const void *data, size_t size, ip_set_ip_t *hash_ip)
{
struct ip_set_macipmap *map = set->data;
struct ip_set_macip *table = map->members;
const struct ip_set_req_macipmap *req = data;
if (size != sizeof(struct ip_set_req_macipmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_macipmap),
size);
return -EINVAL;
}
if (req->ip < map->first_ip || req->ip > map->last_ip)
return -ERANGE;
*hash_ip = req->ip;
DP("set: %s, ip:%u.%u.%u.%u, %u.%u.%u.%u",
set->name, HIPQUAD(req->ip), HIPQUAD(*hash_ip));
if (test_bit(IPSET_MACIP_ISSET,
(void *) &table[req->ip - map->first_ip].flags)) {
return (memcmp(req->ethernet,
&table[req->ip - map->first_ip].ethernet,
ETH_ALEN) == 0);
} else {
return (map->flags & IPSET_MACIP_MATCHUNSET ? 1 : 0);
}
}
static int
testip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
struct ip_set_macipmap *map = set->data;
struct ip_set_macip *table = map->members;
ip_set_ip_t ip;
ip = ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr);
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr);
#endif
if (ip < map->first_ip || ip > map->last_ip)
return 0;
*hash_ip = ip;
DP("set: %s, ip:%u.%u.%u.%u, %u.%u.%u.%u",
set->name, HIPQUAD(ip), HIPQUAD(*hash_ip));
if (test_bit(IPSET_MACIP_ISSET,
(void *) &table[ip - map->first_ip].flags)) {
/* Is mac pointer valid?
* If so, compare... */
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
return (skb_mac_header(skb) >= skb->head
&& (skb_mac_header(skb) + ETH_HLEN) <= skb->data
#else
return (skb->mac.raw >= skb->head
&& (skb->mac.raw + ETH_HLEN) <= skb->data
#endif
&& (memcmp(eth_hdr(skb)->h_source,
&table[ip - map->first_ip].ethernet,
ETH_ALEN) == 0));
} else {
return (map->flags & IPSET_MACIP_MATCHUNSET ? 1 : 0);
}
}
/* returns 0 on success */
static inline int
__addip(struct ip_set *set,
ip_set_ip_t ip, const unsigned char *ethernet, ip_set_ip_t *hash_ip)
{
struct ip_set_macipmap *map = set->data;
struct ip_set_macip *table = map->members;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
if (test_and_set_bit(IPSET_MACIP_ISSET,
(void *) &table[ip - map->first_ip].flags))
return -EEXIST;
*hash_ip = ip;
DP("%u.%u.%u.%u, %u.%u.%u.%u", HIPQUAD(ip), HIPQUAD(*hash_ip));
memcpy(&table[ip - map->first_ip].ethernet, ethernet, ETH_ALEN);
return 0;
}
static int
addip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_macipmap *req = data;
if (size != sizeof(struct ip_set_req_macipmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_macipmap),
size);
return -EINVAL;
}
return __addip(set, req->ip, req->ethernet, hash_ip);
}
static int
addip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
ip_set_ip_t ip;
ip = ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr);
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr);
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
if (!(skb_mac_header(skb) >= skb->head
&& (skb_mac_header(skb) + ETH_HLEN) <= skb->data))
#else
if (!(skb->mac.raw >= skb->head
&& (skb->mac.raw + ETH_HLEN) <= skb->data))
#endif
return -EINVAL;
return __addip(set, ip, eth_hdr(skb)->h_source, hash_ip);
}
static inline int
__delip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_macipmap *map = set->data;
struct ip_set_macip *table = map->members;
if (ip < map->first_ip || ip > map->last_ip)
return -ERANGE;
if (!test_and_clear_bit(IPSET_MACIP_ISSET,
(void *)&table[ip - map->first_ip].flags))
return -EEXIST;
*hash_ip = ip;
DP("%u.%u.%u.%u, %u.%u.%u.%u", HIPQUAD(ip), HIPQUAD(*hash_ip));
return 0;
}
static int
delip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_macipmap *req = data;
if (size != sizeof(struct ip_set_req_macipmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_macipmap),
size);
return -EINVAL;
}
return __delip(set, req->ip, hash_ip);
}
static int
delip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __delip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static inline size_t members_size(ip_set_ip_t from, ip_set_ip_t to)
{
return (size_t)((to - from + 1) * sizeof(struct ip_set_macip));
}
static int create(struct ip_set *set, const void *data, size_t size)
{
size_t newbytes;
const struct ip_set_req_macipmap_create *req = data;
struct ip_set_macipmap *map;
if (size != sizeof(struct ip_set_req_macipmap_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_macipmap_create),
size);
return -EINVAL;
}
DP("from %u.%u.%u.%u to %u.%u.%u.%u",
HIPQUAD(req->from), HIPQUAD(req->to));
if (req->from > req->to) {
DP("bad ip range");
return -ENOEXEC;
}
if (req->to - req->from > MAX_RANGE) {
ip_set_printk("range too big (max %d addresses)",
MAX_RANGE+1);
return -ENOEXEC;
}
map = kmalloc(sizeof(struct ip_set_macipmap), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_macipmap));
return -ENOMEM;
}
map->flags = req->flags;
map->first_ip = req->from;
map->last_ip = req->to;
newbytes = members_size(map->first_ip, map->last_ip);
map->members = ip_set_malloc(newbytes);
DP("members: %u %p", newbytes, map->members);
if (!map->members) {
DP("out of memory for %d bytes", newbytes);
kfree(map);
return -ENOMEM;
}
memset(map->members, 0, newbytes);
set->data = map;
return 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_macipmap *map = set->data;
ip_set_free(map->members, members_size(map->first_ip, map->last_ip));
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_macipmap *map = set->data;
memset(map->members, 0, members_size(map->first_ip, map->last_ip));
}
static void list_header(const struct ip_set *set, void *data)
{
const struct ip_set_macipmap *map = set->data;
struct ip_set_req_macipmap_create *header = data;
DP("list_header %x %x %u", map->first_ip, map->last_ip,
map->flags);
header->from = map->first_ip;
header->to = map->last_ip;
header->flags = map->flags;
}
static int list_members_size(const struct ip_set *set)
{
const struct ip_set_macipmap *map = set->data;
DP("%u", members_size(map->first_ip, map->last_ip));
return members_size(map->first_ip, map->last_ip);
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_macipmap *map = set->data;
int bytes = members_size(map->first_ip, map->last_ip);
DP("members: %u %p", bytes, map->members);
memcpy(data, map->members, bytes);
}
static struct ip_set_type ip_set_macipmap = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_macipmap),
.addip = &addip,
.addip_kernel = &addip_kernel,
.delip = &delip,
.delip_kernel = &delip_kernel,
.testip = &testip,
.testip_kernel = &testip_kernel,
.header_size = sizeof(struct ip_set_req_macipmap_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("macipmap type of IP sets");
static int __init ip_set_macipmap_init(void)
{
init_max_page_size();
return ip_set_register_set_type(&ip_set_macipmap);
}
static void __exit ip_set_macipmap_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_macipmap);
}
module_init(ip_set_macipmap_init);
module_exit(ip_set_macipmap_fini);

View File

@@ -0,0 +1,38 @@
#ifndef __IP_SET_MACIPMAP_H
#define __IP_SET_MACIPMAP_H
#include "ip_set.h"
#define SETTYPE_NAME "macipmap"
#define MAX_RANGE 0x0000FFFF
/* general flags */
#define IPSET_MACIP_MATCHUNSET 1
/* per ip flags */
#define IPSET_MACIP_ISSET 1
struct ip_set_macipmap {
void *members; /* the macipmap proper */
ip_set_ip_t first_ip; /* host byte order, included in range */
ip_set_ip_t last_ip; /* host byte order, included in range */
u_int32_t flags;
};
struct ip_set_req_macipmap_create {
ip_set_ip_t from;
ip_set_ip_t to;
u_int32_t flags;
};
struct ip_set_req_macipmap {
ip_set_ip_t ip;
unsigned char ethernet[ETH_ALEN];
};
struct ip_set_macip {
unsigned short flags;
unsigned char ethernet[ETH_ALEN];
};
#endif /* __IP_SET_MACIPMAP_H */

View File

@@ -0,0 +1,143 @@
#ifndef _IP_SET_MALLOC_H
#define _IP_SET_MALLOC_H
#ifdef __KERNEL__
static size_t max_malloc_size = 0, max_page_size = 0;
static inline unsigned int init_max_page_size(void)
{
size_t page_size = 0;
#define CACHE(x) if (max_page_size == 0 || x < max_page_size) \
page_size = x;
#include <linux/kmalloc_sizes.h>
#undef CACHE
if (page_size) {
if (max_malloc_size == 0)
max_malloc_size = page_size;
max_page_size = page_size;
return 1;
}
return 0;
}
struct harray {
size_t max_elements;
void *arrays[0];
};
static inline void *
__harray_malloc(size_t hashsize, size_t typesize, int flags)
{
struct harray *harray;
size_t max_elements, size, i, j;
BUG_ON(max_page_size == 0);
if (typesize > max_page_size)
return NULL;
max_elements = max_page_size/typesize;
size = hashsize/max_elements;
if (hashsize % max_elements)
size++;
/* Last pointer signals end of arrays */
harray = kmalloc(sizeof(struct harray) + (size + 1) * sizeof(void *),
flags);
if (!harray)
return NULL;
for (i = 0; i < size - 1; i++) {
harray->arrays[i] = kmalloc(max_elements * typesize, flags);
if (!harray->arrays[i])
goto undo;
memset(harray->arrays[i], 0, max_elements * typesize);
}
harray->arrays[i] = kmalloc((hashsize - i * max_elements) * typesize,
flags);
if (!harray->arrays[i])
goto undo;
memset(harray->arrays[i], 0, (hashsize - i * max_elements) * typesize);
harray->max_elements = max_elements;
harray->arrays[size] = NULL;
return (void *)harray;
undo:
for (j = 0; j < i; j++) {
kfree(harray->arrays[j]);
}
kfree(harray);
return NULL;
}
static inline void *
harray_malloc(size_t hashsize, size_t typesize, int flags)
{
void *harray;
do {
harray = __harray_malloc(hashsize, typesize, flags|__GFP_NOWARN);
} while (harray == NULL && init_max_page_size());
return harray;
}
static inline void harray_free(void *h)
{
struct harray *harray = (struct harray *) h;
size_t i;
for (i = 0; harray->arrays[i] != NULL; i++)
kfree(harray->arrays[i]);
kfree(harray);
}
static inline void harray_flush(void *h, size_t hashsize, size_t typesize)
{
struct harray *harray = (struct harray *) h;
size_t i;
for (i = 0; harray->arrays[i+1] != NULL; i++)
memset(harray->arrays[i], 0, harray->max_elements * typesize);
memset(harray->arrays[i], 0,
(hashsize - i * harray->max_elements) * typesize);
}
#define HARRAY_ELEM(h, type, which) \
({ \
struct harray *__h = (struct harray *)(h); \
((type)((__h)->arrays[(which)/(__h)->max_elements]) \
+ (which)%(__h)->max_elements); \
})
/* General memory allocation and deallocation */
static inline void * ip_set_malloc(size_t bytes)
{
BUG_ON(max_malloc_size == 0);
if (bytes > max_malloc_size)
return vmalloc(bytes);
else
return kmalloc(bytes, GFP_KERNEL | __GFP_NOWARN);
}
static inline void ip_set_free(void * data, size_t bytes)
{
BUG_ON(max_malloc_size == 0);
if (bytes > max_malloc_size)
vfree(data);
else
kfree(data);
}
#endif /* __KERNEL__ */
#endif /*_IP_SET_MALLOC_H*/

View File

@@ -0,0 +1,490 @@
/* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing a cidr nethash set */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/jhash.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <linux/random.h>
#include <net/ip.h>
#include "ip_set_malloc.h"
#include "ip_set_nethash.h"
static int limit = MAX_RANGE;
static inline __u32
jhash_ip(const struct ip_set_nethash *map, uint16_t i, ip_set_ip_t ip)
{
return jhash_1word(ip, *(((uint32_t *) map->initval) + i));
}
static inline __u32
hash_id_cidr(struct ip_set_nethash *map,
ip_set_ip_t ip,
unsigned char cidr,
ip_set_ip_t *hash_ip)
{
__u32 id;
u_int16_t i;
ip_set_ip_t *elem;
*hash_ip = pack(ip, cidr);
for (i = 0; i < map->probes; i++) {
id = jhash_ip(map, i, *hash_ip) % map->hashsize;
DP("hash key: %u", id);
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, id);
if (*elem == *hash_ip)
return id;
}
return UINT_MAX;
}
static inline __u32
hash_id(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
struct ip_set_nethash *map = set->data;
__u32 id = UINT_MAX;
int i;
for (i = 0; i < 30 && map->cidr[i]; i++) {
id = hash_id_cidr(map, ip, map->cidr[i], hash_ip);
if (id != UINT_MAX)
break;
}
return id;
}
static inline int
__testip_cidr(struct ip_set *set, ip_set_ip_t ip, unsigned char cidr,
ip_set_ip_t *hash_ip)
{
struct ip_set_nethash *map = set->data;
return (ip && hash_id_cidr(map, ip, cidr, hash_ip) != UINT_MAX);
}
static inline int
__testip(struct ip_set *set, ip_set_ip_t ip, ip_set_ip_t *hash_ip)
{
return (ip && hash_id(set, ip, hash_ip) != UINT_MAX);
}
static int
testip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_nethash *req = data;
if (size != sizeof(struct ip_set_req_nethash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_nethash),
size);
return -EINVAL;
}
return (req->cidr == 32 ? __testip(set, req->ip, hash_ip)
: __testip_cidr(set, req->ip, req->cidr, hash_ip));
}
static int
testip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
return __testip(set,
ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr),
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr),
#endif
hash_ip);
}
static inline int
__addip_base(struct ip_set_nethash *map, ip_set_ip_t ip)
{
__u32 probe;
u_int16_t i;
ip_set_ip_t *elem;
for (i = 0; i < map->probes; i++) {
probe = jhash_ip(map, i, ip) % map->hashsize;
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, probe);
if (*elem == ip)
return -EEXIST;
if (!*elem) {
*elem = ip;
map->elements++;
return 0;
}
}
/* Trigger rehashing */
return -EAGAIN;
}
static inline int
__addip(struct ip_set_nethash *map, ip_set_ip_t ip, unsigned char cidr,
ip_set_ip_t *hash_ip)
{
if (!ip || map->elements >= limit)
return -ERANGE;
*hash_ip = pack(ip, cidr);
DP("%u.%u.%u.%u/%u, %u.%u.%u.%u", HIPQUAD(ip), cidr, HIPQUAD(*hash_ip));
return __addip_base(map, *hash_ip);
}
static void
update_cidr_sizes(struct ip_set_nethash *map, unsigned char cidr)
{
unsigned char next;
int i;
for (i = 0; i < 30 && map->cidr[i]; i++) {
if (map->cidr[i] == cidr) {
return;
} else if (map->cidr[i] < cidr) {
next = map->cidr[i];
map->cidr[i] = cidr;
cidr = next;
}
}
if (i < 30)
map->cidr[i] = cidr;
}
static int
addip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_nethash *req = data;
int ret;
if (size != sizeof(struct ip_set_req_nethash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_nethash),
size);
return -EINVAL;
}
ret = __addip(set->data, req->ip, req->cidr, hash_ip);
if (ret == 0)
update_cidr_sizes(set->data, req->cidr);
return ret;
}
static int
addip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
struct ip_set_nethash *map = set->data;
int ret = -ERANGE;
ip_set_ip_t ip = ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr);
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr);
#endif
if (map->cidr[0])
ret = __addip(map, ip, map->cidr[0], hash_ip);
return ret;
}
static int retry(struct ip_set *set)
{
struct ip_set_nethash *map = set->data;
ip_set_ip_t *elem;
void *members;
u_int32_t i, hashsize = map->hashsize;
int res;
struct ip_set_nethash *tmp;
if (map->resize == 0)
return -ERANGE;
again:
res = 0;
/* Calculate new parameters */
hashsize += (hashsize * map->resize)/100;
if (hashsize == map->hashsize)
hashsize++;
ip_set_printk("rehashing of set %s triggered: "
"hashsize grows from %u to %u",
set->name, map->hashsize, hashsize);
tmp = kmalloc(sizeof(struct ip_set_nethash)
+ map->probes * sizeof(uint32_t), GFP_ATOMIC);
if (!tmp) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_nethash)
+ map->probes * sizeof(uint32_t));
return -ENOMEM;
}
tmp->members = harray_malloc(hashsize, sizeof(ip_set_ip_t), GFP_ATOMIC);
if (!tmp->members) {
DP("out of memory for %d bytes", hashsize * sizeof(ip_set_ip_t));
kfree(tmp);
return -ENOMEM;
}
tmp->hashsize = hashsize;
tmp->elements = 0;
tmp->probes = map->probes;
tmp->resize = map->resize;
memcpy(tmp->initval, map->initval, map->probes * sizeof(uint32_t));
memcpy(tmp->cidr, map->cidr, 30 * sizeof(unsigned char));
write_lock_bh(&set->lock);
map = set->data; /* Play safe */
for (i = 0; i < map->hashsize && res == 0; i++) {
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, i);
if (*elem)
res = __addip_base(tmp, *elem);
}
if (res) {
/* Failure, try again */
write_unlock_bh(&set->lock);
harray_free(tmp->members);
kfree(tmp);
goto again;
}
/* Success at resizing! */
members = map->members;
map->hashsize = tmp->hashsize;
map->members = tmp->members;
write_unlock_bh(&set->lock);
harray_free(members);
kfree(tmp);
return 0;
}
static inline int
__delip(struct ip_set_nethash *map, ip_set_ip_t ip, unsigned char cidr,
ip_set_ip_t *hash_ip)
{
ip_set_ip_t id, *elem;
if (!ip)
return -ERANGE;
id = hash_id_cidr(map, ip, cidr, hash_ip);
if (id == UINT_MAX)
return -EEXIST;
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, id);
*elem = 0;
map->elements--;
return 0;
}
static int
delip(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_ip)
{
const struct ip_set_req_nethash *req = data;
if (size != sizeof(struct ip_set_req_nethash)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_nethash),
size);
return -EINVAL;
}
/* TODO: no garbage collection in map->cidr */
return __delip(set->data, req->ip, req->cidr, hash_ip);
}
static int
delip_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_ip,
const u_int32_t *flags,
unsigned char index)
{
struct ip_set_nethash *map = set->data;
int ret = -ERANGE;
ip_set_ip_t ip = ntohl(flags[index] & IPSET_SRC
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
? ip_hdr(skb)->saddr
: ip_hdr(skb)->daddr);
#else
? skb->nh.iph->saddr
: skb->nh.iph->daddr);
#endif
if (map->cidr[0])
ret = __delip(map, ip, map->cidr[0], hash_ip);
return ret;
}
static int create(struct ip_set *set, const void *data, size_t size)
{
const struct ip_set_req_nethash_create *req = data;
struct ip_set_nethash *map;
uint16_t i;
if (size != sizeof(struct ip_set_req_nethash_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_nethash_create),
size);
return -EINVAL;
}
if (req->hashsize < 1) {
ip_set_printk("hashsize too small");
return -ENOEXEC;
}
if (req->probes < 1) {
ip_set_printk("probes too small");
return -ENOEXEC;
}
map = kmalloc(sizeof(struct ip_set_nethash)
+ req->probes * sizeof(uint32_t), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_nethash)
+ req->probes * sizeof(uint32_t));
return -ENOMEM;
}
for (i = 0; i < req->probes; i++)
get_random_bytes(((uint32_t *) map->initval)+i, 4);
map->elements = 0;
map->hashsize = req->hashsize;
map->probes = req->probes;
map->resize = req->resize;
memset(map->cidr, 0, 30 * sizeof(unsigned char));
map->members = harray_malloc(map->hashsize, sizeof(ip_set_ip_t), GFP_KERNEL);
if (!map->members) {
DP("out of memory for %d bytes", map->hashsize * sizeof(ip_set_ip_t));
kfree(map);
return -ENOMEM;
}
set->data = map;
return 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_nethash *map = set->data;
harray_free(map->members);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_nethash *map = set->data;
harray_flush(map->members, map->hashsize, sizeof(ip_set_ip_t));
memset(map->cidr, 0, 30 * sizeof(unsigned char));
map->elements = 0;
}
static void list_header(const struct ip_set *set, void *data)
{
const struct ip_set_nethash *map = set->data;
struct ip_set_req_nethash_create *header = data;
header->hashsize = map->hashsize;
header->probes = map->probes;
header->resize = map->resize;
}
static int list_members_size(const struct ip_set *set)
{
struct ip_set_nethash *map = set->data;
return (map->hashsize * sizeof(ip_set_ip_t));
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_nethash *map = set->data;
ip_set_ip_t i, *elem;
for (i = 0; i < map->hashsize; i++) {
elem = HARRAY_ELEM(map->members, ip_set_ip_t *, i);
((ip_set_ip_t *)data)[i] = *elem;
}
}
static struct ip_set_type ip_set_nethash = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_IP | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_nethash),
.addip = &addip,
.addip_kernel = &addip_kernel,
.retry = &retry,
.delip = &delip,
.delip_kernel = &delip_kernel,
.testip = &testip,
.testip_kernel = &testip_kernel,
.header_size = sizeof(struct ip_set_req_nethash_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("nethash type of IP sets");
module_param(limit, int, 0600);
MODULE_PARM_DESC(limit, "maximal number of elements stored in the sets");
static int __init ip_set_nethash_init(void)
{
init_max_page_size();
return ip_set_register_set_type(&ip_set_nethash);
}
static void __exit ip_set_nethash_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_nethash);
}
module_init(ip_set_nethash_init);
module_exit(ip_set_nethash_fini);

View File

@@ -0,0 +1,55 @@
#ifndef __IP_SET_NETHASH_H
#define __IP_SET_NETHASH_H
#include "ip_set.h"
#define SETTYPE_NAME "nethash"
#define MAX_RANGE 0x0000FFFF
struct ip_set_nethash {
ip_set_ip_t *members; /* the nethash proper */
uint32_t elements; /* number of elements */
uint32_t hashsize; /* hash size */
uint16_t probes; /* max number of probes */
uint16_t resize; /* resize factor in percent */
unsigned char cidr[30]; /* CIDR sizes */
void *initval[0]; /* initvals for jhash_1word */
};
struct ip_set_req_nethash_create {
uint32_t hashsize;
uint16_t probes;
uint16_t resize;
};
struct ip_set_req_nethash {
ip_set_ip_t ip;
unsigned char cidr;
};
static unsigned char shifts[] = {255, 253, 249, 241, 225, 193, 129, 1};
static inline ip_set_ip_t
pack(ip_set_ip_t ip, unsigned char cidr)
{
ip_set_ip_t addr, *paddr = &addr;
unsigned char n, t, *a;
addr = htonl(ip & (0xFFFFFFFF << (32 - (cidr))));
#ifdef __KERNEL__
DP("ip:%u.%u.%u.%u/%u", NIPQUAD(addr), cidr);
#endif
n = cidr / 8;
t = cidr % 8;
a = &((unsigned char *)paddr)[n];
*a = *a /(1 << (8 - t)) + shifts[t];
#ifdef __KERNEL__
DP("n: %u, t: %u, a: %u", n, t, *a);
DP("ip:%u.%u.%u.%u/%u, %u.%u.%u.%u",
HIPQUAD(ip), cidr, NIPQUAD(addr));
#endif
return ntohl(addr);
}
#endif /* __IP_SET_NETHASH_H */

View File

@@ -0,0 +1,341 @@
/* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing a port set type as a bitmap */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/bitops.h>
#include <linux/spinlock.h>
#include <net/ip.h>
#include "ip_set_portmap.h"
/* We must handle non-linear skbs */
static inline ip_set_ip_t
get_port(const struct sk_buff *skb, u_int32_t flags)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
struct iphdr *iph = ip_hdr(skb);
#else
struct iphdr *iph = skb->nh.iph;
#endif
u_int16_t offset = ntohs(iph->frag_off) & IP_OFFSET;
switch (iph->protocol) {
case IPPROTO_TCP: {
struct tcphdr tcph;
/* See comments at tcp_match in ip_tables.c */
if (offset)
return INVALID_PORT;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
if (skb_copy_bits(skb, ip_hdr(skb)->ihl*4, &tcph, sizeof(tcph)) < 0)
#else
if (skb_copy_bits(skb, skb->nh.iph->ihl*4, &tcph, sizeof(tcph)) < 0)
#endif
/* No choice either */
return INVALID_PORT;
return ntohs(flags & IPSET_SRC ?
tcph.source : tcph.dest);
}
case IPPROTO_UDP: {
struct udphdr udph;
if (offset)
return INVALID_PORT;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
if (skb_copy_bits(skb, ip_hdr(skb)->ihl*4, &udph, sizeof(udph)) < 0)
#else
if (skb_copy_bits(skb, skb->nh.iph->ihl*4, &udph, sizeof(udph)) < 0)
#endif
/* No choice either */
return INVALID_PORT;
return ntohs(flags & IPSET_SRC ?
udph.source : udph.dest);
}
default:
return INVALID_PORT;
}
}
static inline int
__testport(struct ip_set *set, ip_set_ip_t port, ip_set_ip_t *hash_port)
{
struct ip_set_portmap *map = set->data;
if (port < map->first_port || port > map->last_port)
return -ERANGE;
*hash_port = port;
DP("set: %s, port:%u, %u", set->name, port, *hash_port);
return !!test_bit(port - map->first_port, map->members);
}
static int
testport(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_port)
{
const struct ip_set_req_portmap *req = data;
if (size != sizeof(struct ip_set_req_portmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_portmap),
size);
return -EINVAL;
}
return __testport(set, req->port, hash_port);
}
static int
testport_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_port,
const u_int32_t *flags,
unsigned char index)
{
int res;
ip_set_ip_t port = get_port(skb, flags[index]);
DP("flag %s port %u", flags[index] & IPSET_SRC ? "SRC" : "DST", port);
if (port == INVALID_PORT)
return 0;
res = __testport(set, port, hash_port);
return (res < 0 ? 0 : res);
}
static inline int
__addport(struct ip_set *set, ip_set_ip_t port, ip_set_ip_t *hash_port)
{
struct ip_set_portmap *map = set->data;
if (port < map->first_port || port > map->last_port)
return -ERANGE;
if (test_and_set_bit(port - map->first_port, map->members))
return -EEXIST;
*hash_port = port;
DP("port %u", port);
return 0;
}
static int
addport(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_port)
{
const struct ip_set_req_portmap *req = data;
if (size != sizeof(struct ip_set_req_portmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_portmap),
size);
return -EINVAL;
}
return __addport(set, req->port, hash_port);
}
static int
addport_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_port,
const u_int32_t *flags,
unsigned char index)
{
ip_set_ip_t port = get_port(skb, flags[index]);
if (port == INVALID_PORT)
return -EINVAL;
return __addport(set, port, hash_port);
}
static inline int
__delport(struct ip_set *set, ip_set_ip_t port, ip_set_ip_t *hash_port)
{
struct ip_set_portmap *map = set->data;
if (port < map->first_port || port > map->last_port)
return -ERANGE;
if (!test_and_clear_bit(port - map->first_port, map->members))
return -EEXIST;
*hash_port = port;
DP("port %u", port);
return 0;
}
static int
delport(struct ip_set *set, const void *data, size_t size,
ip_set_ip_t *hash_port)
{
const struct ip_set_req_portmap *req = data;
if (size != sizeof(struct ip_set_req_portmap)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_portmap),
size);
return -EINVAL;
}
return __delport(set, req->port, hash_port);
}
static int
delport_kernel(struct ip_set *set,
const struct sk_buff *skb,
ip_set_ip_t *hash_port,
const u_int32_t *flags,
unsigned char index)
{
ip_set_ip_t port = get_port(skb, flags[index]);
if (port == INVALID_PORT)
return -EINVAL;
return __delport(set, port, hash_port);
}
static int create(struct ip_set *set, const void *data, size_t size)
{
int newbytes;
const struct ip_set_req_portmap_create *req = data;
struct ip_set_portmap *map;
if (size != sizeof(struct ip_set_req_portmap_create)) {
ip_set_printk("data length wrong (want %zu, have %zu)",
sizeof(struct ip_set_req_portmap_create),
size);
return -EINVAL;
}
DP("from %u to %u", req->from, req->to);
if (req->from > req->to) {
DP("bad port range");
return -ENOEXEC;
}
if (req->to - req->from > MAX_RANGE) {
ip_set_printk("range too big (max %d ports)",
MAX_RANGE+1);
return -ENOEXEC;
}
map = kmalloc(sizeof(struct ip_set_portmap), GFP_KERNEL);
if (!map) {
DP("out of memory for %d bytes",
sizeof(struct ip_set_portmap));
return -ENOMEM;
}
map->first_port = req->from;
map->last_port = req->to;
newbytes = bitmap_bytes(req->from, req->to);
map->members = kmalloc(newbytes, GFP_KERNEL);
if (!map->members) {
DP("out of memory for %d bytes", newbytes);
kfree(map);
return -ENOMEM;
}
memset(map->members, 0, newbytes);
set->data = map;
return 0;
}
static void destroy(struct ip_set *set)
{
struct ip_set_portmap *map = set->data;
kfree(map->members);
kfree(map);
set->data = NULL;
}
static void flush(struct ip_set *set)
{
struct ip_set_portmap *map = set->data;
memset(map->members, 0, bitmap_bytes(map->first_port, map->last_port));
}
static void list_header(const struct ip_set *set, void *data)
{
const struct ip_set_portmap *map = set->data;
struct ip_set_req_portmap_create *header = data;
DP("list_header %u %u", map->first_port, map->last_port);
header->from = map->first_port;
header->to = map->last_port;
}
static int list_members_size(const struct ip_set *set)
{
const struct ip_set_portmap *map = set->data;
return bitmap_bytes(map->first_port, map->last_port);
}
static void list_members(const struct ip_set *set, void *data)
{
const struct ip_set_portmap *map = set->data;
int bytes = bitmap_bytes(map->first_port, map->last_port);
memcpy(data, map->members, bytes);
}
static struct ip_set_type ip_set_portmap = {
.typename = SETTYPE_NAME,
.features = IPSET_TYPE_PORT | IPSET_DATA_SINGLE,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create = &create,
.destroy = &destroy,
.flush = &flush,
.reqsize = sizeof(struct ip_set_req_portmap),
.addip = &addport,
.addip_kernel = &addport_kernel,
.delip = &delport,
.delip_kernel = &delport_kernel,
.testip = &testport,
.testip_kernel = &testport_kernel,
.header_size = sizeof(struct ip_set_req_portmap_create),
.list_header = &list_header,
.list_members_size = &list_members_size,
.list_members = &list_members,
.me = THIS_MODULE,
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("portmap type of IP sets");
static int __init ip_set_portmap_init(void)
{
return ip_set_register_set_type(&ip_set_portmap);
}
static void __exit ip_set_portmap_fini(void)
{
/* FIXME: possible race with ip_set_create() */
ip_set_unregister_set_type(&ip_set_portmap);
}
module_init(ip_set_portmap_init);
module_exit(ip_set_portmap_fini);

View File

@@ -0,0 +1,25 @@
#ifndef __IP_SET_PORTMAP_H
#define __IP_SET_PORTMAP_H
#include "ip_set.h"
#define SETTYPE_NAME "portmap"
#define MAX_RANGE 0x0000FFFF
#define INVALID_PORT (MAX_RANGE + 1)
struct ip_set_portmap {
void *members; /* the portmap proper */
ip_set_ip_t first_port; /* host byte order, included in range */
ip_set_ip_t last_port; /* host byte order, included in range */
};
struct ip_set_req_portmap_create {
ip_set_ip_t from;
ip_set_ip_t to;
};
struct ip_set_req_portmap {
ip_set_ip_t port;
};
#endif /* __IP_SET_PORTMAP_H */

470
extensions/ipset/ipset.8 Normal file
View File

@@ -0,0 +1,470 @@
.TH IPSET 8 "Feb 05, 2004" "" ""
.\"
.\" Man page written by Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
.\"
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program; if not, write to the Free Software
.\" Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
.\"
.\"
.SH NAME
ipset \- administration tool for IP sets
.SH SYNOPSIS
.BR "ipset -N " "set type-specification [options]"
.br
.BR "ipset -[XFLSHh] " "[set] [options]"
.br
.BR "ipset -[EW] " "from-set to-set"
.br
.BR "ipset -[ADU] " "set entry"
.br
.BR "ipset -B " "set entry -b binding"
.br
.BR "ipset -T " "set entry [-b binding]"
.br
.BR "ipset -R "
.SH DESCRIPTION
.B ipset
is used to set up, maintain and inspect so called IP sets in the Linux
kernel. Depending on the type, an IP set may store IP addresses, (TCP/UDP)
port numbers or additional informations besides IP addresses: the word IP
means a general term here. See the set type definitions below.
.P
Any entry in a set can be bound to another set, which forms a relationship
between a set element and the set it is bound to. In order to define a
binding it is not required that the entry be already added to the set.
The sets may have a default binding, which is valid for every set element
for which there is no binding defined at all.
.P
IP set bindings pointing to sets and iptables matches and targets
referring to sets creates references, which protects the given sets in
the kernel. A set cannot be removed (destroyed) while there is a single
reference pointing to it.
.SH OPTIONS
The options that are recognized by
.B ipset
can be divided into several different groups.
.SS COMMANDS
These options specify the specific action to perform. Only one of them
can be specified on the command line unless otherwise specified
below. For all the long versions of the command and option names, you
need to use only enough letters to ensure that
.B ipset
can differentiate it from all other options.
.TP
.BI "-N, --create " "\fIsetname\fP type type-specific-options"
Create a set identified with setname and specified type.
Type-specific options must be supplied.
.TP
.BI "-X, --destroy " "[\fIsetname\fP]"
Destroy the specified set, or all sets if none or the keyword
.B
:all:
is specified.
Before destroying the set, all bindings belonging to the
set elements and the default binding of the set are removed.
If the set has got references, nothing is done.
.TP
.BI "-F, --flush " "[\fIsetname\fP]"
Delete all entries from the specified set, or flush
all sets if none or the keyword
.B
:all:
is given. Bindings are not affected by the flush operation.
.TP
.BI "-E, --rename " "\fIfrom-setname\fP \fIto-setname\fP"
Rename a set. Set identified by to-setname must not exist.
.TP
.BI "-W, --swap " "\fIfrom-setname\fP \fIto-setname\fP"
Swap two sets as they referenced in the Linux kernel.
.B
iptables
rules or
.B
ipset
bindings pointing to the content of from-setname will point to
the content of to-setname and vice versa. Both sets must exist.
.TP
.BI "-L, --list " "[\fIsetname\fP]"
List the entries and bindings for the specified set, or for
all sets if none or the keyword
.B
:all:
is given. The
.B "-n, --numeric"
option can be used to suppress name lookups and generate numeric
output. When the
.B "-s, --sorted"
option is given, the entries are listed sorted (if the given set
type supports the operation).
.TP
.BI "-S, --save " "[\fIsetname\fP]"
Save the given set, or all sets if none or the keyword
.B
:all:
is specified to stdout in a format that --restore can read.
.TP
.BI "-R, --restore "
Restore a saved session generated by --save. The saved session
can be fed from stdin.
When generating a session file please note that the supported commands
(create set, add element, bind) must appear in a strict order: first create
the set, then add all elements. Then create the next set, add all its elements
and so on. Finally you can list all binding commands. Also, it is a restore
operation, so the sets being restored must not exist.
.TP
.BI "-A, --add " "\fIsetname\fP \fIIP\fP"
Add an IP to a set.
.TP
.BI "-D, --del " "\fIsetname\fP \fIIP\fP"
Delete an IP from a set.
.TP
.BI "-T, --test " "\fIsetname\fP \fIIP
Test wether an IP is in a set or not. Exit status number is zero
if the tested IP is in the set and nonzero if it is missing from
the set.
.TP
.BI "-T, --test " "\fIsetname\fP \fIIP\fP \fI--binding\fP \fIto-setname\fP"
Test wether the IP belonging to the set points to the specified binding.
Exit status number is zero if the binding points to the specified set,
otherwise it is nonzero. The keyword
.B
:default:
can be used to test the default binding of the set.
.TP
.BI "-B, --bind " "\fIsetname\fP \fIIP\fP \fI--binding\fP \fIto-setname\fP"
Bind the IP in setname to to-setname.
.TP
.BI "-U, --unbind " "\fIsetname\fP \fIIP\fP"
Delete the binding belonging to IP in set setname.
.TP
.BI "-H, --help " "[settype]"
Print help and settype specific help if settype specified.
.P
At the
.B
-B, -U
and
.B
-T
commands you can use the token
.B
:default:
to bind, unbind or test the default binding of a set instead
of an IP. At the
.B
-U
command you can use the token
.B
:all:
to destroy the bindings of all elements of a set.
.SS "OTHER OPTIONS"
The following additional options can be specified:
.TP
.B "-b, --binding setname"
The option specifies the value of the binding for the
.B "-B"
binding command, for which it is a mandatory option.
You can use it in the
.B "-T"
test command as well to test bindings.
.TP
.B "-s, --sorted"
Sorted output. When listing sets, entries are listed sorted.
.TP
.B "-n, --numeric"
Numeric output. When listing sets, bindings, IP addresses and
port numbers will be printed in numeric format. By default the
program will try to display them as host names, network names
or services (whenever applicable), which can trigger
.B
slow
DNS
lookups.
.TP
.B "-q, --quiet"
Suppress any output to stdout and stderr. ipset will still return
possible errors.
.SH SET TYPES
ipset supports the following set types:
.SS ipmap
The ipmap set type uses a memory range, where each bit represents
one IP address. An ipmap set can store up to 65536 (B-class network)
IP addresses. The ipmap set type is very fast and memory cheap, great
for use when one want to match certain IPs in a range. Using the
.B "--netmask"
option with a CIDR netmask value between 0-32 when creating an ipmap
set, you will be able to store and match network addresses: i.e an
IP address will be in the set if the value resulted by masking the address
with the specified netmask can be found in the set.
.P
Options to use when creating an ipmap set:
.TP
.BR "--from " from-IP
.TP
.BR "--to " to-IP
Create an ipmap set from the specified range.
.TP
.BR "--network " IP/mask
Create an ipmap set from the specified network.
.TP
.BR "--netmask " CIDR-netmask
When the optional
.B "--netmask"
parameter specified, network addresses will be
stored in the set instead of IP addresses, and the from-IP parameter
must be a network address.
.SS macipmap
The macipmap set type uses a memory range, where each 8 bytes
represents one IP and a MAC addresses. A macipmap set type can store
up to 65536 (B-class network) IP addresses with MAC.
When adding an entry to a macipmap set, you must specify the entry as
.I IP:MAC.
When deleting or testing macipmap entries, the
.I :MAC
part is not mandatory. (The old "%" separation token instead of ":", i.e
IP%MAC is accepted as well.)
.P
Options to use when creating an macipmap set:
.TP
.BR "--from " from-IP
.TP
.BR "--to " to-IP
Create a macipmap set from the specified range.
.TP
.BR "--network " IP/mask
Create a macipmap set from the specified network.
.TP
.BR "--matchunset"
When the optional
.B "--matchunset"
parameter specified, IP addresses which could be stored
in the set but not set yet, will always match.
.P
Please note, the
.I
set
and
.I
SET
netfilter kernel modules
.B
always
use the source MAC address from the packet to match, add or delete
entries from a macipmap type of set.
.SS portmap
The portmap set type uses a memory range, where each bit represents
one port. A portmap set type can store up to 65536 ports.
The portmap set type is very fast and memory cheap.
.P
Options to use when creating an portmap set:
.TP
.BR "--from " from-port
.TP
.BR "--to " to-port
Create a portmap set from the specified range.
.SS iphash
The iphash set type uses a hash to store IP addresses.
In order to avoid clashes in the hash double-hashing, and as a last
resort, dynamic growing of the hash performed. The iphash set type is
great to store random addresses. By supplyig the
.B "--netmask"
option with a CIDR netmask value between 0-32 at creating the set,
you will be able to store and match network addresses instead: i.e
an IP address will be in the set if the value of the address
masked with the specified netmask can be found in the set.
.P
Options to use when creating an iphash set:
.TP
.BR "--hashsize " hashsize
The initial hash size (default 1024)
.TP
.BR "--probes " probes
How many times try to resolve clashing at adding an IP to the hash
by double-hashing (default 8).
.TP
.BR "--resize " percent
Increase the hash size by this many percent (default 50) when adding
an IP to the hash could not be performed after
.B
probes
number of double-hashing.
.TP
.BR "--netmask " CIDR-netmask
When the optional
.B "--netmask"
parameter specified, network addresses will be
stored in the set instead of IP addresses.
.P
The iphash type of sets can store up to 65536 entries. If a set is full,
no new entries can be added to it.
.P
Sets created by zero valued resize parameter won't be resized at all.
The lookup time in an iphash type of set approximately linearly grows with
the value of the
.B
probes
parameter. At the same time higher
.B
probes
values result a better utilized hash while smaller values
produce a larger, sparse hash.
.SS nethash
The nethash set type uses a hash to store different size of
network addresses. The
.I
IP
"address" used in the ipset commands must be in the form
.I
IP-address/cidr-size
where the CIDR block size must be in the inclusive range of 1-31.
In order to avoid clashes in the hash
double-hashing, and as a last resort, dynamic growing of the hash performed.
.P
Options to use when creating an nethash set:
.TP
.BR "--hashsize " hashsize
The initial hash size (default 1024)
.TP
.BR "--probes " probes
How many times try to resolve clashing at adding an IP to the hash
by double-hashing (default 4).
.TP
.BR "--resize " percent
Increase the hash size by this many percent (default 50) when adding
an IP to the hash could not be performed after
.P
The nethash type of sets can store up to 65536 entries. If a set is full,
no new entries can be added to it.
.P
An IP address will be in a nethash type of set if it is in any of the
netblocks added to the set and the matching always start from the smallest
size of netblock (most specific netmask) to the biggest ones (least
specific netmasks). When adding/deleting IP addresses
to a nethash set by the
.I
SET
netfilter kernel module, it will be added/deleted by the smallest
netblock size which can be found in the set.
.P
The lookup time in a nethash type of set is approximately linearly
grows with the times of the
.B
probes
parameter and the number of different mask parameters in the hash.
Otherwise the same speed and memory efficiency comments applies here
as at the iphash type.
.SS ipporthash
The ipporthash set type uses a hash to store IP address and port pairs.
In order to avoid clashes in the hash double-hashing, and as a last
resort, dynamic growing of the hash performed. An ipporthash set can
store up to 65536 (B-class network) IP addresses with all possible port
values. When adding, deleting and testing values in an ipporthash type of
set, the entries must be specified as
.B
"IP:port".
(Old "IP%port" format accepted as well.)
.P
The ipporthash types of sets evaluates two src/dst parameters of the
.I
set
match and
.I
SET
target.
.P
Options to use when creating an ipporthash set:
.TP
.BR "--from " from-IP
.TP
.BR "--to " to-IP
Create an ipporthash set from the specified range.
.TP
.BR "--network " IP/mask
Create an ipporthash set from the specified network.
.TP
.BR "--hashsize " hashsize
The initial hash size (default 1024)
.TP
.BR "--probes " probes
How many times try to resolve clashing at adding an IP to the hash
by double-hashing (default 8).
.TP
.BR "--resize " percent
Increase the hash size by this many percent (default 50) when adding
an IP to the hash could not be performed after
.B
probes
number of double-hashing.
.P
The same resizing, speed and memory efficiency comments applies here
as at the iphash type.
.SS iptree
The iptree set type uses a tree to store IP addresses, optionally
with timeout values.
.P
Options to use when creating an iptree set:
.TP
.BR "--timeout " value
The timeout value for the entries in seconds (default 0)
.P
If a set was created with a nonzero valued
.B "--timeout"
parameter then one may add IP addresses to the set with a specific
timeout value using the syntax
.I IP:timeout-value.
Similarly to the hash types, the iptree type of sets can store up to 65536
entries.
.SS iptreemap
The iptreemap set type uses a tree to store IP addresses or networks,
where the last octet of an IP address are stored in a bitmap.
As input entry, you can add IP addresses, CIDR blocks or network ranges
to the set. Network ranges can be specified in the format
.I IP1:IP2
.P
Options to use when creating an iptreemap set:
.TP
.BR "--gc " value
How often the garbage collection should be called, in seconds (default 300)
.SH GENERAL RESTRICTIONS
Setnames starting with colon (:) cannot be defined. Zero valued set
entries cannot be used with hash type of sets.
.SH COMMENTS
If you want to store same size subnets from a given network
(say /24 blocks from a /8 network), use the ipmap set type.
If you want to store random same size networks (say random /24 blocks),
use the iphash set type. If you have got random size of netblocks,
use nethash.
.SH DIAGNOSTICS
Various error messages are printed to standard error. The exit code
is 0 for correct functioning. Errors which appear to be caused by
invalid or abused command line parameters cause an exit code of 2, and
other errors cause an exit code of 1.
.SH BUGS
Bugs? No, just funny features. :-)
OK, just kidding...
.SH SEE ALSO
.BR iptables (8),
.SH AUTHORS
Jozsef Kadlecsik wrote ipset, which is based on ippool by
Joakim Axelsson, Patrick Schaaf and Martin Josefsson.
.P
Sven Wegener wrote the iptreemap type.
.SH LAST REMARK
.BR "I stand on the shoulder of giants."
.\" .. and did I mention that we are incredibly cool people?
.\" .. sexy, too ..
.\" .. witty, charming, powerful ..
.\" .. and most of all, modest ..

2309
extensions/ipset/ipset.c Normal file

File diff suppressed because it is too large Load Diff

191
extensions/ipset/ipset.h Normal file
View File

@@ -0,0 +1,191 @@
#ifndef __IPSET_H
#define __IPSET_H
/* Copyright 2000-2004 Joakim Axelsson (gozem@linux.nu)
* Patrick Schaaf (bof@bof.de)
* Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <getopt.h>
#include <sys/types.h>
#include <netdb.h>
#include "ip_set.h"
#define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
#define LIST_TRIES 5
#ifdef IPSET_DEBUG
extern int option_debug;
#define DP(format, args...) if (option_debug) \
do { \
fprintf(stderr, "%s: %s (DBG): ", __FILE__, __FUNCTION__);\
fprintf(stderr, format "\n" , ## args); \
} while (0)
#else
#define DP(format, args...)
#endif
/* Commands */
enum set_commands {
CMD_NONE,
CMD_CREATE, /* -N */
CMD_DESTROY, /* -X */
CMD_FLUSH, /* -F */
CMD_RENAME, /* -E */
CMD_SWAP, /* -W */
CMD_LIST, /* -L */
CMD_SAVE, /* -S */
CMD_RESTORE, /* -R */
CMD_ADD, /* -A */
CMD_DEL, /* -D */
CMD_TEST, /* -T */
CMD_BIND, /* -B */
CMD_UNBIND, /* -U */
CMD_HELP, /* -H */
CMD_VERSION, /* -V */
NUMBER_OF_CMD = CMD_VERSION,
/* Internal commands */
CMD_MAX_SETS,
CMD_LIST_SIZE,
CMD_SAVE_SIZE,
CMD_ADT_GET,
};
enum exittype {
OTHER_PROBLEM = 1,
PARAMETER_PROBLEM,
VERSION_PROBLEM
};
/* The view of an ipset in userspace */
struct set {
char name[IP_SET_MAXNAMELEN]; /* Name of the set */
ip_set_id_t id; /* Unique set id */
ip_set_id_t index; /* Array index */
unsigned ref; /* References in kernel */
struct settype *settype; /* Pointer to set type functions */
};
struct settype {
struct settype *next;
char typename[IP_SET_MAXNAMELEN];
int protocol_version;
/*
* Create set
*/
/* Size of create data. Will be sent to kernel */
size_t create_size;
/* Initialize the create. */
void (*create_init) (void *data);
/* Function which parses command options; returns true if it ate an option */
int (*create_parse) (int c, char *argv[], void *data,
unsigned *flags);
/* Final check; exit if not ok. */
void (*create_final) (void *data, unsigned int flags);
/* Pointer to list of extra command-line options for create */
const struct option *create_opts;
/*
* Add/del/test IP
*/
/* Size of data. Will be sent to kernel */
size_t adt_size;
/* Function which parses command options */
ip_set_ip_t (*adt_parser) (unsigned cmd, const char *optarg, void *data);
/*
* Printing
*/
/* Size of header. */
size_t header_size;
/* Initialize the type-header */
void (*initheader) (struct set *set, const void *data);
/* Pretty print the type-header */
void (*printheader) (struct set *set, unsigned options);
/* Pretty print all IPs */
void (*printips) (struct set *set, void *data, size_t len, unsigned options);
/* Pretty print all IPs sorted */
void (*printips_sorted) (struct set *set, void *data, size_t len, unsigned options);
/* Print save arguments for creating the set */
void (*saveheader) (struct set *set, unsigned options);
/* Print save for all IPs */
void (*saveips) (struct set *set, void *data, size_t len, unsigned options);
/* Conver a single IP (binding) to string */
char * (*bindip_tostring)(struct set *set, ip_set_ip_t ip, unsigned options);
/* Parse an IP at restoring bindings. FIXME */
void (*bindip_parse) (const char *str, ip_set_ip_t * ip);
/* Print usage */
void (*usage) (void);
/* Internal data */
void *header;
void *data;
unsigned int option_offset;
unsigned int flags;
};
extern void settype_register(struct settype *settype);
/* extern void unregister_settype(set_type_t *set_type); */
extern void exit_error(enum exittype status, const char *msg, ...);
extern char *binding_ip_tostring(struct set *set,
ip_set_ip_t ip, unsigned options);
extern char *ip_tostring(ip_set_ip_t ip, unsigned options);
extern char *ip_tostring_numeric(ip_set_ip_t ip);
extern void parse_ip(const char *str, ip_set_ip_t * ip);
extern void parse_mask(const char *str, ip_set_ip_t * mask);
extern void parse_ipandmask(const char *str, ip_set_ip_t * ip,
ip_set_ip_t * mask);
extern char *port_tostring(ip_set_ip_t port, unsigned options);
extern void parse_port(const char *str, ip_set_ip_t * port);
extern int string_to_number(const char *str, unsigned int min, unsigned int max,
ip_set_ip_t *port);
extern void *ipset_malloc(size_t size);
extern char *ipset_strdup(const char *);
extern void ipset_free(void **data);
#define BITSPERBYTE (8*sizeof(char))
#define ID2BYTE(id) ((id)/BITSPERBYTE)
#define ID2MASK(id) (1 << ((id)%BITSPERBYTE))
#define test_bit(id, heap) ((((char *)(heap))[ID2BYTE(id)] & ID2MASK(id)) != 0)
#endif /* __IPSET_H */

View File

@@ -0,0 +1,299 @@
/* Copyright 2004 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <asm/types.h>
#include "ip_set_iphash.h"
#include "ip_set_jhash.h"
#include "ipset.h"
#define BUFLEN 30;
#define OPT_CREATE_HASHSIZE 0x01U
#define OPT_CREATE_PROBES 0x02U
#define OPT_CREATE_RESIZE 0x04U
#define OPT_CREATE_NETMASK 0x08U
/* Initialize the create. */
static void create_init(void *data)
{
struct ip_set_req_iphash_create *mydata =
(struct ip_set_req_iphash_create *) data;
DP("create INIT");
/* Default create parameters */
mydata->hashsize = 1024;
mydata->probes = 8;
mydata->resize = 50;
mydata->netmask = 0xFFFFFFFF;
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_iphash_create *mydata =
(struct ip_set_req_iphash_create *) data;
unsigned int bits;
ip_set_ip_t value;
DP("create_parse");
switch (c) {
case '1':
if (string_to_number(optarg, 1, UINT_MAX - 1, &mydata->hashsize))
exit_error(PARAMETER_PROBLEM, "Invalid hashsize `%s' specified", optarg);
*flags |= OPT_CREATE_HASHSIZE;
DP("--hashsize %u", mydata->hashsize);
break;
case '2':
if (string_to_number(optarg, 1, 65535, &value))
exit_error(PARAMETER_PROBLEM, "Invalid probes `%s' specified", optarg);
mydata->probes = value;
*flags |= OPT_CREATE_PROBES;
DP("--probes %u", mydata->probes);
break;
case '3':
if (string_to_number(optarg, 0, 65535, &value))
exit_error(PARAMETER_PROBLEM, "Invalid resize `%s' specified", optarg);
mydata->resize = value;
*flags |= OPT_CREATE_RESIZE;
DP("--resize %u", mydata->resize);
break;
case '4':
if (string_to_number(optarg, 0, 32, &bits))
exit_error(PARAMETER_PROBLEM,
"Invalid netmask `%s' specified", optarg);
if (bits != 0)
mydata->netmask = 0xFFFFFFFF << (32 - bits);
*flags |= OPT_CREATE_NETMASK;
DP("--netmask %x", mydata->netmask);
break;
default:
return 0;
}
return 1;
}
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
#ifdef IPSET_DEBUG
struct ip_set_req_iphash_create *mydata =
(struct ip_set_req_iphash_create *) data;
DP("hashsize %u probes %u resize %u",
mydata->hashsize, mydata->probes, mydata->resize);
#endif
}
/* Create commandline options */
static const struct option create_opts[] = {
{"hashsize", 1, 0, '1'},
{"probes", 1, 0, '2'},
{"resize", 1, 0, '3'},
{"netmask", 1, 0, '4'},
{NULL},
};
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_iphash *mydata =
(struct ip_set_req_iphash *) data;
parse_ip(arg, &mydata->ip);
if (!mydata->ip)
exit_error(PARAMETER_PROBLEM,
"Zero valued IP address `%s' specified", arg);
return mydata->ip;
};
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_iphash_create *header =
(struct ip_set_req_iphash_create *) data;
struct ip_set_iphash *map =
(struct ip_set_iphash *) set->settype->header;
memset(map, 0, sizeof(struct ip_set_iphash));
map->hashsize = header->hashsize;
map->probes = header->probes;
map->resize = header->resize;
map->netmask = header->netmask;
}
static unsigned int
mask_to_bits(ip_set_ip_t mask)
{
unsigned int bits = 32;
ip_set_ip_t maskaddr;
if (mask == 0xFFFFFFFF)
return bits;
maskaddr = 0xFFFFFFFE;
while (--bits >= 0 && maskaddr != mask)
maskaddr <<= 1;
return bits;
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_iphash *mysetdata =
(struct ip_set_iphash *) set->settype->header;
printf(" hashsize: %u", mysetdata->hashsize);
printf(" probes: %u", mysetdata->probes);
printf(" resize: %u", mysetdata->resize);
if (mysetdata->netmask == 0xFFFFFFFF)
printf("\n");
else
printf(" netmask: %d\n", mask_to_bits(mysetdata->netmask));
}
static void printips(struct set *set, void *data, size_t len,
unsigned int options)
{
size_t offset = 0;
ip_set_ip_t *ip;
while (offset < len) {
ip = data + offset;
if (*ip)
printf("%s\n", ip_tostring(*ip, options));
offset += sizeof(ip_set_ip_t);
}
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_iphash *mysetdata =
(struct ip_set_iphash *) set->settype->header;
printf("-N %s %s --hashsize %u --probes %u --resize %u",
set->name, set->settype->typename,
mysetdata->hashsize, mysetdata->probes, mysetdata->resize);
if (mysetdata->netmask == 0xFFFFFFFF)
printf("\n");
else
printf(" --netmask %d\n", mask_to_bits(mysetdata->netmask));
}
/* Print save for an IP */
static void saveips(struct set *set, void *data, size_t len,
unsigned int options)
{
size_t offset = 0;
ip_set_ip_t *ip;
while (offset < len) {
ip = data + offset;
if (*ip)
printf("-A %s %s\n", set->name,
ip_tostring(*ip, options));
offset += sizeof(ip_set_ip_t);
}
}
static void usage(void)
{
printf
("-N set iphash [--hashsize hashsize] [--probes probes ]\n"
" [--resize resize] [--netmask CIDR-netmask]\n"
"-A set IP\n"
"-D set IP\n"
"-T set IP\n");
}
static struct settype settype_iphash = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_iphash_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_iphash),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_iphash),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips, /* We only have the unsorted version */
.printips_sorted = &printips,
.saveheader = &saveheader,
.saveips = &saveips,
/* Bindings */
.bindip_tostring = &binding_ip_tostring,
.bindip_parse = &parse_ip,
.usage = &usage,
};
static __attribute__((constructor)) void iphash_init(void)
{
settype_register(&settype_iphash);
}

View File

@@ -0,0 +1,362 @@
/* Copyright 2000-2004 Joakim Axelsson (gozem@linux.nu)
* Patrick Schaaf (bof@bof.de)
* Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* #include <asm/bitops.h> */
#include "ip_set_ipmap.h"
#include "ipset.h"
#define BUFLEN 30;
#define OPT_CREATE_FROM 0x01U
#define OPT_CREATE_TO 0x02U
#define OPT_CREATE_NETWORK 0x04U
#define OPT_CREATE_NETMASK 0x08U
#define OPT_ADDDEL_IP 0x01U
/* Initialize the create. */
static void create_init(void *data)
{
struct ip_set_req_ipmap_create *mydata =
(struct ip_set_req_ipmap_create *) data;
DP("create INIT");
mydata->netmask = 0xFFFFFFFF;
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_ipmap_create *mydata =
(struct ip_set_req_ipmap_create *) data;
unsigned int bits;
DP("create_parse");
switch (c) {
case '1':
parse_ip(optarg, &mydata->from);
*flags |= OPT_CREATE_FROM;
DP("--from %x (%s)", mydata->from,
ip_tostring_numeric(mydata->from));
break;
case '2':
parse_ip(optarg, &mydata->to);
*flags |= OPT_CREATE_TO;
DP("--to %x (%s)", mydata->to,
ip_tostring_numeric(mydata->to));
break;
case '3':
parse_ipandmask(optarg, &mydata->from, &mydata->to);
/* Make to the last of from + mask */
if (mydata->to)
mydata->to = mydata->from | ~(mydata->to);
else {
mydata->from = 0x00000000;
mydata->to = 0xFFFFFFFF;
}
*flags |= OPT_CREATE_NETWORK;
DP("--network from %x (%s)",
mydata->from, ip_tostring_numeric(mydata->from));
DP("--network to %x (%s)",
mydata->to, ip_tostring_numeric(mydata->to));
break;
case '4':
if (string_to_number(optarg, 0, 32, &bits))
exit_error(PARAMETER_PROBLEM,
"Invalid netmask `%s' specified", optarg);
if (bits != 0)
mydata->netmask = 0xFFFFFFFF << (32 - bits);
*flags |= OPT_CREATE_NETMASK;
DP("--netmask %x", mydata->netmask);
break;
default:
return 0;
}
return 1;
}
#define ERRSTRLEN 256
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
struct ip_set_req_ipmap_create *mydata =
(struct ip_set_req_ipmap_create *) data;
ip_set_ip_t range;
char errstr[ERRSTRLEN];
if (flags == 0)
exit_error(PARAMETER_PROBLEM,
"Need to specify --from and --to, or --network\n");
if (flags & OPT_CREATE_NETWORK) {
/* --network */
if ((flags & OPT_CREATE_FROM) || (flags & OPT_CREATE_TO))
exit_error(PARAMETER_PROBLEM,
"Can't specify --from or --to with --network\n");
} else {
/* --from --to */
if ((flags & OPT_CREATE_FROM) == 0
|| (flags & OPT_CREATE_TO) == 0)
exit_error(PARAMETER_PROBLEM,
"Need to specify both --from and --to\n");
}
DP("from : %x to: %x diff: %x",
mydata->from, mydata->to,
mydata->to - mydata->from);
if (mydata->from > mydata->to)
exit_error(PARAMETER_PROBLEM,
"From can't be lower than to.\n");
if (flags & OPT_CREATE_NETMASK) {
unsigned int mask_bits, netmask_bits;
ip_set_ip_t mask;
if ((mydata->from & mydata->netmask) != mydata->from)
exit_error(PARAMETER_PROBLEM,
"%s is not a network address according to netmask %d\n",
ip_tostring_numeric(mydata->from),
mask_to_bits(mydata->netmask));
mask = range_to_mask(mydata->from, mydata->to, &mask_bits);
if (!mask
&& (mydata->from || mydata->to != 0xFFFFFFFF)) {
strncpy(errstr, ip_tostring_numeric(mydata->from),
ERRSTRLEN-2);
errstr[ERRSTRLEN-1] = '\0';
exit_error(PARAMETER_PROBLEM,
"%s-%s is not a full network (%x)\n",
errstr,
ip_tostring_numeric(mydata->to), mask);
}
netmask_bits = mask_to_bits(mydata->netmask);
if (netmask_bits <= mask_bits) {
strncpy(errstr, ip_tostring_numeric(mydata->from),
ERRSTRLEN-2);
errstr[ERRSTRLEN-1] = '\0';
exit_error(PARAMETER_PROBLEM,
"%d netmask specifies larger or equal netblock than %s-%s (%d)\n",
netmask_bits,
errstr,
ip_tostring_numeric(mydata->to),
mask_bits);
}
range = (1<<(netmask_bits - mask_bits)) - 1;
} else {
range = mydata->to - mydata->from;
}
if (range > MAX_RANGE)
exit_error(PARAMETER_PROBLEM,
"Range too large. Max is %d IPs in range\n",
MAX_RANGE+1);
}
/* Create commandline options */
static const struct option create_opts[] = {
{"from", 1, 0, '1'},
{"to", 1, 0, '2'},
{"network", 1, 0, '3'},
{"netmask", 1, 0, '4'},
{NULL},
};
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_ipmap *mydata =
(struct ip_set_req_ipmap *) data;
DP("ipmap: %p %p", arg, data);
parse_ip(arg, &mydata->ip);
DP("%s", ip_tostring_numeric(mydata->ip));
return 1;
}
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_ipmap_create *header =
(struct ip_set_req_ipmap_create *) data;
struct ip_set_ipmap *map =
(struct ip_set_ipmap *) set->settype->header;
memset(map, 0, sizeof(struct ip_set_ipmap));
map->first_ip = header->from;
map->last_ip = header->to;
map->netmask = header->netmask;
if (map->netmask == 0xFFFFFFFF) {
map->hosts = 1;
map->sizeid = map->last_ip - map->first_ip + 1;
} else {
unsigned int mask_bits, netmask_bits;
ip_set_ip_t mask;
mask = range_to_mask(header->from, header->to, &mask_bits);
netmask_bits = mask_to_bits(header->netmask);
DP("bits: %i %i", mask_bits, netmask_bits);
map->hosts = 2 << (32 - netmask_bits - 1);
map->sizeid = 2 << (netmask_bits - mask_bits - 1);
}
DP("%i %i", map->hosts, map->sizeid );
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_ipmap *mysetdata =
(struct ip_set_ipmap *) set->settype->header;
printf(" from: %s", ip_tostring(mysetdata->first_ip, options));
printf(" to: %s", ip_tostring(mysetdata->last_ip, options));
if (mysetdata->netmask == 0xFFFFFFFF)
printf("\n");
else
printf(" netmask: %d\n", mask_to_bits(mysetdata->netmask));
}
static void printips_sorted(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_ipmap *mysetdata =
(struct ip_set_ipmap *) set->settype->header;
ip_set_ip_t id;
for (id = 0; id < mysetdata->sizeid; id++)
if (test_bit(id, data))
printf("%s\n",
ip_tostring(mysetdata->first_ip
+ id * mysetdata->hosts,
options));
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_ipmap *mysetdata =
(struct ip_set_ipmap *) set->settype->header;
printf("-N %s %s --from %s",
set->name, set->settype->typename,
ip_tostring(mysetdata->first_ip, options));
printf(" --to %s",
ip_tostring(mysetdata->last_ip, options));
if (mysetdata->netmask == 0xFFFFFFFF)
printf("\n");
else
printf(" --netmask %d\n",
mask_to_bits(mysetdata->netmask));
}
static void saveips(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_ipmap *mysetdata =
(struct ip_set_ipmap *) set->settype->header;
ip_set_ip_t id;
DP("%s", set->name);
for (id = 0; id < mysetdata->sizeid; id++)
if (test_bit(id, data))
printf("-A %s %s\n",
set->name,
ip_tostring(mysetdata->first_ip
+ id * mysetdata->hosts,
options));
}
static void usage(void)
{
printf
("-N set ipmap --from IP --to IP [--netmask CIDR-netmask]\n"
"-N set ipmap --network IP/mask [--netmask CIDR-netmask]\n"
"-A set IP\n"
"-D set IP\n"
"-T set IP\n");
}
static struct settype settype_ipmap = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_ipmap_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_ipmap),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_ipmap),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips_sorted, /* We only have sorted version */
.printips_sorted = &printips_sorted,
.saveheader = &saveheader,
.saveips = &saveips,
/* Bindings */
.bindip_tostring = &binding_ip_tostring,
.bindip_parse = &parse_ip,
.usage = &usage,
};
static __attribute__((constructor)) void ipmap_init(void)
{
settype_register(&settype_ipmap);
}

View File

@@ -0,0 +1,375 @@
/* Copyright 2004 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <asm/types.h>
#include "ip_set_ipporthash.h"
#include "ip_set_jhash.h"
#include "ipset.h"
#define OPT_CREATE_HASHSIZE 0x01U
#define OPT_CREATE_PROBES 0x02U
#define OPT_CREATE_RESIZE 0x04U
#define OPT_CREATE_NETWORK 0x08U
#define OPT_CREATE_FROM 0x10U
#define OPT_CREATE_TO 0x20U
/* Initialize the create. */
static void create_init(void *data)
{
struct ip_set_req_ipporthash_create *mydata =
(struct ip_set_req_ipporthash_create *) data;
DP("create INIT");
/* Default create parameters */
mydata->hashsize = 1024;
mydata->probes = 8;
mydata->resize = 50;
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_ipporthash_create *mydata =
(struct ip_set_req_ipporthash_create *) data;
ip_set_ip_t value;
DP("create_parse");
switch (c) {
case '1':
if (string_to_number(optarg, 1, UINT_MAX - 1, &mydata->hashsize))
exit_error(PARAMETER_PROBLEM, "Invalid hashsize `%s' specified", optarg);
*flags |= OPT_CREATE_HASHSIZE;
DP("--hashsize %u", mydata->hashsize);
break;
case '2':
if (string_to_number(optarg, 1, 65535, &value))
exit_error(PARAMETER_PROBLEM, "Invalid probes `%s' specified", optarg);
mydata->probes = value;
*flags |= OPT_CREATE_PROBES;
DP("--probes %u", mydata->probes);
break;
case '3':
if (string_to_number(optarg, 0, 65535, &value))
exit_error(PARAMETER_PROBLEM, "Invalid resize `%s' specified", optarg);
mydata->resize = value;
*flags |= OPT_CREATE_RESIZE;
DP("--resize %u", mydata->resize);
break;
case '4':
parse_ip(optarg, &mydata->from);
*flags |= OPT_CREATE_FROM;
DP("--from %x (%s)", mydata->from,
ip_tostring_numeric(mydata->from));
break;
case '5':
parse_ip(optarg, &mydata->to);
*flags |= OPT_CREATE_TO;
DP("--to %x (%s)", mydata->to,
ip_tostring_numeric(mydata->to));
break;
case '6':
parse_ipandmask(optarg, &mydata->from, &mydata->to);
/* Make to the last of from + mask */
if (mydata->to)
mydata->to = mydata->from | ~(mydata->to);
else {
mydata->from = 0x00000000;
mydata->to = 0xFFFFFFFF;
}
*flags |= OPT_CREATE_NETWORK;
DP("--network from %x (%s)",
mydata->from, ip_tostring_numeric(mydata->from));
DP("--network to %x (%s)",
mydata->to, ip_tostring_numeric(mydata->to));
break;
default:
return 0;
}
return 1;
}
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
struct ip_set_req_ipporthash_create *mydata =
(struct ip_set_req_ipporthash_create *) data;
#ifdef IPSET_DEBUG
DP("hashsize %u probes %u resize %u",
mydata->hashsize, mydata->probes, mydata->resize);
#endif
if (flags & OPT_CREATE_NETWORK) {
/* --network */
if ((flags & OPT_CREATE_FROM) || (flags & OPT_CREATE_TO))
exit_error(PARAMETER_PROBLEM,
"Can't specify --from or --to with --network\n");
} else if (flags & (OPT_CREATE_FROM | OPT_CREATE_TO)) {
/* --from --to */
if (!(flags & OPT_CREATE_FROM) || !(flags & OPT_CREATE_TO))
exit_error(PARAMETER_PROBLEM,
"Need to specify both --from and --to\n");
} else {
exit_error(PARAMETER_PROBLEM,
"Need to specify --from and --to, or --network\n");
}
DP("from : %x to: %x diff: %x",
mydata->from, mydata->to,
mydata->to - mydata->from);
if (mydata->from > mydata->to)
exit_error(PARAMETER_PROBLEM,
"From can't be higher than to.\n");
if (mydata->to - mydata->from > MAX_RANGE)
exit_error(PARAMETER_PROBLEM,
"Range too large. Max is %d IPs in range\n",
MAX_RANGE+1);
}
/* Create commandline options */
static const struct option create_opts[] = {
{"hashsize", 1, 0, '1'},
{"probes", 1, 0, '2'},
{"resize", 1, 0, '3'},
{"from", 1, 0, '4'},
{"to", 1, 0, '5'},
{"network", 1, 0, '6'},
{NULL},
};
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_ipporthash *mydata =
(struct ip_set_req_ipporthash *) data;
char *saved = ipset_strdup(arg);
char *ptr, *tmp = saved;
DP("ipporthash: %p %p", arg, data);
ptr = strsep(&tmp, ":%");
parse_ip(ptr, &mydata->ip);
if (tmp)
parse_port(tmp, &mydata->port);
else
exit_error(PARAMETER_PROBLEM,
"IP address and port must be specified: ip%%port");
free(saved);
return 1;
};
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_ipporthash_create *header =
(struct ip_set_req_ipporthash_create *) data;
struct ip_set_ipporthash *map =
(struct ip_set_ipporthash *) set->settype->header;
memset(map, 0, sizeof(struct ip_set_ipporthash));
map->hashsize = header->hashsize;
map->probes = header->probes;
map->resize = header->resize;
map->first_ip = header->from;
map->last_ip = header->to;
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_ipporthash *mysetdata =
(struct ip_set_ipporthash *) set->settype->header;
printf(" from: %s", ip_tostring(mysetdata->first_ip, options));
printf(" to: %s", ip_tostring(mysetdata->last_ip, options));
printf(" hashsize: %u", mysetdata->hashsize);
printf(" probes: %u", mysetdata->probes);
printf(" resize: %u\n", mysetdata->resize);
}
static void printips(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_ipporthash *mysetdata =
(struct ip_set_ipporthash *) set->settype->header;
size_t offset = 0;
ip_set_ip_t *ipptr, ip;
uint16_t port;
while (offset < len) {
ipptr = data + offset;
if (*ipptr) {
ip = (*ipptr>>16) + mysetdata->first_ip;
port = (uint16_t) *ipptr;
printf("%s:%s\n",
ip_tostring(ip, options),
port_tostring(port, options));
}
offset += sizeof(ip_set_ip_t);
}
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_ipporthash *mysetdata =
(struct ip_set_ipporthash *) set->settype->header;
printf("-N %s %s --from %s",
set->name, set->settype->typename,
ip_tostring(mysetdata->first_ip, options));
printf(" --to %s",
ip_tostring(mysetdata->last_ip, options));
printf(" --hashsize %u --probes %u --resize %u\n",
mysetdata->hashsize, mysetdata->probes, mysetdata->resize);
}
/* Print save for an IP */
static void saveips(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_ipporthash *mysetdata =
(struct ip_set_ipporthash *) set->settype->header;
size_t offset = 0;
ip_set_ip_t *ipptr, ip;
uint16_t port;
while (offset < len) {
ipptr = data + offset;
if (*ipptr) {
ip = (*ipptr>>16) + mysetdata->first_ip;
port = (uint16_t) *ipptr;
printf("-A %s %s:%s\n", set->name,
ip_tostring(ip, options),
port_tostring(port, options));
}
offset += sizeof(ip_set_ip_t);
}
}
static char buffer[22];
static char * unpack_ipport_tostring(struct set *set, ip_set_ip_t bip, unsigned options)
{
struct ip_set_ipporthash *mysetdata =
(struct ip_set_ipporthash *) set->settype->header;
ip_set_ip_t ip, port;
ip = (bip>>16) + mysetdata->first_ip;
port = (uint16_t) bip;
sprintf(buffer, "%s:%s",
ip_tostring(ip, options), port_tostring(port, options));
return buffer;
}
static void usage(void)
{
printf
("-N set ipporthash --from IP --to IP\n"
" [--hashsize hashsize] [--probes probes ] [--resize resize]\n"
"-N set ipporthash --network IP/mask\n"
" [--hashsize hashsize] [--probes probes ] [--resize resize]\n"
"-A set IP:port\n"
"-D set IP:port\n"
"-T set IP:port\n");
}
static struct settype settype_ipporthash = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_ipporthash_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_ipporthash),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_ipporthash),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips, /* We only have the unsorted version */
.printips_sorted = &printips,
.saveheader = &saveheader,
.saveips = &saveips,
/* Bindings */
.bindip_tostring = &unpack_ipport_tostring,
.bindip_parse = &parse_ip,
.usage = &usage,
};
static __attribute__((constructor)) void ipporthash_init(void)
{
settype_register(&settype_ipporthash);
}

View File

@@ -0,0 +1,226 @@
/* Copyright 2005 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ip_set_iptree.h"
#include "ipset.h"
#define BUFLEN 30;
#define OPT_CREATE_TIMEOUT 0x01U
/* Initialize the create. */
static void create_init(void *data)
{
struct ip_set_req_iptree_create *mydata =
(struct ip_set_req_iptree_create *) data;
DP("create INIT");
mydata->timeout = 0;
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_iptree_create *mydata =
(struct ip_set_req_iptree_create *) data;
DP("create_parse");
switch (c) {
case '1':
string_to_number(optarg, 0, UINT_MAX, &mydata->timeout);
*flags |= OPT_CREATE_TIMEOUT;
DP("--timeout %u", mydata->timeout);
break;
default:
return 0;
}
return 1;
}
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
}
/* Create commandline options */
static const struct option create_opts[] = {
{"timeout", 1, 0, '1'},
{NULL},
};
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_iptree *mydata =
(struct ip_set_req_iptree *) data;
char *saved = ipset_strdup(arg);
char *ptr, *tmp = saved;
DP("iptree: %p %p", arg, data);
ptr = strsep(&tmp, ":%");
parse_ip(ptr, &mydata->ip);
if (tmp)
string_to_number(tmp, 0, UINT_MAX, &mydata->timeout);
else
mydata->timeout = 0;
free(saved);
return 1;
}
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_iptree_create *header =
(struct ip_set_req_iptree_create *) data;
struct ip_set_iptree *map =
(struct ip_set_iptree *) set->settype->header;
map->timeout = header->timeout;
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_iptree *mysetdata =
(struct ip_set_iptree *) set->settype->header;
if (mysetdata->timeout)
printf(" timeout: %u", mysetdata->timeout);
printf("\n");
}
static void printips_sorted(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_iptree *mysetdata =
(struct ip_set_iptree *) set->settype->header;
struct ip_set_req_iptree *req;
size_t offset = 0;
while (len >= offset + sizeof(struct ip_set_req_iptree)) {
req = (struct ip_set_req_iptree *)(data + offset);
if (mysetdata->timeout)
printf("%s:%u\n", ip_tostring(req->ip, options),
req->timeout);
else
printf("%s\n", ip_tostring(req->ip, options));
offset += sizeof(struct ip_set_req_iptree);
}
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_iptree *mysetdata =
(struct ip_set_iptree *) set->settype->header;
if (mysetdata->timeout)
printf("-N %s %s --timeout %u\n",
set->name, set->settype->typename,
mysetdata->timeout);
else
printf("-N %s %s\n",
set->name, set->settype->typename);
}
static void saveips(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_iptree *mysetdata =
(struct ip_set_iptree *) set->settype->header;
struct ip_set_req_iptree *req;
size_t offset = 0;
DP("%s", set->name);
while (len >= offset + sizeof(struct ip_set_req_iptree)) {
req = (struct ip_set_req_iptree *)(data + offset);
if (mysetdata->timeout)
printf("-A %s %s:%u\n",
set->name,
ip_tostring(req->ip, options),
req->timeout);
else
printf("-A %s %s\n",
set->name,
ip_tostring(req->ip, options));
offset += sizeof(struct ip_set_req_iptree);
}
}
static void usage(void)
{
printf
("-N set iptree [--timeout value]\n"
"-A set IP[:timeout]\n"
"-D set IP\n"
"-T set IP\n");
}
static struct settype settype_iptree = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_iptree_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_iptree),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_iptree),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips_sorted, /* We only have sorted version */
.printips_sorted = &printips_sorted,
.saveheader = &saveheader,
.saveips = &saveips,
/* Bindings */
.bindip_tostring = &binding_ip_tostring,
.bindip_parse = &parse_ip,
.usage = &usage,
};
static __attribute__((constructor)) void iptree_init(void)
{
settype_register(&settype_iptree);
}

View File

@@ -0,0 +1,206 @@
/* Copyright 2007 Sven Wegener <sven.wegener@stealer.net>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ip_set_iptreemap.h"
#include "ipset.h"
#define OPT_CREATE_GC 0x1
static void
create_init(void *data)
{
struct ip_set_req_iptreemap_create *mydata = data;
mydata->gc_interval = 0;
}
static int
create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_iptreemap_create *mydata = data;
switch (c) {
case 'g':
string_to_number(optarg, 0, UINT_MAX, &mydata->gc_interval);
*flags |= OPT_CREATE_GC;
break;
default:
return 0;
break;
}
return 1;
}
static void
create_final(void *data, unsigned int flags)
{
}
static const struct option create_opts[] = {
{"gc", 1, 0, 'g'},
{NULL},
};
static ip_set_ip_t
adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_iptreemap *mydata = data;
ip_set_ip_t mask;
char *saved = ipset_strdup(arg);
char *ptr, *tmp = saved;
if (strchr(tmp, '/')) {
parse_ipandmask(tmp, &mydata->start, &mask);
mydata->end = mydata->start | ~mask;
} else {
ptr = strsep(&tmp, ":");
parse_ip(ptr, &mydata->start);
if (tmp) {
parse_ip(tmp, &mydata->end);
} else {
mydata->end = mydata->start;
}
}
return 1;
}
static void
initheader(struct set *set, const void *data)
{
const struct ip_set_req_iptreemap_create *header = data;
struct ip_set_iptreemap *map = set->settype->header;
map->gc_interval = header->gc_interval;
}
static void
printheader(struct set *set, unsigned int options)
{
struct ip_set_iptreemap *mysetdata = set->settype->header;
if (mysetdata->gc_interval)
printf(" gc: %u", mysetdata->gc_interval);
printf("\n");
}
static void
printips_sorted(struct set *set, void *data, size_t len, unsigned int options)
{
struct ip_set_req_iptreemap *req;
size_t offset = 0;
while (len >= offset + sizeof(struct ip_set_req_iptreemap)) {
req = data + offset;
printf("%s", ip_tostring(req->start, options));
if (req->start != req->end)
printf(":%s", ip_tostring(req->end, options));
printf("\n");
offset += sizeof(struct ip_set_req_iptreemap);
}
}
static void
saveheader(struct set *set, unsigned int options)
{
struct ip_set_iptreemap *mysetdata = set->settype->header;
printf("-N %s %s", set->name, set->settype->typename);
if (mysetdata->gc_interval)
printf(" --gc %u", mysetdata->gc_interval);
printf("\n");
}
static void
saveips(struct set *set, void *data, size_t len, unsigned int options)
{
struct ip_set_req_iptreemap *req;
size_t offset = 0;
while (len >= offset + sizeof(struct ip_set_req_iptreemap)) {
req = data + offset;
printf("-A %s %s", set->name, ip_tostring(req->start, options));
if (req->start != req->end)
printf(":%s", ip_tostring(req->end, options));
printf("\n");
offset += sizeof(struct ip_set_req_iptreemap);
}
}
static void
usage(void)
{
printf(
"-N set iptreemap --gc interval\n"
"-A set IP\n"
"-D set IP\n"
"-T set IP\n"
);
}
static struct settype settype_iptreemap = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
.create_size = sizeof(struct ip_set_req_iptreemap_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
.adt_size = sizeof(struct ip_set_req_iptreemap),
.adt_parser = &adt_parser,
.header_size = sizeof(struct ip_set_iptreemap),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips_sorted,
.printips_sorted = &printips_sorted,
.saveheader = &saveheader,
.saveips = &saveips,
.bindip_tostring = &binding_ip_tostring,
.bindip_parse = &parse_ip,
.usage = &usage,
};
static __attribute__((constructor)) void iptreemap_init(void)
{
settype_register(&settype_iptreemap);
}

View File

@@ -0,0 +1,341 @@
/* Copyright 2000, 2001, 2002 Joakim Axelsson (gozem@linux.nu)
* Patrick Schaaf (bof@bof.de)
* Martin Josefsson (gandalf@wlug.westbo.se)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
#include "ip_set_macipmap.h"
#include "ipset.h"
#define BUFLEN 30;
#define OPT_CREATE_FROM 0x01U
#define OPT_CREATE_TO 0x02U
#define OPT_CREATE_NETWORK 0x04U
#define OPT_CREATE_MATCHUNSET 0x08U
#define OPT_ADDDEL_IP 0x01U
#define OPT_ADDDEL_MAC 0x02U
/* Initialize the create. */
static void create_init(void *data)
{
DP("create INIT");
/* Nothing */
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_macipmap_create *mydata =
(struct ip_set_req_macipmap_create *) data;
DP("create_parse");
switch (c) {
case '1':
parse_ip(optarg, &mydata->from);
*flags |= OPT_CREATE_FROM;
DP("--from %x (%s)", mydata->from,
ip_tostring_numeric(mydata->from));
break;
case '2':
parse_ip(optarg, &mydata->to);
*flags |= OPT_CREATE_TO;
DP("--to %x (%s)", mydata->to,
ip_tostring_numeric(mydata->to));
break;
case '3':
parse_ipandmask(optarg, &mydata->from, &mydata->to);
/* Make to the last of from + mask */
mydata->to = mydata->from | (~mydata->to);
*flags |= OPT_CREATE_NETWORK;
DP("--network from %x (%s)",
mydata->from, ip_tostring_numeric(mydata->from));
DP("--network to %x (%s)",
mydata->to, ip_tostring_numeric(mydata->to));
break;
case '4':
mydata->flags |= IPSET_MACIP_MATCHUNSET;
*flags |= OPT_CREATE_MATCHUNSET;
DP("--matchunset");
break;
default:
return 0;
}
return 1;
}
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
struct ip_set_req_macipmap_create *mydata =
(struct ip_set_req_macipmap_create *) data;
if (flags == 0)
exit_error(PARAMETER_PROBLEM,
"Need to specify --from and --to, or --network\n");
if (flags & OPT_CREATE_NETWORK) {
/* --network */
if ((flags & OPT_CREATE_FROM) || (flags & OPT_CREATE_TO))
exit_error(PARAMETER_PROBLEM,
"Can't specify --from or --to with --network\n");
} else {
/* --from --to */
if ((flags & OPT_CREATE_FROM) == 0
|| (flags & OPT_CREATE_TO) == 0)
exit_error(PARAMETER_PROBLEM,
"Need to specify both --from and --to\n");
}
DP("from : %x to: %x diff: %d match unset: %d", mydata->from,
mydata->to, mydata->to - mydata->from,
flags & OPT_CREATE_MATCHUNSET);
if (mydata->from > mydata->to)
exit_error(PARAMETER_PROBLEM,
"From can't be lower than to.\n");
if (mydata->to - mydata->from > MAX_RANGE)
exit_error(PARAMETER_PROBLEM,
"Range too large. Max is %d IPs in range\n",
MAX_RANGE+1);
}
/* Create commandline options */
static const struct option create_opts[] = {
{"from", 1, 0, '1'},
{"to", 1, 0, '2'},
{"network", 1, 0, '3'},
{"matchunset", 0, 0, '4'},
{NULL},
};
static void parse_mac(const char *mac, unsigned char *ethernet)
{
unsigned int i = 0;
if (strlen(mac) != ETH_ALEN * 3 - 1)
exit_error(PARAMETER_PROBLEM, "Bad mac address `%s'", mac);
for (i = 0; i < ETH_ALEN; i++) {
long number;
char *end;
number = strtol(mac + i * 3, &end, 16);
if (end == mac + i * 3 + 2 && number >= 0 && number <= 255)
ethernet[i] = number;
else
exit_error(PARAMETER_PROBLEM,
"Bad mac address `%s'", mac);
}
}
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_macipmap *mydata =
(struct ip_set_req_macipmap *) data;
char *saved = ipset_strdup(arg);
char *ptr, *tmp = saved;
DP("macipmap: %p %p", arg, data);
ptr = strsep(&tmp, ":%");
parse_ip(ptr, &mydata->ip);
if (tmp)
parse_mac(tmp, mydata->ethernet);
else
memset(mydata->ethernet, 0, ETH_ALEN);
free(saved);
return 1;
}
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_macipmap_create *header =
(struct ip_set_req_macipmap_create *) data;
struct ip_set_macipmap *map =
(struct ip_set_macipmap *) set->settype->header;
memset(map, 0, sizeof(struct ip_set_macipmap));
map->first_ip = header->from;
map->last_ip = header->to;
map->flags = header->flags;
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_macipmap *mysetdata =
(struct ip_set_macipmap *) set->settype->header;
printf(" from: %s", ip_tostring(mysetdata->first_ip, options));
printf(" to: %s", ip_tostring(mysetdata->last_ip, options));
if (mysetdata->flags & IPSET_MACIP_MATCHUNSET)
printf(" matchunset");
printf("\n");
}
static void print_mac(unsigned char macaddress[ETH_ALEN])
{
unsigned int i;
printf("%02X", macaddress[0]);
for (i = 1; i < ETH_ALEN; i++)
printf(":%02X", macaddress[i]);
}
static void printips_sorted(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_macipmap *mysetdata =
(struct ip_set_macipmap *) set->settype->header;
struct ip_set_macip *table =
(struct ip_set_macip *) data;
u_int32_t addr = mysetdata->first_ip;
while (addr <= mysetdata->last_ip) {
if (test_bit(IPSET_MACIP_ISSET,
(void *)&table[addr - mysetdata->first_ip].flags)) {
printf("%s:", ip_tostring(addr, options));
print_mac(table[addr - mysetdata->first_ip].
ethernet);
printf("\n");
}
addr++;
}
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_macipmap *mysetdata =
(struct ip_set_macipmap *) set->settype->header;
printf("-N %s %s --from %s",
set->name, set->settype->typename,
ip_tostring(mysetdata->first_ip, options));
printf(" --to %s", ip_tostring(mysetdata->last_ip, options));
if (mysetdata->flags & IPSET_MACIP_MATCHUNSET)
printf(" --matchunset");
printf("\n");
}
static void saveips(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_macipmap *mysetdata =
(struct ip_set_macipmap *) set->settype->header;
struct ip_set_macip *table =
(struct ip_set_macip *) data;
u_int32_t addr = mysetdata->first_ip;
while (addr <= mysetdata->last_ip) {
if (test_bit(IPSET_MACIP_ISSET,
(void *)&table[addr - mysetdata->first_ip].flags)) {
printf("-A %s %s:",
set->name, ip_tostring(addr, options));
print_mac(table[addr - mysetdata->first_ip].
ethernet);
printf("\n");
}
addr++;
}
}
static void usage(void)
{
printf
("-N set macipmap --from IP --to IP [--matchunset]\n"
"-N set macipmap --network IP/mask [--matchunset]\n"
"-A set IP:MAC\n"
"-D set IP[:MAC]\n"
"-T set IP[:MAC]\n");
}
static struct settype settype_macipmap = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_macipmap_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_macipmap),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_macipmap),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips_sorted, /* We only have sorted version */
.printips_sorted = &printips_sorted,
.saveheader = &saveheader,
.saveips = &saveips,
/* Bindings */
.bindip_tostring = &binding_ip_tostring,
.bindip_parse = &parse_ip,
.usage = &usage,
};
static __attribute__((constructor)) void macipmap_init(void)
{
settype_register(&settype_macipmap);
}

View File

@@ -0,0 +1,352 @@
/* Copyright 2004 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <asm/types.h>
#include "ip_set_nethash.h"
#include "ip_set_jhash.h"
#include "ipset.h"
#define BUFLEN 30;
#define OPT_CREATE_HASHSIZE 0x01U
#define OPT_CREATE_PROBES 0x02U
#define OPT_CREATE_RESIZE 0x04U
/* Initialize the create. */
static void create_init(void *data)
{
struct ip_set_req_nethash_create *mydata =
(struct ip_set_req_nethash_create *) data;
DP("create INIT");
/* Default create parameters */
mydata->hashsize = 1024;
mydata->probes = 4;
mydata->resize = 50;
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_nethash_create *mydata =
(struct ip_set_req_nethash_create *) data;
ip_set_ip_t value;
DP("create_parse");
switch (c) {
case '1':
if (string_to_number(optarg, 1, UINT_MAX - 1, &mydata->hashsize))
exit_error(PARAMETER_PROBLEM, "Invalid hashsize `%s' specified", optarg);
*flags |= OPT_CREATE_HASHSIZE;
DP("--hashsize %u", mydata->hashsize);
break;
case '2':
if (string_to_number(optarg, 1, 65535, &value))
exit_error(PARAMETER_PROBLEM, "Invalid probes `%s' specified", optarg);
mydata->probes = value;
*flags |= OPT_CREATE_PROBES;
DP("--probes %u", mydata->probes);
break;
case '3':
if (string_to_number(optarg, 0, 65535, &value))
exit_error(PARAMETER_PROBLEM, "Invalid resize `%s' specified", optarg);
mydata->resize = value;
*flags |= OPT_CREATE_RESIZE;
DP("--resize %u", mydata->resize);
break;
default:
return 0;
}
return 1;
}
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
#ifdef IPSET_DEBUG
struct ip_set_req_nethash_create *mydata =
(struct ip_set_req_nethash_create *) data;
DP("hashsize %u probes %u resize %u",
mydata->hashsize, mydata->probes, mydata->resize);
#endif
}
/* Create commandline options */
static const struct option create_opts[] = {
{"hashsize", 1, 0, '1'},
{"probes", 1, 0, '2'},
{"resize", 1, 0, '3'},
{NULL},
};
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_nethash *mydata =
(struct ip_set_req_nethash *) data;
char *saved = ipset_strdup(arg);
char *ptr, *tmp = saved;
ip_set_ip_t cidr;
ptr = strsep(&tmp, "/");
if (tmp == NULL) {
if (cmd == CMD_TEST)
cidr = 32;
else
exit_error(PARAMETER_PROBLEM,
"Missing cidr from `%s'", arg);
} else
if (string_to_number(tmp, 1, 31, &cidr))
exit_error(PARAMETER_PROBLEM,
"Out of range cidr `%s' specified", arg);
mydata->cidr = cidr;
parse_ip(ptr, &mydata->ip);
if (!mydata->ip)
exit_error(PARAMETER_PROBLEM,
"Zero valued IP address `%s' specified", ptr);
free(saved);
return mydata->ip;
};
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_nethash_create *header =
(struct ip_set_req_nethash_create *) data;
struct ip_set_nethash *map =
(struct ip_set_nethash *) set->settype->header;
memset(map, 0, sizeof(struct ip_set_nethash));
map->hashsize = header->hashsize;
map->probes = header->probes;
map->resize = header->resize;
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_nethash *mysetdata =
(struct ip_set_nethash *) set->settype->header;
printf(" hashsize: %u", mysetdata->hashsize);
printf(" probes: %u", mysetdata->probes);
printf(" resize: %u\n", mysetdata->resize);
}
static char buf[20];
static char * unpack_ip_tostring(ip_set_ip_t ip, unsigned options)
{
int i, j = 3;
unsigned char a, b;
ip = htonl(ip);
for (i = 3; i >= 0; i--)
if (((unsigned char *)&ip)[i] != 0) {
j = i;
break;
}
a = ((unsigned char *)&ip)[j];
if (a <= 128) {
a = (a - 1) * 2;
b = 7;
} else if (a <= 192) {
a = (a - 129) * 4;
b = 6;
} else if (a <= 224) {
a = (a - 193) * 8;
b = 5;
} else if (a <= 240) {
a = (a - 225) * 16;
b = 4;
} else if (a <= 248) {
a = (a - 241) * 32;
b = 3;
} else if (a <= 252) {
a = (a - 249) * 64;
b = 2;
} else if (a <= 254) {
a = (a - 253) * 128;
b = 1;
} else {
a = b = 0;
}
((unsigned char *)&ip)[j] = a;
b += j * 8;
sprintf(buf, "%u.%u.%u.%u/%u",
((unsigned char *)&ip)[0],
((unsigned char *)&ip)[1],
((unsigned char *)&ip)[2],
((unsigned char *)&ip)[3],
b);
DP("%s %s", ip_tostring(ntohl(ip), options), buf);
return buf;
}
static void printips(struct set *set, void *data, size_t len,
unsigned int options)
{
size_t offset = 0;
ip_set_ip_t *ip;
while (offset < len) {
ip = data + offset;
if (*ip)
printf("%s\n", unpack_ip_tostring(*ip, options));
offset += sizeof(ip_set_ip_t);
}
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_nethash *mysetdata =
(struct ip_set_nethash *) set->settype->header;
printf("-N %s %s --hashsize %u --probes %u --resize %u\n",
set->name, set->settype->typename,
mysetdata->hashsize, mysetdata->probes, mysetdata->resize);
}
/* Print save for an IP */
static void saveips(struct set *set, void *data, size_t len,
unsigned int options)
{
size_t offset = 0;
ip_set_ip_t *ip;
while (offset < len) {
ip = data + offset;
if (*ip)
printf("-A %s %s\n", set->name,
unpack_ip_tostring(*ip, options));
offset += sizeof(ip_set_ip_t);
}
}
static char * net_tostring(struct set *set, ip_set_ip_t ip, unsigned options)
{
return unpack_ip_tostring(ip, options);
}
static void parse_net(const char *str, ip_set_ip_t *ip)
{
char *saved = strdup(str);
char *ptr, *tmp = saved;
ip_set_ip_t cidr;
ptr = strsep(&tmp, "/");
if (tmp == NULL)
exit_error(PARAMETER_PROBLEM,
"Missing cidr from `%s'", str);
if (string_to_number(tmp, 1, 31, &cidr))
exit_error(PARAMETER_PROBLEM,
"Out of range cidr `%s' specified", str);
parse_ip(ptr, ip);
free(saved);
*ip = pack(*ip, cidr);
}
static void usage(void)
{
printf
("-N set nethash [--hashsize hashsize] [--probes probes ]\n"
" [--resize resize]\n"
"-A set IP/cidr\n"
"-D set IP/cidr\n"
"-T set IP/cidr\n");
}
static struct settype settype_nethash = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_nethash_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_nethash),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_nethash),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printips, /* We only have the unsorted version */
.printips_sorted = &printips,
.saveheader = &saveheader,
.saveips = &saveips,
/* Bindings */
.bindip_tostring = &net_tostring,
.bindip_parse = &parse_net,
.usage = &usage,
};
static __attribute__((constructor)) void nethash_init(void)
{
settype_register(&settype_nethash);
}

View File

@@ -0,0 +1,247 @@
/* Copyright 2004 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "ip_set_portmap.h"
#include "ipset.h"
#define BUFLEN 30;
#define OPT_CREATE_FROM 0x01U
#define OPT_CREATE_TO 0x02U
#define OPT_ADDDEL_PORT 0x01U
/* Initialize the create. */
static void create_init(void *data)
{
DP("create INIT");
/* Nothing */
}
/* Function which parses command options; returns true if it ate an option */
static int create_parse(int c, char *argv[], void *data, unsigned int *flags)
{
struct ip_set_req_portmap_create *mydata =
(struct ip_set_req_portmap_create *) data;
DP("create_parse");
switch (c) {
case '1':
parse_port(optarg, &mydata->from);
*flags |= OPT_CREATE_FROM;
DP("--from %x (%s)", mydata->from,
port_tostring(mydata->from, 0));
break;
case '2':
parse_port(optarg, &mydata->to);
*flags |= OPT_CREATE_TO;
DP("--to %x (%s)", mydata->to,
port_tostring(mydata->to, 0));
break;
default:
return 0;
}
return 1;
}
/* Final check; exit if not ok. */
static void create_final(void *data, unsigned int flags)
{
struct ip_set_req_portmap_create *mydata =
(struct ip_set_req_portmap_create *) data;
if (flags == 0) {
exit_error(PARAMETER_PROBLEM,
"Need to specify --from and --to\n");
} else {
/* --from --to */
if ((flags & OPT_CREATE_FROM) == 0
|| (flags & OPT_CREATE_TO) == 0)
exit_error(PARAMETER_PROBLEM,
"Need to specify both --from and --to\n");
}
DP("from : %x to: %x diff: %d", mydata->from, mydata->to,
mydata->to - mydata->from);
if (mydata->from > mydata->to)
exit_error(PARAMETER_PROBLEM,
"From can't be lower than to.\n");
if (mydata->to - mydata->from > MAX_RANGE)
exit_error(PARAMETER_PROBLEM,
"Range too large. Max is %d ports in range\n",
MAX_RANGE+1);
}
/* Create commandline options */
static const struct option create_opts[] = {
{"from", 1, 0, '1'},
{"to", 1, 0, '2'},
{NULL},
};
/* Add, del, test parser */
static ip_set_ip_t adt_parser(unsigned int cmd, const char *arg, void *data)
{
struct ip_set_req_portmap *mydata =
(struct ip_set_req_portmap *) data;
parse_port(arg, &mydata->port);
DP("%s", port_tostring(mydata->port, 0));
return 1;
}
/*
* Print and save
*/
static void initheader(struct set *set, const void *data)
{
struct ip_set_req_portmap_create *header =
(struct ip_set_req_portmap_create *) data;
struct ip_set_portmap *map =
(struct ip_set_portmap *) set->settype->header;
memset(map, 0, sizeof(struct ip_set_portmap));
map->first_port = header->from;
map->last_port = header->to;
}
static void printheader(struct set *set, unsigned int options)
{
struct ip_set_portmap *mysetdata =
(struct ip_set_portmap *) set->settype->header;
printf(" from: %s", port_tostring(mysetdata->first_port, options));
printf(" to: %s\n", port_tostring(mysetdata->last_port, options));
}
static void printports_sorted(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_portmap *mysetdata =
(struct ip_set_portmap *) set->settype->header;
u_int32_t addr = mysetdata->first_port;
DP("%u -- %u", mysetdata->first_port, mysetdata->last_port);
while (addr <= mysetdata->last_port) {
if (test_bit(addr - mysetdata->first_port, data))
printf("%s\n", port_tostring(addr, options));
addr++;
}
}
static char *binding_port_tostring(struct set *set, ip_set_ip_t ip,
unsigned int options)
{
return port_tostring(ip, options);
}
static void saveheader(struct set *set, unsigned int options)
{
struct ip_set_portmap *mysetdata =
(struct ip_set_portmap *) set->settype->header;
printf("-N %s %s --from %s",
set->name,
set->settype->typename,
port_tostring(mysetdata->first_port, options));
printf(" --to %s\n",
port_tostring(mysetdata->last_port, options));
}
static void saveports(struct set *set, void *data, size_t len,
unsigned int options)
{
struct ip_set_portmap *mysetdata =
(struct ip_set_portmap *) set->settype->header;
u_int32_t addr = mysetdata->first_port;
while (addr <= mysetdata->last_port) {
if (test_bit(addr - mysetdata->first_port, data))
printf("-A %s %s\n",
set->name,
port_tostring(addr, options));
addr++;
}
}
static void usage(void)
{
printf
("-N set portmap --from PORT --to PORT\n"
"-A set PORT\n"
"-D set PORT\n"
"-T set PORT\n");
}
static struct settype settype_portmap = {
.typename = SETTYPE_NAME,
.protocol_version = IP_SET_PROTOCOL_VERSION,
/* Create */
.create_size = sizeof(struct ip_set_req_portmap_create),
.create_init = &create_init,
.create_parse = &create_parse,
.create_final = &create_final,
.create_opts = create_opts,
/* Add/del/test */
.adt_size = sizeof(struct ip_set_req_portmap),
.adt_parser = &adt_parser,
/* Printing */
.header_size = sizeof(struct ip_set_portmap),
.initheader = &initheader,
.printheader = &printheader,
.printips = &printports_sorted, /* We only have sorted version */
.printips_sorted = &printports_sorted,
.saveheader = &saveheader,
.saveips = &saveports,
/* Bindings */
.bindip_tostring = &binding_port_tostring,
.bindip_parse = &parse_port,
.usage = &usage,
};
static __attribute__((constructor)) void portmap_init(void)
{
settype_register(&settype_portmap);
}

179
extensions/ipset/ipt_SET.c Normal file
View File

@@ -0,0 +1,179 @@
/* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
* Patrick Schaaf <bof@bof.de>
* Martin Josefsson <gandalf@wlug.westbo.se>
* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* ipt_SET.c - netfilter target to manipulate IP sets */
#include <linux/types.h>
#include <linux/ip.h>
#include <linux/timer.h>
#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/netdevice.h>
#include <linux/if.h>
#include <linux/inetdevice.h>
#include <linux/version.h>
#include <net/protocol.h>
#include <net/checksum.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ipt_set.h"
static unsigned int
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
target(struct sk_buff *skb,
#else
target(struct sk_buff **pskb,
#endif
const struct net_device *in,
const struct net_device *out,
unsigned int hooknum,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
const struct xt_target *target,
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
const void *targinfo,
void *userinfo)
#else
const void *targinfo)
#endif
{
const struct ipt_set_info_target *info = targinfo;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24)
struct sk_buff *skb = *pskb;
#endif
if (info->add_set.index != IP_SET_INVALID_ID)
ip_set_addip_kernel(info->add_set.index,
skb,
info->add_set.flags);
if (info->del_set.index != IP_SET_INVALID_ID)
ip_set_delip_kernel(info->del_set.index,
skb,
info->del_set.flags);
return IPT_CONTINUE;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
static bool
#else
static int
#endif
checkentry(const char *tablename,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
const void *e,
#else
const struct ipt_entry *e,
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
const struct xt_target *target,
#endif
void *targinfo,
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
unsigned int targinfosize,
#endif
unsigned int hook_mask)
{
struct ipt_set_info_target *info = targinfo;
ip_set_id_t index;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
if (targinfosize != IPT_ALIGN(sizeof(*info))) {
DP("bad target info size %u", targinfosize);
return 0;
}
#endif
if (info->add_set.index != IP_SET_INVALID_ID) {
index = ip_set_get_byindex(info->add_set.index);
if (index == IP_SET_INVALID_ID) {
ip_set_printk("cannot find add_set index %u as target",
info->add_set.index);
return 0; /* error */
}
}
if (info->del_set.index != IP_SET_INVALID_ID) {
index = ip_set_get_byindex(info->del_set.index);
if (index == IP_SET_INVALID_ID) {
ip_set_printk("cannot find del_set index %u as target",
info->del_set.index);
return 0; /* error */
}
}
if (info->add_set.flags[IP_SET_MAX_BINDINGS] != 0
|| info->del_set.flags[IP_SET_MAX_BINDINGS] != 0) {
ip_set_printk("That's nasty!");
return 0; /* error */
}
return 1;
}
static void destroy(
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
const struct xt_target *target,
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
void *targetinfo, unsigned int targetsize)
#else
void *targetinfo)
#endif
{
struct ipt_set_info_target *info = targetinfo;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
if (targetsize != IPT_ALIGN(sizeof(struct ipt_set_info_target))) {
ip_set_printk("invalid targetsize %d", targetsize);
return;
}
#endif
if (info->add_set.index != IP_SET_INVALID_ID)
ip_set_put(info->add_set.index);
if (info->del_set.index != IP_SET_INVALID_ID)
ip_set_put(info->del_set.index);
}
static struct ipt_target SET_target = {
.name = "SET",
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)
.family = AF_INET,
#endif
.target = target,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
.targetsize = sizeof(struct ipt_set_info_target),
#endif
.checkentry = checkentry,
.destroy = destroy,
.me = THIS_MODULE
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("iptables IP set target module");
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)
#define ipt_register_target xt_register_target
#define ipt_unregister_target xt_unregister_target
#endif
static int __init ipt_SET_init(void)
{
return ipt_register_target(&SET_target);
}
static void __exit ipt_SET_fini(void)
{
ipt_unregister_target(&SET_target);
}
module_init(ipt_SET_init);
module_exit(ipt_SET_fini);

159
extensions/ipset/ipt_set.c Normal file
View File

@@ -0,0 +1,159 @@
/* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
* Patrick Schaaf <bof@bof.de>
* Martin Josefsson <gandalf@wlug.westbo.se>
* Copyright (C) 2003-2004 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module to match an IP set. */
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include "ip_set.h"
#include "ipt_set.h"
static inline int
match_set(const struct ipt_set_info *info,
const struct sk_buff *skb,
int inv)
{
if (ip_set_testip_kernel(info->index, skb, info->flags))
inv = !inv;
return inv;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
static bool
#else
static int
#endif
match(const struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
const struct xt_match *match,
#endif
const void *matchinfo,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
int offset, unsigned int protoff, bool *hotdrop)
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
int offset, unsigned int protoff, int *hotdrop)
#else
int offset, int *hotdrop)
#endif
{
const struct ipt_set_info_match *info = matchinfo;
return match_set(&info->match_set,
skb,
info->match_set.flags[0] & IPSET_MATCH_INV);
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,23)
static bool
#else
static int
#endif
checkentry(const char *tablename,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
const void *inf,
#else
const struct ipt_ip *ip,
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
const struct xt_match *match,
#endif
void *matchinfo,
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
unsigned int matchsize,
#endif
unsigned int hook_mask)
{
struct ipt_set_info_match *info = matchinfo;
ip_set_id_t index;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
if (matchsize != IPT_ALIGN(sizeof(struct ipt_set_info_match))) {
ip_set_printk("invalid matchsize %d", matchsize);
return 0;
}
#endif
index = ip_set_get_byindex(info->match_set.index);
if (index == IP_SET_INVALID_ID) {
ip_set_printk("Cannot find set indentified by id %u to match",
info->match_set.index);
return 0; /* error */
}
if (info->match_set.flags[IP_SET_MAX_BINDINGS] != 0) {
ip_set_printk("That's nasty!");
return 0; /* error */
}
return 1;
}
static void destroy(
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
const struct xt_match *match,
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
void *matchinfo, unsigned int matchsize)
#else
void *matchinfo)
#endif
{
struct ipt_set_info_match *info = matchinfo;
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19)
if (matchsize != IPT_ALIGN(sizeof(struct ipt_set_info_match))) {
ip_set_printk("invalid matchsize %d", matchsize);
return;
}
#endif
ip_set_put(info->match_set.index);
}
static struct ipt_match set_match = {
.name = "set",
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)
.family = AF_INET,
#endif
.match = &match,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,17)
.matchsize = sizeof(struct ipt_set_info_match),
#endif
.checkentry = &checkentry,
.destroy = &destroy,
.me = THIS_MODULE
};
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("iptables IP set match module");
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)
#define ipt_register_match xt_register_match
#define ipt_unregister_match xt_unregister_match
#endif
static int __init ipt_ipset_init(void)
{
return ipt_register_match(&set_match);
}
static void __exit ipt_ipset_fini(void)
{
ipt_unregister_match(&set_match);
}
module_init(ipt_ipset_init);
module_exit(ipt_ipset_fini);

View File

@@ -0,0 +1,21 @@
#ifndef _IPT_SET_H
#define _IPT_SET_H
#include "ip_set.h"
struct ipt_set_info {
ip_set_id_t index;
u_int32_t flags[IP_SET_MAX_BINDINGS + 1];
};
/* match info */
struct ipt_set_info_match {
struct ipt_set_info match_set;
};
struct ipt_set_info_target {
struct ipt_set_info add_set;
struct ipt_set_info del_set;
};
#endif /*_IPT_SET_H*/

View File

@@ -1,13 +1,15 @@
/*
* CHAOS target for Xtables
* Copyright © CC Computer Consultants GmbH, 2006 - 2008
* "CHAOS" target extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2006 - 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License; either version
* 2 or 3 as published by the Free Software Foundation.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
@@ -74,7 +76,6 @@ static void chaos_tg_print(const void *ip,
printf("TARPIT ");
break;
}
return;
}
static void chaos_tg_save(const void *ip, const struct xt_entry_target *target)
@@ -89,7 +90,6 @@ static void chaos_tg_save(const void *ip, const struct xt_entry_target *target)
printf("--tarpit ");
break;
}
return;
}
static struct xtables_target chaos_tg_reg = {

View File

@@ -16,3 +16,6 @@ connections than they can.
.PP
The randomness factor of not replying vs. replying can be set during load-time
of the xt_CHAOS module or during runtime in /sys/modules/xt_CHAOS/parameters.
.PP
See http://jengelh.medozas.de/projects/chaostables/ for more information
about CHAOS, DELUDE and portscan.

View File

@@ -1,10 +1,11 @@
/*
* DELUDE target for Xtables
* Copyright © CC Computer Consultants GmbH, 2006 - 2008
* "DELUDE" target extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2006 - 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License; either version
* 2 or 3 as published by the Free Software Foundation.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stdio.h>

101
extensions/libxt_DHCPADDR.c Normal file
View File

@@ -0,0 +1,101 @@
/*
* "DHCPADDR" target extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ether.h>
#include <xtables.h>
#include "xt_DHCPADDR.h"
#include "mac.c"
enum {
F_MAC = 1 << 0,
};
static const struct option dhcpaddr_tg_opts[] = {
{.name = "set-mac", .has_arg = true, .val = 'M'},
{NULL},
};
static void dhcpaddr_tg_help(void)
{
printf(
"DHCPADDDR target options:\n"
" --set-mac lladdr[/mask] Set MAC address in DHCP Client Host field\n"
);
}
static int dhcpaddr_tg_parse(int c, char **argv, int invert,
unsigned int *flags, const void *entry, struct xt_entry_target **target)
{
struct dhcpaddr_info *info = (void *)(*target)->data;
switch (c) {
case 'M':
param_act(P_ONLY_ONCE, "DHCPADDR", "--set-mac", *flags & F_MAC);
param_act(P_NO_INVERT, "DHCPADDR", "--set-mac", invert);
if (!mac_parse(optarg, info->addr, &info->mask))
param_act(P_BAD_VALUE, "DHCPADDR", "--set-mac", optarg);
*flags |= F_MAC;
return true;
}
return false;
}
static void dhcpaddr_tg_check(unsigned int flags)
{
if (flags == 0)
exit_error(PARAMETER_PROBLEM, "DHCPADDR target: "
"--set-mac parameter required");
}
static void dhcpaddr_tg_print(const void *ip,
const struct xt_entry_target *target, int numeric)
{
const struct dhcpaddr_info *info = (void *)target->data;
printf("DHCPADDR %s" DH_MAC_FMT "/%u ",
info->invert ? "!" : "", DH_MAC_HEX(info->addr), info->mask);
}
static void dhcpaddr_tg_save(const void *ip,
const struct xt_entry_target *target)
{
const struct dhcpaddr_info *info = (const void *)target->data;
if (info->invert)
printf("! ");
printf("--set-mac " DH_MAC_FMT "/%u ",
DH_MAC_HEX(info->addr), info->mask);
}
static struct xtables_target dhcpaddr_tg_reg = {
.version = XTABLES_VERSION,
.name = "DHCPADDR",
.revision = 0,
.family = PF_INET,
.size = XT_ALIGN(sizeof(struct dhcpaddr_info)),
.userspacesize = XT_ALIGN(sizeof(struct dhcpaddr_info)),
.help = dhcpaddr_tg_help,
.parse = dhcpaddr_tg_parse,
.final_check = dhcpaddr_tg_check,
.print = dhcpaddr_tg_print,
.save = dhcpaddr_tg_save,
.extra_opts = dhcpaddr_tg_opts,
};
static void _init(void)
{
xtables_register_target(&dhcpaddr_tg_reg);
}

View File

@@ -0,0 +1,25 @@
In conjunction with ebtables, DHCPADDR can be used to completely change all MAC
addresses from and to a VMware-based virtual machine. This is needed because
VMware does not allow to set a non-VMware MAC address before an operating
system is booted (and the MAC be changed with `ip link set eth0 address
aa:bb..`).
.TP
\fB--set-mac\fP \fIaa:bb:cc:dd:ee:ff\fP[\fB/\fP\fImask\fP]
Replace the client host MAC address field in the DHCP message with the given
MAC address. This option is mandatory. The \fImask\fP parameter specifies the
prefix length of bits to change.
.PP
EXAMPLE, replacing all addresses from one of VMware's assigned vendor IDs
(00:50:56) addresses with something else:
.PP
iptables -t mangle -A FORWARD -p udp --dport 67 -m physdev --physdev-in vmnet1
-m dhcpaddr --mac 00:50:56:00:00:00/24 -j DHCPADDR --set-mac
ab:cd:ef:00:00:00/24
.PP
iptables -t mangle -A FORWARD -p udp --dport 68 -m physdev --physdev-out vmnet1
-m dhcpaddr --mac ab:cd:ef:00:00:00/24 -j DHCPADDR --set-mac
00:50:56:00:00:00/24
.PP
(This assumes there is a bridge interface that has vmnet1 as a port. You will
also need to add appropriate ebtables rules to change the MAC address of the
Ethernet headers.)

View File

@@ -1,3 +1,12 @@
/*
* "ECHO" target extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <stdio.h>
#include <getopt.h>
#include <xtables.h>

View File

@@ -1,9 +1,12 @@
/* Shared library add-on to iptables to add IPMARK target support.
* (C) 2003 by Grzegorz Janoszka <Grzegorz.Janoszka@pro.onet.pl>
/*
* "IPMARK" target extension for iptables
* Copyright © Grzegorz Janoszka <Grzegorz.Janoszka@pro.onet.pl>, 2003
* Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* based on original MARK target
*
* This program is distributed under the terms of GNU GPL
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stdio.h>

View File

@@ -7,31 +7,31 @@ This target is to be used inside the \fBmangle\fP table.
\fB--addr\fP {\fBsrc\fP|\fBdst\fP}
Select source or destination IP address as a basis for the mark.
.TP
.BI "--and-mask " "mask"
Perform bitwise `and' on the IP address and this mask.
\fB--and-mask\fP \fImask\fP
Perform bitwise AND on the IP address and this bitmask.
.TP
.BI "--or-mask " "mask"
Perform bitwise `or' on the IP address and this mask.
\fB--or-mask\fP \fImask\fP
Perform bitwise OR on the IP address and this bitmask.
.TP
\fB--shift\fP \fIvalue\fP
Shift addresses to the right by the given number of bits before taking it
as a mark. (This is done before ANDing or ORing it.) This option is needed
to select part of an IPv6 address, because marks are only 32 bits in size.
.P
.PP
The order of IP address bytes is reversed to meet "human order of bytes":
192.168.0.1 is 0xc0a80001. At first the `and' operation is performed, then
`or'.
192.168.0.1 is 0xc0a80001. At first the "AND" operation is performed, then
"OR".
.PP
Examples:
.PP
We create a queue for each user, the queue number is adequate
to the IP address of the user, e.g.: all packets going to/from 192.168.5.2
are directed to 1:0502 queue, 192.168.5.12 -> 1:050c etc.
.PP
We have one classifier rule:
.IP
tc filter add dev eth3 parent 1:0 protocol ip fw
.P
.PP
Earlier we had many rules just like below:
.IP
iptables -t mangle -A POSTROUTING -o eth3 -d 192.168.5.2 -j MARK
@@ -39,12 +39,12 @@ iptables -t mangle -A POSTROUTING -o eth3 -d 192.168.5.2 -j MARK
.IP
iptables -t mangle -A POSTROUTING -o eth3 -d 192.168.5.3 -j MARK
--set-mark 0x10503
.P
.PP
Using IPMARK target we can replace all the mangle/mark rules with only one:
.IP
iptables -t mangle -A POSTROUTING -o eth3 -j IPMARK --addr=dst
--and-mask=0xffff --or-mask=0x10000
.P
iptables -t mangle -A POSTROUTING -o eth3 -j IPMARK --addr dst
--and-mask 0xffff --or-mask 0x10000
.PP
On the routers with hundreds of users there should be significant load
decrease (e.g. twice).
.PP

View File

@@ -1,3 +1,12 @@
/*
* "LOGMARK" target extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stdbool.h>
#include <stdio.h>

50
extensions/libxt_SYSRQ.c Normal file
View File

@@ -0,0 +1,50 @@
/*
* "SYSRQ" target extension to iptables
* this file is in the Public Domain
*/
#include <stdio.h>
#include <getopt.h>
#include <xtables.h>
static void sysrq_tg_help(void)
{
printf("SYSRQ takes no options\n\n");
}
static int sysrq_tg_parse(int c, char **argv, int invert, unsigned int *flags,
const void *entry, struct xt_entry_target **target)
{
return 0;
}
static void sysrq_tg_check(unsigned int flags)
{
}
static struct xtables_target sysrq_tg4_reg = {
.version = XTABLES_VERSION,
.name = "SYSRQ",
.family = PF_INET,
.size = XT_ALIGN(0),
.userspacesize = XT_ALIGN(0),
.help = sysrq_tg_help,
.parse = sysrq_tg_parse,
.final_check = sysrq_tg_check,
};
static struct xtables_target sysrq_tg6_reg = {
.version = XTABLES_VERSION,
.name = "SYSRQ",
.family = PF_INET6,
.size = XT_ALIGN(0),
.userspacesize = XT_ALIGN(0),
.help = sysrq_tg_help,
.parse = sysrq_tg_parse,
.final_check = sysrq_tg_check,
};
static void _init(void)
{
xtables_register_target(&sysrq_tg4_reg);
xtables_register_target(&sysrq_tg6_reg);
}

View File

@@ -0,0 +1,47 @@
The SYSRQ target allows to remotely trigger sysrq on the local machine over the
network. This can be useful when vital parts of the machine hang, for example
an oops in a filesystem causing locks to be not released and processes to get
stuck as a result -- if still possible, use /proc/sysrq-trigger. Even when
processes are stuck, interrupts are likely to be still processed, and as such,
sysrq can be triggered through incoming network packets.
.PP
This xt_SYSRQ implementation does not use any encryption, so you should change
the SYSRQ password after use unless you have made sure it was transmitted
securely and no one sniffed the network, e.g. by use of an IPsec tunnel whose
endpoint is at the machine where you want to trigger the sysrq. Also, you
should limit as to who can issue commands using \fB-s\fP and/or \fB-m mac\fP,
and also that the destination is correct using \fB-d\fP (to protect against
potential broadcast packets), noting that it is still short of MAC/IP spoofing:
.IP
-A INPUT -s 10.10.25.1 -m mac --mac-source aa:bb:cc:dd:ee:ff -d 10.10.25.7
-p udp --dport 9 -j SYSRQ
.IP
(with IPsec) -A INPUT -s 10.10.25.1 -d 10.10.25.7 -m policy --dir in --pol
ipsec --proto esp --tunnel-src 10.10.25.1 --tunnel-dst 10.10.25.7
-p udp --dport 9 -j SYSRQ
.PP
This extension does not take any options. The \fB-p udp\fP options are
required.
.PP
The SYSRQ password can be changed through
/sys/module/xt_SYSRQ/parameters/password; note you need to use `echo -n` to
not add a newline to the password, i.e.
.IP
echo -n "password" >/sys/.../password
.PP
Alternatively, the password may be specified at modprobe time, but this is
insecure as people can possible see it through ps(1). You can use an option
line in /etc/modprobe.d/sysrq if it is properly guarded, that is, only readable
by root.
.IP
options xt_SYSRQ password=cookies
.PP
To trigger SYSRQ from a remote host, just use netcat or socat, specifying the
action (only one) as first character, followed by the password:
.IP
echo -n "scookies" | socat stdin udp-sendto:10.10.25.7:9
.IP
echo -n "scookies" | netcat -u 10.10.25.7 9
.PP
See the Linux docs for possible sysrq keys. Important ones are:
re(b)oot, power(o)ff, (s)ync filesystems, (u)mount and remount readonly.

View File

@@ -1,3 +1,7 @@
/*
* "TARPIT" target extension to iptables
* this file is in the Public Domain
*/
#include <stdio.h>
#include <getopt.h>
#include <xtables.h>

View File

@@ -1,9 +1,12 @@
/*
* libxt_TEE
* "TEE" target extension for iptables
* Copyright © Sebastian Claßen <sebastian.classen [at] freenet.ag>, 2007
* Jan Engelhardt <jengelh [at] medozas de>, 2007 - 2008
*
* Copyright © Sebastian Claßen <sebastian.classen@freenet.ag>, 2007
* Copyright © CC Computer Consultants GmbH, 2007 - 2008
* Jan Engelhardt <jengelh@computergmbh.de>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <sys/socket.h>
#include <getopt.h>

View File

@@ -1,4 +1,13 @@
/* Shared library add-on to iptables for condition match */
/*
* "condition" match extension for iptables
* Stephane Ouellette <ouellettes [at] videotron ca>, 2002-10-22
* Massimiliano Hofer <max [at] nucleus it>, 2006-05-15
* Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License; either version 2
* or 3 of the License, as published by the Free Software Foundation.
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
@@ -68,10 +77,10 @@ static void condition_save(const void *ip, const struct xt_entry_match *match)
printf("--condition %s\"%s\" ", (info->invert) ? "! " : "", info->name);
}
static struct xtables_match condition_mt4_reg = {
static struct xtables_match condition_mt_reg = {
.name = "condition",
.revision = 0,
.family = PF_INET,
.family = PF_UNSPEC,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_condition_mtinfo)),
.userspacesize = XT_ALIGN(sizeof(struct xt_condition_mtinfo)),
@@ -83,23 +92,7 @@ static struct xtables_match condition_mt4_reg = {
.extra_opts = condition_opts,
};
static struct xtables_match condition_mt6_reg = {
.name = "condition",
.revision = 0,
.family = PF_INET6,
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_condition_mtinfo)),
.userspacesize = offsetof(struct xt_condition_mtinfo, condvar),
.help = condition_help,
.parse = condition_parse,
.final_check = condition_check,
.print = condition_print,
.save = condition_save,
.extra_opts = condition_opts,
};
static void _init(void)
{
xtables_register_match(&condition_mt4_reg);
xtables_register_match(&condition_mt6_reg);
xtables_register_match(&condition_mt_reg);
}

102
extensions/libxt_dhcpaddr.c Normal file
View File

@@ -0,0 +1,102 @@
/*
* "dhcpaddr" match extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <net/ethernet.h>
#include <xtables.h>
#include "xt_DHCPADDR.h"
#include "mac.c"
enum {
F_MAC = 1 << 0,
};
static const struct option dhcpaddr_mt_opts[] = {
{.name = "mac", .has_arg = true, .val = 'M'},
{NULL},
};
static void dhcpaddr_mt_help(void)
{
printf(
"dhcpaddr match options:\n"
"[!] --mac lladdr[/mask] Match on MAC address in DHCP Client Host field\n"
);
}
static int dhcpaddr_mt_parse(int c, char **argv, int invert,
unsigned int *flags, const void *entry, struct xt_entry_match **match)
{
struct dhcpaddr_info *info = (void *)(*match)->data;
switch (c) {
case 'M':
param_act(P_ONLY_ONCE, "dhcpaddr", "--mac", *flags & F_MAC);
param_act(P_NO_INVERT, "dhcpaddr", "--mac", invert);
if (!mac_parse(optarg, info->addr, &info->mask))
param_act(P_BAD_VALUE, "dhcpaddr", "--mac", optarg);
if (invert)
info->invert = true;
*flags |= F_MAC;
return true;
}
return false;
}
static void dhcpaddr_mt_check(unsigned int flags)
{
if (flags == 0)
exit_error(PARAMETER_PROBLEM, "dhcpaddr match: "
"--mac parameter required");
}
static void dhcpaddr_mt_print(const void *ip,
const struct xt_entry_match *match, int numeric)
{
const struct dhcpaddr_info *info = (void *)match->data;
printf("dhcpaddr %s" DH_MAC_FMT "/%u ",
info->invert ? "!" : "", DH_MAC_HEX(info->addr), info->mask);
}
static void dhcpaddr_mt_save(const void *ip,
const struct xt_entry_match *match)
{
const struct dhcpaddr_info *info = (void *)match->data;
if (info->invert)
printf("! ");
printf("--mac " DH_MAC_FMT "/%u ",
DH_MAC_HEX(info->addr), info->mask);
}
static struct xtables_match dhcpaddr_mt_reg = {
.version = XTABLES_VERSION,
.name = "dhcpaddr",
.revision = 0,
.family = PF_INET,
.size = XT_ALIGN(sizeof(struct dhcpaddr_info)),
.userspacesize = XT_ALIGN(sizeof(struct dhcpaddr_info)),
.help = dhcpaddr_mt_help,
.parse = dhcpaddr_mt_parse,
.final_check = dhcpaddr_mt_check,
.print = dhcpaddr_mt_print,
.save = dhcpaddr_mt_save,
.extra_opts = dhcpaddr_mt_opts,
};
static void _init(void)
{
xtables_register_match(&dhcpaddr_mt_reg);
}

View File

@@ -0,0 +1,4 @@
.TP
\fB--mac\fP \fIaa:bb:cc:dd:ee:ff\fP[\fB/\fP\fImask\fP]
Matches the DHCP Client Host address in a DHCP message. \fImask\fP specifies
the prefix length of the initial portion to match.

118
extensions/libxt_fuzzy.c Normal file
View File

@@ -0,0 +1,118 @@
/*
* "fuzzy" match extension for iptables
* Hime Aguiar e Oliveira Jr. <hime@engineer.com>, 2002 - 2003
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License;
* either version 2 of the License, or any later version, as
* published by the Free Software Foundation.
*/
#include <getopt.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xtables.h>
#include "xt_fuzzy.h"
static void fuzzy_mt_help(void)
{
printf(
"fuzzy match options:\n"
" --lower-limit number (in packets per second)\n"
" --upper-limit number\n");
};
static const struct option fuzzy_mt_opts[] = {
{.name = "lower-limit", .has_arg = true, .val = '1'},
{.name = "upper-limit", .has_arg = true, .val = '2'},
{NULL},
};
/* Initialize data structures */
static void fuzzy_mt_init(struct xt_entry_match *m)
{
struct xt_fuzzy_mtinfo *info = (void *)m->data;
/*
* Default rates (I will improve this very soon with something based
* on real statistics of the running machine).
*/
info->minimum_rate = 1000;
info->maximum_rate = 2000;
}
#define IPT_FUZZY_OPT_MINIMUM 0x01
#define IPT_FUZZY_OPT_MAXIMUM 0x02
static int fuzzy_mt_parse(int c, char **argv, int invert, unsigned int *flags,
const void *entry, struct xt_entry_match **match)
{
struct xt_fuzzy_mtinfo *info = (void *)(*match)->data;
uint32_t num;
switch (c) {
case '1':
if (invert)
exit_error(PARAMETER_PROBLEM,"Can't specify ! --lower-limit");
if (*flags & IPT_FUZZY_OPT_MINIMUM)
exit_error(PARAMETER_PROBLEM,"Can't specify --lower-limit twice");
if (string_to_number(optarg,1,FUZZY_MAX_RATE,&num) == -1 || num < 1)
exit_error(PARAMETER_PROBLEM,"BAD --lower-limit");
info->minimum_rate = num;
*flags |= IPT_FUZZY_OPT_MINIMUM;
return true;
case '2':
if (invert)
exit_error(PARAMETER_PROBLEM,"Can't specify ! --upper-limit");
if (*flags & IPT_FUZZY_OPT_MAXIMUM)
exit_error(PARAMETER_PROBLEM,"Can't specify --upper-limit twice");
if (string_to_number(optarg,1,FUZZY_MAX_RATE,&num) == -1 || num < 1)
exit_error(PARAMETER_PROBLEM,"BAD --upper-limit");
info->maximum_rate = num;
*flags |= IPT_FUZZY_OPT_MAXIMUM;
return true;
}
return false;
}
static void fuzzy_mt_check(unsigned int flags)
{
}
static void fuzzy_mt_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_fuzzy_mtinfo *info = (const void *)match->data;
printf("fuzzy: lower limit = %u pps - upper limit = %u pps ",
info->minimum_rate, info->maximum_rate);
}
static void fuzzy_mt_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_fuzzy_mtinfo *info = (const void *)match->data;
printf("--lower-limit %u ", info->minimum_rate);
printf("--upper-limit %u ", info->maximum_rate);
}
static struct xtables_match fuzzy_mt_reg = {
.name = "fuzzy",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof(struct xt_fuzzy_mtinfo)),
.userspacesize = XT_ALIGN(sizeof(struct xt_fuzzy_mtinfo)),
.help = fuzzy_mt_help,
.init = fuzzy_mt_init,
.parse = fuzzy_mt_parse,
.final_check = fuzzy_mt_check,
.print = fuzzy_mt_print,
.save = fuzzy_mt_save,
.extra_opts = fuzzy_mt_opts,
};
static void _init(void)
{
xtables_register_match(&fuzzy_mt_reg);
}

View File

@@ -0,0 +1,7 @@
This module matches a rate limit based on a fuzzy logic controller (FLC).
.TP
\fB--lower-limit\fP \fInumber\fP
Specifies the lower limit, in packets per second.
.TP
\fB--upper-limit\fP \fInumber\fP
Specifies the upper limit, also in packets per second.

View File

@@ -1,16 +1,13 @@
/* Shared library add-on to iptables to add geoip match support.
/*
* "geoip" match extension for iptables
* Copyright © Samuel Jean <peejix [at] people netfilter org>, 2004 - 2008
* Copyright © Nicolas Bouliane <acidfu [at] people netfilter org>, 2004 - 2008
* Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (c) 2004, 2005, 2006, 2007, 2008
* Samuel Jean & Nicolas Bouliane
*
* For comments, bugs or suggestions, please contact
* Samuel Jean <peejix@people.netfilter.org>
* Nicolas Bouliane <peejix@people.netfilter.org>
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <sys/stat.h>
#include <sys/types.h>
@@ -20,6 +17,7 @@
#include <fcntl.h>
#include <getopt.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -175,35 +173,37 @@ static int geoip_parse(int c, char **argv, int invert, unsigned int *flags,
{
struct xt_geoip_match_info *info = (void *)(*match)->data;
switch(c) {
case '1':
// Ensure that XT_GEOIP_SRC *OR* XT_GEOIP_DST haven't been used yet.
switch (c) {
case '1':
if (*flags & (XT_GEOIP_SRC | XT_GEOIP_DST))
exit_error(PARAMETER_PROBLEM,
"geoip: only use --source-country *OR* --destination-country once!");
"geoip: Only exactly one of --source-country "
"or --destination-country must be specified!");
*flags |= XT_GEOIP_SRC;
break;
if (invert)
*flags |= XT_GEOIP_INV;
info->count = parse_geoip_cc(argv[optind-1], info->cc, info->mem);
info->flags = *flags;
return true;
case '2':
// Ensure that XT_GEOIP_SRC *OR* XT_GEOIP_DST haven't been used yet.
if (*flags & (XT_GEOIP_SRC | XT_GEOIP_DST))
exit_error(PARAMETER_PROBLEM,
"geoip: only use --source-country *OR* --destination-country once!");
"geoip: Only exactly one of --source-country "
"or --destination-country must be specified!");
*flags |= XT_GEOIP_DST;
break;
if (invert)
*flags |= XT_GEOIP_INV;
default:
return 0;
info->count = parse_geoip_cc(argv[optind-1], info->cc, info->mem);
info->flags = *flags;
return true;
}
if (invert)
*flags |= XT_GEOIP_INV;
info->count = parse_geoip_cc(argv[optind-1], info->cc, info->mem);
info->flags = *flags;
return 1;
return false;
}
static void

View File

@@ -1,3 +1,13 @@
/*
* "ipp2p" match extension for iptables
* Eicke Friedrich/Klaus Degner <ipp2p@ipp2p.org>, 2005 - 2006
* Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <stdbool.h>
#include <stdio.h>
#include <netdb.h>

View File

@@ -1,12 +1,14 @@
/*
* portscan target for Xtables
* Copyright © CC Computer Consultants GmbH, 2006 - 2008
* "portscan" match extension for iptables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2006 - 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License; either version
* 2 or 3 as published by the Free Software Foundation.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

139
extensions/libxt_quota2.c Normal file
View File

@@ -0,0 +1,139 @@
/*
* "quota2" match extension for iptables
* Sam Johnston <samj [at] samj net>
* Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <getopt.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <xtables.h>
#include "xt_quota2.h"
enum {
FL_QUOTA = 1 << 0,
FL_NAME = 1 << 1,
FL_GROW = 1 << 2,
FL_PACKET = 1 << 3,
};
static const struct option quota_mt2_opts[] = {
{.name = "grow", .has_arg = false, .val = 'g'},
{.name = "name", .has_arg = true, .val = 'n'},
{.name = "quota", .has_arg = true, .val = 'q'},
{.name = "packets", .has_arg = false, .val = 'p'},
{NULL},
};
static void quota_mt2_help(void)
{
printf(
"quota match options:\n"
" --grow provide an increasing counter\n"
" --name name name for the file in sysfs\n"
"[!] --quota quota initial quota (bytes or packets)\n"
" --packets count packets instead of bytes\n"
);
}
static int
quota_mt2_parse(int c, char **argv, int invert, unsigned int *flags,
const void *entry, struct xt_entry_match **match)
{
struct xt_quota_mtinfo2 *info = (void *)(*match)->data;
char *end;
switch (c) {
case 'g':
param_act(P_ONLY_ONCE, "quota", "--grow", *flags & FL_GROW);
param_act(P_NO_INVERT, "quota", "--grow", invert);
info->flags |= XT_QUOTA_GROW;
*flags |= FL_GROW;
return true;
case 'n':
/* zero termination done on behalf of the kernel module */
param_act(P_ONLY_ONCE, "quota", "--name", *flags & FL_NAME);
param_act(P_NO_INVERT, "quota", "--name", invert);
strncpy(info->name, optarg, sizeof(info->name));
*flags |= FL_NAME;
return true;
case 'p':
param_act(P_ONLY_ONCE, "quota", "--packets", *flags & FL_PACKET);
param_act(P_NO_INVERT, "quota", "--packets", invert);
info->flags |= XT_QUOTA_PACKET;
*flags |= FL_PACKET;
return true;
case 'q':
param_act(P_ONLY_ONCE, "quota", "--quota", *flags & FL_QUOTA);
if (invert)
info->flags |= XT_QUOTA_INVERT;
info->quota = strtoull(optarg, &end, 0);
if (*end != '\0')
exit_error(PARAMETER_PROBLEM, "quota match: "
"invalid value for --quota");
*flags |= FL_QUOTA;
return true;
}
return false;
}
static void
quota_mt2_save(const void *ip, const struct xt_entry_match *match)
{
const struct xt_quota_mtinfo2 *q = (void *)match->data;
if (q->flags & XT_QUOTA_INVERT)
printf("! ");
if (q->flags & XT_QUOTA_GROW)
printf("--grow ");
if (q->flags & XT_QUOTA_PACKET)
printf("--packets ");
if (*q->name != '\0')
printf("--name %s ", q->name);
printf("--quota %llu ", (unsigned long long)q->quota);
}
static void quota_mt2_print(const void *ip, const struct xt_entry_match *match,
int numeric)
{
const struct xt_quota_mtinfo2 *q = (const void *)match->data;
if (q->flags & XT_QUOTA_INVERT)
printf("! ");
if (q->flags & XT_QUOTA_GROW)
printf("counter");
else
printf("quota");
if (*q->name != '\0')
printf(" %s:", q->name);
printf(" %llu ", (unsigned long long)q->quota);
if (q->flags & XT_QUOTA_PACKET)
printf("packets ");
else
printf("bytes ");
}
static struct xtables_match quota_mt2_reg = {
.family = AF_UNSPEC,
.revision = 2,
.name = "quota2",
.version = XTABLES_VERSION,
.size = XT_ALIGN(sizeof (struct xt_quota_mtinfo2)),
.userspacesize = offsetof(struct xt_quota_mtinfo2, quota),
.help = quota_mt2_help,
.parse = quota_mt2_parse,
.print = quota_mt2_print,
.save = quota_mt2_save,
.extra_opts = quota_mt2_opts,
};
static void _init(void)
{
xtables_register_match(&quota_mt2_reg);
}

View File

@@ -0,0 +1,31 @@
The "quota2" implements a named counter which can be increased or decreased
on a per-match basis. Available modes are packet counting or byte counting.
The value of the counter can be read and reset through procfs, thereby making
this match a minimalist accounting tool.
.PP
When counting down from the initial quota, the counter will stop at 0 and
the match will return false, just like the original "quota" match. In growing
(upcounting) mode, it will always return true.
.TP
\fB--grow\fP
Count upwards instead of downwards.
.TP
\fB--name\fP \fIname\fP
Assign the counter a specific name. This option must be present, as an empty
name is not allowed. Names starting with a dot or names containing a slash are
prohibited.
.TP
[\fB!\fP] \fB--quota\fP \fIiq\fP
Specify the initial quota for this counter. If the counter already exists,
it is not reset. An "!" may be used to invert the result of the match. The
negation has no effect when \fB--grow\fP is used.
.TP
\fB--packets\fP
Count packets instead of bytes that passed the quota2 match.
.PP
Because counters in quota2 can be shared, you can combine them for various
purposes, for example, a bytebucket filter that only lets as much traffic go
out as has come in:
.PP
-A INPUT -p tcp --dport 6881 -m quota --name bt --grow
-A OUTPUT -p tcp --sport 6881 -m quota --name bt

29
extensions/mac.c Normal file
View File

@@ -0,0 +1,29 @@
static bool mac_parse(const char *addr, unsigned char *dest, uint8_t *mask)
{
unsigned int i = 0, value;
char *end;
for (i = 0; i < ETH_ALEN; ++i) {
value = strtoul(addr, &end, 16);
if (addr == end || value > 0xFF)
return false;
if (i == ETH_ALEN - 1) {
if (*end != '\0' && *end != '/')
return false;
} else if (*end != ':') {
return false;
}
dest[i] = value;
addr = end + 1;
}
*mask = 48;
if (*end == '/') {
if (!strtonum(end + 1, &end, &value, 0, 48))
return false;
if (*end != '\0')
return false;
}
return true;
}

View File

@@ -1,11 +1,11 @@
/*
* CHAOS target for netfilter
* Copyright © CC Computer Consultants GmbH, 2006 - 2007
* Contact: Jan Engelhardt <jengelh@computergmbh.de>
* "CHAOS" target extension for Xtables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2006 - 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License; either version
* 2 or 3 as published by the Free Software Foundation.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <linux/icmp.h>
#include <linux/in.h>
@@ -72,12 +72,11 @@ static void xt_chaos_total(const struct xt_chaos_tginfo *info,
#else
destiny->target(skb, in, out, hooknum, destiny, NULL);
#endif
return;
}
static unsigned int chaos_tg(struct sk_buff *skb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
static unsigned int chaos_tg(struct sk_buff **pskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *target, const void *targinfo)
{
/*
* Equivalent to:
@@ -88,18 +87,19 @@ static unsigned int chaos_tg(struct sk_buff *skb, const struct net_device *in,
* -A chaos -j DROP;
*/
const struct xt_chaos_tginfo *info = targinfo;
struct sk_buff *skb = *pskb;
const struct iphdr *iph = ip_hdr(skb);
if ((unsigned int)net_random() <= reject_percentage)
#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 18)
return xt_reject->target(&skb, in, out, hooknum,
return xt_reject->target(pskb, in, out, hooknum,
target->__compat_target, &reject_params, NULL);
#elif LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 23)
return xt_reject->target(&skb, in, out, hooknum,
return xt_reject->target(pskb, in, out, hooknum,
target->__compat_target, &reject_params);
#else
return xt_reject->target(skb, in, out, hooknum, target,
&reject_params);
return xt_reject->target(skb, in, out, hooknum,
target->__compat_target, &reject_params);
#endif
/* TARPIT/DELUDE may not be called from the OUTPUT chain */
@@ -199,7 +199,6 @@ static void __exit chaos_tg_exit(void)
module_put(xt_delude->me);
if (have_tarpit)
module_put(xt_tarpit->me);
return;
}
module_init(chaos_tg_init);

View File

@@ -1,6 +1,6 @@
/*
* DELUDE target
* Copyright © CC Computer Consultants GmbH, 2007 - 2008
* "DELUDE" target extension for Xtables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2007 - 2008
*
* Based upon linux-2.6.18.5/net/ipv4/netfilter/ipt_REJECT.c:
* (C) 1999-2001 Paul `Rusty' Russell
@@ -122,8 +122,10 @@ static void delude_send_reset(struct sk_buff *oldskb, unsigned int hook)
dst_hold(oldskb->dst);
nskb->dst = oldskb->dst;
if (ip_route_me_harder(nskb, addr_type))
if (ip_route_me_harder(&nskb, addr_type))
goto free_nskb;
else
niph = ip_hdr(nskb);
niph->ttl = dst_metric(nskb->dst, RTAX_HOPLIMIT);
nskb->ip_summed = CHECKSUM_NONE;
@@ -141,14 +143,14 @@ static void delude_send_reset(struct sk_buff *oldskb, unsigned int hook)
kfree_skb(nskb);
}
static unsigned int delude_tg(struct sk_buff *skb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
static unsigned int delude_tg(struct sk_buff **pskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *target, const void *targinfo)
{
/* WARNING: This code causes reentry within iptables.
This means that the iptables jump stack is now crap. We
must return an absolute verdict. --RR */
delude_send_reset(skb, hooknum);
delude_send_reset(*pskb, hooknum);
return NF_DROP;
}

175
extensions/xt_DHCPADDR.c Normal file
View File

@@ -0,0 +1,175 @@
/*
* "DHCPADDR" extensions for Xtables
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <linux/ip.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/types.h>
#include <linux/udp.h>
#include <net/ip.h>
#include <linux/netfilter/x_tables.h>
#include "xt_DHCPADDR.h"
#include "compat_xtables.h"
struct dhcp_message {
uint8_t op, htype, hlen, hops;
__be32 xid;
__be16 secs, flags;
__be32 ciaddr, yiaddr, siaddr, giaddr;
char chaddr[16];
/* Omitting all unneeded fields saves runtime memory */
/* char sname[64], file[128]; */
};
static void ether_set(unsigned char *addr, const unsigned char *op,
uint8_t mask)
{
uint8_t lo_mask;
unsigned int i;
for (i = 0; i < ETH_ALEN && mask > 0; ++i) {
lo_mask = mask % 8;
/* FF << 4 >> 4 = 0F */
lo_mask = ~(uint8_t)0U << lo_mask >> lo_mask;
addr[i] &= lo_mask;
addr[i] |= op[i] & ~lo_mask;
if (mask >= 8)
mask -= 8;
else
mask = 0;
}
}
static bool ether_cmp(const unsigned char *lh, const unsigned char *rh,
uint8_t mask)
{
uint8_t lo_mask;
unsigned int i;
#define ZMAC_FMT "%02X:%02X:%02X:%02X:%02X:%02X"
#define ZMACHEX(s) s[0], s[1], s[2], s[3], s[4], s[5]
for (i = 0; i < ETH_ALEN && mask > 0; ++i) {
lo_mask = mask % 8;
/* ~(0xFF << 4 >> 4) = ~0x0F = 0xF0 */
lo_mask = ~(~(uint8_t)0U << lo_mask >> lo_mask);
if ((lh[i] ^ rh[i]) & lo_mask)
return false;
if (mask >= 8)
mask -= 8;
else
mask = 0;
}
return true;
}
static bool dhcpaddr_mt(const struct sk_buff *skb, const struct net_device *in,
const struct net_device *out, const struct xt_match *match,
const void *matchinfo, int offset, unsigned int protoff, bool *hotdrop)
{
const struct dhcpaddr_info *info = matchinfo;
const struct dhcp_message *dh;
struct dhcp_message dhcpbuf;
dh = skb_header_pointer(skb, protoff + sizeof(struct udphdr),
sizeof(dhcpbuf), &dhcpbuf);
if (dh == NULL)
/*
* No hotdrop. This packet does not look like DHCP, but other
* matches may still have a valid reason to get their chance
* to match on this.
*/
return false;
return ether_cmp((const void *)dh->chaddr, info->addr, info->mask);
}
static unsigned int dhcpaddr_tg(struct sk_buff **pskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *target, const void *targinfo)
{
const struct dhcpaddr_info *info = targinfo;
struct dhcp_message dhcpbuf, *dh;
struct udphdr udpbuf, *udph;
struct sk_buff *skb = *pskb;
unsigned int i;
if (!skb_make_writable(pskb, 0))
return NF_DROP;
udph = skb_header_pointer(skb, ip_hdrlen(skb),
sizeof(udpbuf), &udpbuf);
if (udph == NULL)
return NF_DROP;
dh = skb_header_pointer(skb, ip_hdrlen(skb) + sizeof(udpbuf),
sizeof(dhcpbuf), &dhcpbuf);
if (dh == NULL)
return NF_DROP;
for (i = 0; i < sizeof(dh->chaddr); i += 2)
csum_replace2(&udph->check, *(const __be16 *)dh->chaddr, 0);
memset(dh->chaddr, 0, sizeof(dh->chaddr));
ether_set(dh->chaddr, info->addr, info->mask);
for (i = 0; i < sizeof(dh->chaddr); i += 2)
csum_replace2(&udph->check, 0, *(const __be16 *)dh->chaddr);
return XT_CONTINUE;
}
static struct xt_target dhcpaddr_tg_reg __read_mostly = {
.name = "DHCPADDR",
.revision = 0,
.family = PF_INET,
.proto = IPPROTO_UDP,
.table = "mangle",
.target = dhcpaddr_tg,
.targetsize = XT_ALIGN(sizeof(struct dhcpaddr_info)),
.me = THIS_MODULE,
};
static struct xt_match dhcpaddr_mt_reg __read_mostly = {
.name = "dhcpaddr",
.revision = 0,
.family = PF_INET,
.proto = IPPROTO_UDP,
.match = dhcpaddr_mt,
.matchsize = XT_ALIGN(sizeof(struct dhcpaddr_info)),
.me = THIS_MODULE,
};
static int __init dhcpaddr_init(void)
{
int ret;
ret = xt_register_target(&dhcpaddr_tg_reg);
if (ret != 0)
return ret;
ret = xt_register_match(&dhcpaddr_mt_reg);
if (ret != 0) {
xt_unregister_target(&dhcpaddr_tg_reg);
return ret;
}
return 0;
}
static void __exit dhcpaddr_exit(void)
{
xt_unregister_target(&dhcpaddr_tg_reg);
xt_unregister_match(&dhcpaddr_mt_reg);
}
module_init(dhcpaddr_init);
module_exit(dhcpaddr_exit);
MODULE_DESCRIPTION("Xtables: Clamp DHCP MAC to packet MAC addresses");
MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_DHCPADDR");
MODULE_ALIAS("ipt_dhcpaddr");

12
extensions/xt_DHCPADDR.h Normal file
View File

@@ -0,0 +1,12 @@
#ifndef _LINUX_NETFILTER_XT_DHCPADDR_H
#define _LINUX_NETFILTER_XT_DHCPADDR_H 1
#define DH_MAC_FMT "%02X:%02X:%02X:%02X:%02X:%02X"
#define DH_MAC_HEX(z) z[0], z[1], z[2], z[3], z[4], z[5]
struct dhcpaddr_info {
unsigned char addr[ETH_ALEN];
uint8_t mask, invert;
};
#endif /* _LINUX_NETFILTER_XT_DHCPADDR_H */

View File

@@ -1,11 +1,14 @@
/*
* ECHO target (RFC 862)
* Copyright © CC Computer Consultants GmbH, 2008
* "ECHO" (RFC 862) target extension for Xtables
* Sample module for "Writing your own Netfilter Modules"
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 or 3 as published by the Free Software Foundation.
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <linux/ip.h>
#include <linux/module.h>
#include <linux/skbuff.h>
@@ -17,10 +20,11 @@
#include <net/ip.h>
#include "compat_xtables.h"
static unsigned int echo_tg4(struct sk_buff *oldskb,
static unsigned int echo_tg4(struct sk_buff **poldskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *target, const void *targinfo)
{
const struct sk_buff *oldskb = *poldskb;
const struct udphdr *oldudp;
const struct iphdr *oldip;
struct udphdr *newudp, oldudp_buf;

View File

@@ -1,3 +1,13 @@
/*
* "IPMARK" target extension for Xtables
* Copyright © Grzegorz Janoszka <Grzegorz.Janoszka@pro.onet.pl>, 2003
* Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/module.h>
@@ -15,11 +25,12 @@ MODULE_ALIAS("ipt_IPMARK");
MODULE_ALIAS("ip6t_IPMARK");
static unsigned int
ipmark_tg4(struct sk_buff *skb, const struct net_device *in,
ipmark_tg4(struct sk_buff **pskb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
{
const struct xt_ipmark_tginfo *ipmarkinfo = targinfo;
const struct sk_buff *skb = *pskb;
const struct iphdr *iph = ip_hdr(skb);
__u32 mark;
@@ -52,11 +63,12 @@ static __u32 ipmark_from_ip6(const struct in6_addr *a, unsigned int s)
}
static unsigned int
ipmark_tg6(struct sk_buff *skb, const struct net_device *in,
ipmark_tg6(struct sk_buff **pskb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
{
const struct xt_ipmark_tginfo *info = targinfo;
const struct sk_buff *skb = *pskb;
const struct ipv6hdr *iph = ipv6_hdr(skb);
__u32 mark;

View File

@@ -1,19 +1,19 @@
/*
* xt_LOGMARK - netfilter mark logging
* "LOGMARK" target extension to Xtables
* useful for debugging
*
* Copyright © CC Computer Consultants, 2007 - 2008
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 or 3 as published by the Free Software Foundation.
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or any later version, as published by the
* Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netfilter/nf_conntrack_common.h>
#include <linux/netfilter/x_tables.h>
//#include <net/netfilter/nf_conntrack.h>
#include "compat_xtables.h"
#include "xt_LOGMARK.h"
@@ -30,10 +30,11 @@ static const char *const dir_names[] = {
};
static unsigned int
logmark_tg(struct sk_buff *skb, const struct net_device *in,
logmark_tg(struct sk_buff **pskb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
{
const struct sk_buff *skb = *pskb;
const struct xt_logmark_tginfo *info = targinfo;
const struct nf_conn *ct;
enum ip_conntrack_info ctinfo;
@@ -42,7 +43,7 @@ logmark_tg(struct sk_buff *skb, const struct net_device *in,
printk("<%u>%.*s""hook=%s nfmark=0x%x secmark=0x%x classify=0x%x",
info->level, (unsigned int)sizeof(info->prefix), info->prefix,
hook_names[hooknum],
skb_nfmark(skb), skb->secmark, skb->priority);
skb_nfmark(skb), skb_secmark(skb), skb->priority);
ct = nf_ct_get(skb, &ctinfo);
printk(" ctdir=%s", dir_names[ctinfo >= IP_CT_IS_REPLY]);

View File

@@ -0,0 +1,8 @@
config NETFILTER_XT_TARGET_SYSRQ
tristate '"SYSRQ" target support'
depends on NETFILTER_XTABLES && NETFILTER_ADVANCED
---help---
The SYSRQ target allows to remotely trigger sysrq on the
local machine over the network. This can be useful when vital
parts of the machine hang and sysrq cannot be triggered
through, for example, the shell.

166
extensions/xt_SYSRQ.c Normal file
View File

@@ -0,0 +1,166 @@
/*
* "SYSRQ" target extension for Netfilter
* Copyright © Jan Engelhardt <jengelh [at] medozas de>, 2008
*
* Based upon the ipt_SYSRQ idea by Marek Zalem <marek [at] terminus sk>
* xt_SYSRQ does not use hashing or timestamps.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 or 3 as published by the Free Software Foundation.
*/
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/sysrq.h>
#include <linux/udp.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter/x_tables.h>
#include <net/ip.h>
#include "compat_xtables.h"
static bool sysrq_once;
static char sysrq_password[64];
module_param_string(password, sysrq_password, sizeof(sysrq_password),
S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(password, "password for remote sysrq");
static unsigned int sysrq_tg(const void *pdata, uint16_t len)
{
const char *data = pdata;
char c;
if (*sysrq_password == '\0') {
if (!sysrq_once)
printk(KERN_INFO KBUILD_MODNAME "No password set\n");
sysrq_once = true;
return NF_DROP;
}
if (len == 0)
return NF_DROP;
c = *data;
if (strncmp(&data[1], sysrq_password, len - 1) != 0) {
printk(KERN_INFO KBUILD_MODNAME "Failed attempt - "
"password mismatch\n");
return NF_DROP;
}
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 19)
handle_sysrq(c, NULL);
#else
handle_sysrq(c, NULL, NULL);
#endif
return NF_ACCEPT;
}
static unsigned int sysrq_tg4(struct sk_buff **pskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *target, const void *targinfo)
{
struct sk_buff *skb = *pskb;
const struct iphdr *iph;
const struct udphdr *udph;
uint16_t len;
if (skb_linearize(skb) < 0)
return NF_DROP;
iph = ip_hdr(skb);
udph = (void *)iph + ip_hdrlen(skb);
len = ntohs(udph->len) - sizeof(struct udphdr);
printk(KERN_INFO KBUILD_MODNAME ": " NIPQUAD_FMT ":%u -> :%u len=%u\n",
NIPQUAD(iph->saddr), htons(udph->source), htons(udph->dest),
len);
return sysrq_tg((void *)udph + sizeof(struct udphdr), len);
}
static unsigned int sysrq_tg6(struct sk_buff **pskb,
const struct net_device *in, const struct net_device *out,
unsigned int hooknum, const struct xt_target *target, const void *targinfo)
{
struct sk_buff *skb = *pskb;
const struct ipv6hdr *iph;
const struct udphdr *udph;
uint16_t len;
if (skb_linearize(skb) < 0)
return NF_DROP;
iph = ipv6_hdr(skb);
udph = udp_hdr(skb);
len = ntohs(udph->len) - sizeof(struct udphdr);
printk(KERN_INFO KBUILD_MODNAME ": " NIP6_FMT ":%hu -> :%hu len=%u\n",
NIP6(iph->saddr), ntohs(udph->source),
ntohs(udph->dest), len);
return sysrq_tg(udph + sizeof(struct udphdr), len);
}
static bool sysrq_tg_check(const char *table, const void *ventry,
const struct xt_target *target, void *targinfo, unsigned int hook_mask)
{
if (target->family == PF_INET) {
const struct ipt_entry *entry = ventry;
if ((entry->ip.proto != IPPROTO_UDP &&
entry->ip.proto != IPPROTO_UDPLITE) ||
entry->ip.invflags & XT_INV_PROTO)
goto out;
} else if (target->family == PF_INET6) {
const struct ip6t_entry *entry = ventry;
if ((entry->ipv6.proto != IPPROTO_UDP &&
entry->ipv6.proto != IPPROTO_UDPLITE) ||
entry->ipv6.invflags & XT_INV_PROTO)
goto out;
}
return true;
out:
printk(KERN_ERR KBUILD_MODNAME ": only available for UDP and UDP-Lite");
return false;
}
static struct xt_target sysrq_tg_reg[] __read_mostly = {
{
.name = "SYSRQ",
.family = PF_INET,
.revision = 0,
.target = sysrq_tg4,
.checkentry = sysrq_tg_check,
.me = THIS_MODULE,
},
{
.name = "SYSRQ",
.family = PF_INET6,
.revision = 0,
.target = sysrq_tg6,
.checkentry = sysrq_tg_check,
.me = THIS_MODULE,
},
};
static int __init sysrq_tg_init(void)
{
return xt_register_targets(sysrq_tg_reg, ARRAY_SIZE(sysrq_tg_reg));
}
static void __exit sysrq_tg_exit(void)
{
return xt_unregister_targets(sysrq_tg_reg, ARRAY_SIZE(sysrq_tg_reg));
}
module_init(sysrq_tg_init);
module_exit(sysrq_tg_exit);
MODULE_DESCRIPTION("Xtables: triggering SYSRQ remotely");
MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_SYSRQ");
MODULE_ALIAS("ip6t_SYSRQ");

View File

@@ -1,25 +1,28 @@
/*
* Kernel module to capture and hold incoming TCP connections using
* no local per-connection resources.
* "TARPIT" target extension to Xtables
* Kernel module to capture and hold incoming TCP connections using
* no local per-connection resources.
*
* Based on ipt_REJECT.c and offering functionality similar to
* LaBrea <http://www.hackbusters.net/LaBrea/>.
* Copyright © Aaron Hopkins <tools [at] die net>, 2002
*
* Copyright (c) 2002 Aaron Hopkins <tools@die.net>
* Based on ipt_REJECT.c and offering functionality similar to
* LaBrea <http://www.hackbusters.net/LaBrea/>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <<<
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* >>>
*
* Goal:
* - Allow incoming TCP connections to be established.
@@ -46,7 +49,7 @@
#include <net/tcp.h>
#include "compat_xtables.h"
static inline void tarpit_tcp(struct sk_buff *oldskb, unsigned int hook)
static void tarpit_tcp(struct sk_buff *oldskb, unsigned int hook)
{
struct tcphdr _otcph, *oth, *tcph;
unsigned int addr_type;
@@ -154,8 +157,10 @@ static inline void tarpit_tcp(struct sk_buff *oldskb, unsigned int hook)
#endif
addr_type = RTN_LOCAL;
if (ip_route_me_harder(nskb, addr_type))
if (ip_route_me_harder(&nskb, addr_type))
goto free_nskb;
else
niph = ip_hdr(nskb);
nskb->ip_summed = CHECKSUM_NONE;
@@ -181,10 +186,11 @@ static inline void tarpit_tcp(struct sk_buff *oldskb, unsigned int hook)
}
static unsigned int
tarpit_tg(struct sk_buff *skb, const struct net_device *in,
tarpit_tg(struct sk_buff **pskb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
{
const struct sk_buff *skb = *pskb;
const struct iphdr *iph = ip_hdr(skb);
const struct rtable *rt = (const void *)skb->dst;
@@ -212,7 +218,7 @@ tarpit_tg(struct sk_buff *skb, const struct net_device *in,
if (iph->frag_off & htons(IP_OFFSET))
return NF_DROP;
tarpit_tcp(skb, hooknum);
tarpit_tcp(*pskb, hooknum);
return NF_DROP;
}

View File

@@ -1,12 +1,14 @@
/*
* This implements the TEE target.
* "TEE" target extension for Xtables
* Copyright © Sebastian Claßen <sebastian.classen [at] freenet de>, 2007
* Jan Engelhardt <jengelh [at] medozas de>, 2007
*
* Copyright (C) 2007 Sebastian Claßen <sebastian.classen@freenet.de> and
* CC Computer Consultants GmbH, 2007
* based on ipt_ROUTE.c from Cédric de Launois
* <delaunois [at] info ucl ac be>
*
* based on ipt_ROUTE.c from Cédric de Launois <delaunois@info.ucl.ac.be>
*
* This software is distributed under GNU GPL v2, 1991
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2, as published by the Free Software Foundation.
*/
#include <linux/ip.h>
#include <linux/module.h>
@@ -140,11 +142,12 @@ static void tee_ip_direct_send(struct sk_buff *skb)
* packets when we see they already have that ->nfct.
*/
static unsigned int
tee_tg(struct sk_buff *skb, const struct net_device *in,
tee_tg(struct sk_buff **pskb, const struct net_device *in,
const struct net_device *out, unsigned int hooknum,
const struct xt_target *target, const void *targinfo)
{
const struct xt_tee_tginfo *info = targinfo;
struct sk_buff *skb = *pskb;
#ifdef WITH_CONNTRACK
if (skb->nfct == &tee_track.ct_general) {
@@ -158,8 +161,9 @@ tee_tg(struct sk_buff *skb, const struct net_device *in,
}
#endif
if (!skb_make_writable(skb, sizeof(struct iphdr)))
if (!skb_make_writable(pskb, sizeof(struct iphdr)))
return NF_DROP;
skb = *pskb;
/*
* If we are in INPUT, the checksum must be recalculated since

View File

@@ -1,14 +1,16 @@
/*
* xt_condition
* "condition" match extension for Xtables
*
* Description: This module allows firewall rules to match using
* condition variables available through procfs.
*
* Authors:
* Stephane Ouellette <ouellettes@videotron.ca>, 2002-10-22
* Massimiliano Hofer <max@nucleus.it>, 2006-05-15
* Stephane Ouellette <ouellettes [at] videotron ca>, 2002-10-22
* Massimiliano Hofer <max [at] nucleus it>, 2006-05-15
*
* This software is distributed under the terms of the GNU GPL.
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License; either version 2
* or 3 of the License, as published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/list.h>
@@ -25,9 +27,6 @@
#ifndef CONFIG_PROC_FS
# error "proc file system support is required for this module"
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 24)
# define proc_net init_net.proc_net
#endif
/* Defaults, these can be overridden on the module command-line. */
static unsigned int condition_list_perms = S_IRUGO | S_IWUSR;
@@ -157,7 +156,8 @@ condition_mt_check(const char *tablename, const void *entry,
}
/* Create the condition variable's proc file entry. */
var->status_proc = create_proc_entry(info->name, condition_list_perms, proc_net_condition);
var->status_proc = create_proc_entry(info->name, condition_list_perms,
proc_net_condition);
if (var->status_proc == NULL) {
kfree(var);
@@ -236,13 +236,13 @@ static int __init condition_mt_init(void)
{
int ret;
proc_net_condition = proc_mkdir(dir_name, proc_net);
proc_net_condition = proc_mkdir(dir_name, init_net__proc_net);
if (proc_net_condition == NULL)
return -EACCES;
ret = xt_register_matches(condition_mt_reg, ARRAY_SIZE(condition_mt_reg));
if (ret < 0) {
remove_proc_entry(dir_name, proc_net);
remove_proc_entry(dir_name, init_net__proc_net);
return ret;
}
@@ -252,7 +252,7 @@ static int __init condition_mt_init(void)
static void __exit condition_mt_exit(void)
{
xt_unregister_matches(condition_mt_reg, ARRAY_SIZE(condition_mt_reg));
remove_proc_entry(dir_name, proc_net);
remove_proc_entry(dir_name, init_net__proc_net);
}
module_init(condition_mt_init);

View File

@@ -0,0 +1,6 @@
config NETFILTER_XT_MATCH_FUZZY
tristate '"fuzzy" match support'
depends on NETFILTER_XTABLES && NETFILTER_ADVANCED
---help---
This extension allows you to match on packets according to a fuzzy
logic based law.

179
extensions/xt_fuzzy.c Normal file
View File

@@ -0,0 +1,179 @@
/*
* This module implements a simple TSK FLC (Takagi-Sugeno-Kang Fuzzy Logic
* Controller) that aims to limit, in an adaptive and flexible way, the
* packet rate crossing a given stream. It serves as an initial and very
* simple (but effective) example of how Fuzzy Logic techniques can be
* applied to defeat DoS attacks.
*
* As a matter of fact, Fuzzy Logic can help us to insert any "behavior"
* into our code in a precise, adaptive and efficient manner.
*
* The goal is very similar to that of "limit" match, but using techniques
* of Fuzzy Control, that allow us to shape the transfer functions
* precisely, avoiding over and undershoots - and stuff like that.
*
* 2002-08-10 Hime Aguiar e Oliveira Jr. <hime@engineer.com> : Initial version.
* 2002-08-17 : Changed to eliminate floating point operations .
* 2002-08-23 : Coding style changes .
* 2003-04-08 Maciej Soltysiak <solt@dns.toxicilms.tv> : IPv6 Port
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/random.h>
#include <net/tcp.h>
#include <linux/netfilter/x_tables.h>
#include "xt_fuzzy.h"
#include "compat_xtables.h"
/*
* Packet Acceptance Rate - LOW and Packet Acceptance Rate - HIGH
* Expressed in percentage.
*/
#define PAR_LOW 1/100
#define PAR_HIGH 1
MODULE_AUTHOR("Hime Aguiar e Oliveira Junior <hime@engineer.com>");
MODULE_DESCRIPTION("Xtables: Fuzzy Logic Controller match");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_fuzzy");
MODULE_ALIAS("ip6t_fuzzy");
static uint8_t mf_high(uint32_t tx, uint32_t mini, uint32_t maxi)
{
if (tx >= maxi)
return 100;
if (tx <= mini)
return 0;
return 100 * (tx - mini) / (maxi - mini);
}
static uint8_t mf_low(uint32_t tx, uint32_t mini, uint32_t maxi)
{
if (tx <= mini)
return 100;
if (tx >= maxi)
return 0;
return 100 * (maxi - tx) / (maxi - mini);
}
static bool
fuzzy_mt(const struct sk_buff *skb, const struct net_device *in,
const struct net_device *out, const struct xt_match *match,
const void *matchinfo, int offset, unsigned int protoff,
bool *hotdrop)
{
struct xt_fuzzy_mtinfo *info = (void *)matchinfo;
unsigned long amount;
uint8_t howhigh, howlow, random_number;
info->bytes_total += skb->len;
++info->packets_total;
info->present_time = jiffies;
if (info->present_time >= info->previous_time) {
amount = info->present_time - info->previous_time;
} else {
/*
* There was a transition: I choose to re-sample
* and keep the old acceptance rate...
*/
amount = 0;
info->previous_time = info->present_time;
info->bytes_total = info->packets_total = 0;
}
if (amount > HZ / 10) {
/* More than 100 ms elapsed ... */
info->mean_rate = HZ * info->packets_total / amount;
info->previous_time = info->present_time;
info->bytes_total = info->packets_total = 0;
howhigh = mf_high(info->mean_rate, info->minimum_rate,
info->maximum_rate);
howlow = mf_low(info->mean_rate, info->minimum_rate,
info->maximum_rate);
info->acceptance_rate = howhigh * PAR_LOW + PAR_HIGH * howlow;
/*
* In fact, the above defuzzification would require a
* denominator proportional to (howhigh+howlow) but, in this
* particular case, that expression is constant.
*
* An imediate consequence is that it is not necessary to call
* both mf_high and mf_low - but to keep things understandable,
* I did so.
*/
}
if (info->acceptance_rate < 100) {
get_random_bytes(&random_number, sizeof(random_number));
if (random_number <= 255 * info->acceptance_rate / 100)
/*
* If within the acceptance, it can pass
* => do not match.
*/
return false;
else
/* It cannot pass (it matches) */
return true;
};
/* acceptance_rate == 100 % => Everything passes ... */
return false;
}
static bool
fuzzy_mt_check(const char *table, const void *ip, const struct xt_match *match,
void *matchinfo, unsigned int hook_mask)
{
const struct xt_fuzzy_mtinfo *info = matchinfo;
if (info->minimum_rate < FUZZY_MIN_RATE ||
info->maximum_rate > FUZZY_MAX_RATE ||
info->minimum_rate >= info->maximum_rate) {
printk(KERN_INFO KBUILD_MODNAME ": bad values, please check.\n");
return false;
}
return true;
}
static struct xt_match fuzzy_mt_reg[] __read_mostly = {
{
.name = "fuzzy",
.revision = 0,
.family = PF_INET,
.match = fuzzy_mt,
.checkentry = fuzzy_mt_check,
.matchsize = XT_ALIGN(sizeof(struct xt_fuzzy_mtinfo)),
.me = THIS_MODULE,
},
{
.name = "fuzzy",
.revision = 0,
.family = PF_INET6,
.match = fuzzy_mt,
.checkentry = fuzzy_mt_check,
.matchsize = XT_ALIGN(sizeof(struct xt_fuzzy_mtinfo)),
.me = THIS_MODULE,
},
};
static int __init fuzzy_mt_init(void)
{
return xt_register_matches(fuzzy_mt_reg, ARRAY_SIZE(fuzzy_mt_reg));
}
static void __exit fuzzy_mt_exit(void)
{
xt_unregister_matches(fuzzy_mt_reg, ARRAY_SIZE(fuzzy_mt_reg));
}
module_init(fuzzy_mt_init);
module_exit(fuzzy_mt_exit);

20
extensions/xt_fuzzy.h Normal file
View File

@@ -0,0 +1,20 @@
#ifndef _LINUX_NETFILTER_XT_FUZZY_H
#define _LINUX_NETFILTER_XT_FUZZY_H 1
enum {
FUZZY_MIN_RATE = 3,
FUZZY_MAX_RATE = 10000000,
};
struct xt_fuzzy_mtinfo {
uint32_t minimum_rate;
uint32_t maximum_rate;
uint32_t packets_total;
uint32_t bytes_total;
uint32_t previous_time;
uint32_t present_time;
uint32_t mean_rate;
uint8_t acceptance_rate;
};
#endif /* _LINUX_NETFILTER_XT_FUZZY_H */

View File

@@ -1,6 +1,6 @@
#ifndef __IPT_IPP2P_H
#define __IPT_IPP2P_H
#define IPP2P_VERSION "0.8.1_rc1"
#define IPP2P_VERSION "0.9"
enum {
IPP2N_EDK,

View File

@@ -232,31 +232,44 @@ static bool portscan_mt_check(const char *tablename, const void *entry,
return true;
}
static struct xt_match portscan_mt_reg __read_mostly = {
.name = "portscan",
.revision = 0,
.family = AF_INET,
.match = portscan_mt,
.checkentry = portscan_mt_check,
.matchsize = sizeof(struct xt_portscan_mtinfo),
.proto = IPPROTO_TCP,
.me = THIS_MODULE,
static struct xt_match portscan_mt_reg[] __read_mostly = {
{
.name = "portscan",
.revision = 0,
.family = PF_INET,
.match = portscan_mt,
.checkentry = portscan_mt_check,
.matchsize = sizeof(struct xt_portscan_mtinfo),
.proto = IPPROTO_TCP,
.me = THIS_MODULE,
},
{
.name = "portscan",
.revision = 0,
.family = PF_INET6,
.match = portscan_mt,
.checkentry = portscan_mt_check,
.matchsize = sizeof(struct xt_portscan_mtinfo),
.proto = IPPROTO_TCP,
.me = THIS_MODULE,
},
};
static int __init portscan_mt_init(void)
{
return xt_register_match(&portscan_mt_reg);
return xt_register_matches(portscan_mt_reg,
ARRAY_SIZE(portscan_mt_reg));
}
static void __exit portscan_mt_exit(void)
{
xt_unregister_match(&portscan_mt_reg);
return;
xt_unregister_matches(portscan_mt_reg, ARRAY_SIZE(portscan_mt_reg));
}
module_init(portscan_mt_init);
module_exit(portscan_mt_exit);
MODULE_AUTHOR("Jan Engelhardt <jengelh@computergmbh.de>");
MODULE_DESCRIPTION("netfilter \"portscan\" match");
MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
MODULE_DESCRIPTION("Xtables: \"portscan\" match");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_portscan");
MODULE_ALIAS("ip6t_portscan");

248
extensions/xt_quota2.c Normal file
View File

@@ -0,0 +1,248 @@
/*
* xt_quota2 - enhanced xt_quota that can count upwards and in packets
* as a minimal accounting match.
* by Jan Engelhardt <jengelh@medozas.de>, 2008
*
* Originally based on xt_quota.c:
* netfilter module to enforce network quotas
* Sam Johnston <samj@samj.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License; either
* version 2 of the License, as published by the Free Software Foundation.
*/
#include <linux/list.h>
#include <linux/proc_fs.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <asm/atomic.h>
#include <linux/netfilter/x_tables.h>
#include "xt_quota2.h"
#include "compat_xtables.h"
struct quota_counter {
u_int64_t quota;
spinlock_t lock;
struct list_head list;
atomic_t ref;
char name[XT_QUOTA_COUNTER_NAME_LENGTH];
struct proc_dir_entry *procfs_entry;
};
static LIST_HEAD(counter_list);
static DEFINE_SPINLOCK(counter_list_lock);
static struct proc_dir_entry *proc_xt_quota;
static unsigned int quota_list_perms = S_IRUGO | S_IWUSR;
static unsigned int quota_list_uid = 0;
static unsigned int quota_list_gid = 0;
module_param_named(perms, quota_list_perms, uint, S_IRUGO | S_IWUSR);
module_param_named(uid, quota_list_uid, uint, S_IRUGO | S_IWUSR);
module_param_named(gid, quota_list_gid, uint, S_IRUGO | S_IWUSR);
static int quota_proc_read(char *page, char **start, off_t offset,
int count, int *eof, void *data)
{
struct quota_counter *e = data;
int ret;
spin_lock_bh(&e->lock);
ret = snprintf(page, PAGE_SIZE, "%llu\n", e->quota);
spin_unlock_bh(&e->lock);
return ret;
}
static int quota_proc_write(struct file *file, const char __user *input,
unsigned long size, void *data)
{
struct quota_counter *e = data;
char buf[sizeof("18446744073709551616")];
if (size > sizeof(buf))
size = sizeof(buf);
if (copy_from_user(buf, input, size) != 0)
return -EFAULT;
buf[sizeof(buf)-1] = '\0';
spin_lock_bh(&e->lock);
e->quota = simple_strtoul(buf, NULL, 0);
spin_unlock_bh(&e->lock);
return size;
}
/**
* q2_get_counter - get ref to counter or create new
* @name: name of counter
*/
static struct quota_counter *q2_get_counter(const struct xt_quota_mtinfo2 *q)
{
struct proc_dir_entry *p;
struct quota_counter *e;
spin_lock_bh(&counter_list_lock);
list_for_each_entry(e, &counter_list, list) {
if (strcmp(e->name, q->name) == 0) {
atomic_inc(&e->ref);
spin_unlock_bh(&counter_list_lock);
return e;
}
}
e = kmalloc(sizeof(struct quota_counter), GFP_KERNEL);
if (e == NULL)
goto out;
e->quota = q->quota;
spin_lock_init(&e->lock);
INIT_LIST_HEAD(&e->list);
atomic_set(&e->ref, 1);
strncpy(e->name, q->name, sizeof(e->name));
p = e->procfs_entry = create_proc_entry(e->name, quota_list_perms,
proc_xt_quota);
if (p == NULL || IS_ERR(p))
goto out;
p->owner = THIS_MODULE;
p->data = e;
p->read_proc = quota_proc_read;
p->write_proc = quota_proc_write;
p->uid = quota_list_uid;
p->gid = quota_list_gid;
list_add_tail(&e->list, &counter_list);
spin_unlock_bh(&counter_list_lock);
return e;
out:
spin_unlock_bh(&counter_list_lock);
kfree(e);
return NULL;
}
static bool
quota_mt2_check(const char *tablename, const void *entry,
const struct xt_match *match, void *matchinfo,
unsigned int hook_mask)
{
struct xt_quota_mtinfo2 *q = matchinfo;
if (q->flags & ~XT_QUOTA_MASK)
return false;
q->name[sizeof(q->name)-1] = '\0';
if (*q->name == '\0' || *q->name == '.' ||
strchr(q->name, '/') != NULL) {
printk(KERN_ERR "xt_quota.2: illegal name\n");
return false;
}
q->master = q2_get_counter(q);
if (q->master == NULL) {
printk(KERN_ERR "xt_quota.2: memory alloc failure\n");
return false;
}
return true;
}
static void quota_mt2_destroy(const struct xt_match *match, void *matchinfo)
{
struct xt_quota_mtinfo2 *q = matchinfo;
struct quota_counter *e = q->master;
spin_lock_bh(&counter_list_lock);
if (!atomic_dec_and_test(&e->ref)) {
spin_unlock_bh(&counter_list_lock);
return;
}
list_del(&e->list);
spin_unlock_bh(&counter_list_lock);
remove_proc_entry(e->name, proc_xt_quota);
kfree(e);
}
static bool
quota_mt2(const struct sk_buff *skb, const struct net_device *in,
const struct net_device *out, const struct xt_match *match,
const void *matchinfo, int offset, unsigned int protoff,
bool *hotdrop)
{
struct xt_quota_mtinfo2 *q = (void *)matchinfo;
struct quota_counter *e = q->master;
bool ret = q->flags & XT_QUOTA_INVERT;
if (q->flags & XT_QUOTA_GROW) {
spin_lock_bh(&e->lock);
e->quota += (q->flags & XT_QUOTA_PACKET) ? 1 : skb->len;
q->quota = e->quota;
spin_unlock_bh(&e->lock);
ret = true;
} else {
spin_lock_bh(&e->lock);
if (e->quota >= skb->len) {
e->quota -= (q->flags & XT_QUOTA_PACKET) ? 1 : skb->len;
ret = !ret;
} else {
/* we do not allow even small packets from now on */
e->quota = 0;
}
q->quota = e->quota;
spin_unlock_bh(&e->lock);
}
return ret;
}
static struct xt_match quota_mt2_reg[] __read_mostly = {
{
.name = "quota2",
.revision = 2,
.family = AF_INET,
.checkentry = quota_mt2_check,
.match = quota_mt2,
.destroy = quota_mt2_destroy,
.matchsize = sizeof(struct xt_quota_mtinfo2),
.me = THIS_MODULE,
},
{
.name = "quota2",
.revision = 2,
.family = AF_INET6,
.checkentry = quota_mt2_check,
.match = quota_mt2,
.destroy = quota_mt2_destroy,
.matchsize = sizeof(struct xt_quota_mtinfo2),
.me = THIS_MODULE,
},
};
static int __init quota_mt2_init(void)
{
int ret;
proc_xt_quota = proc_mkdir("xt_quota", init_net__proc_net);
if (proc_xt_quota == NULL)
return -EACCES;
ret = xt_register_matches(quota_mt2_reg, ARRAY_SIZE(quota_mt2_reg));
if (ret < 0)
remove_proc_entry("xt_quota", init_net__proc_net);
return ret;
}
static void __exit quota_mt2_exit(void)
{
xt_unregister_matches(quota_mt2_reg, ARRAY_SIZE(quota_mt2_reg));
remove_proc_entry("xt_quota", init_net__proc_net);
}
module_init(quota_mt2_init);
module_exit(quota_mt2_exit);
MODULE_DESCRIPTION("Xtables: countdown quota match; up counter");
MODULE_AUTHOR("Sam Johnston <samj@samj.net>");
MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_quota2");
MODULE_ALIAS("ip6t_quota2");

26
extensions/xt_quota2.h Normal file
View File

@@ -0,0 +1,26 @@
#ifndef _XT_QUOTA_H
#define _XT_QUOTA_H
enum xt_quota_flags {
XT_QUOTA_INVERT = 1 << 0,
XT_QUOTA_GROW = 1 << 1,
XT_QUOTA_PACKET = 1 << 2,
XT_QUOTA_MASK = 0x7,
XT_QUOTA_COUNTER_NAME_LENGTH = 31,
};
struct quota_counter;
struct xt_quota_mtinfo2 {
char name[XT_QUOTA_COUNTER_NAME_LENGTH];
u_int8_t flags;
/* Comparison-invariant */
aligned_u64 quota;
/* Used internally by the kernel */
struct quota_counter *master __attribute__((aligned(8)));
};
#endif /* _XT_QUOTA_H */

View File

@@ -1,179 +0,0 @@
#ifndef __LINUX_COMPILER_H
#define __LINUX_COMPILER_H
#ifndef __ASSEMBLY__
#ifdef __CHECKER__
# define __user __attribute__((noderef, address_space(1)))
# define __kernel /* default address space */
# define __safe __attribute__((safe))
# define __force __attribute__((force))
# define __nocast __attribute__((nocast))
# define __iomem __attribute__((noderef, address_space(2)))
# define __acquires(x) __attribute__((context(x,0,1)))
# define __releases(x) __attribute__((context(x,1,0)))
# define __acquire(x) __context__(x,1)
# define __release(x) __context__(x,-1)
# define __cond_lock(x,c) ((c) ? ({ __acquire(x); 1; }) : 0)
extern void __chk_user_ptr(const volatile void __user *);
extern void __chk_io_ptr(const volatile void __iomem *);
#else
# define __user
# define __kernel
# define __safe
# define __force
# define __nocast
# define __iomem
# define __chk_user_ptr(x) (void)0
# define __chk_io_ptr(x) (void)0
# define __builtin_warning(x, y...) (1)
# define __acquires(x)
# define __releases(x)
# define __acquire(x) (void)0
# define __release(x) (void)0
# define __cond_lock(x,c) (c)
#endif
#ifdef __KERNEL__
#if __GNUC__ >= 4
# include <linux/compiler-gcc4.h>
#elif __GNUC__ == 3 && __GNUC_MINOR__ >= 2
# include <linux/compiler-gcc3.h>
#else
# error Sorry, your compiler is too old/not recognized.
#endif
/* Intel compiler defines __GNUC__. So we will overwrite implementations
* coming from above header files here
*/
#ifdef __INTEL_COMPILER
# include <linux/compiler-intel.h>
#endif
/*
* Generic compiler-dependent macros required for kernel
* build go below this comment. Actual compiler/compiler version
* specific implementations come from the above header files
*/
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
/* Optimization barrier */
#ifndef barrier
# define barrier() __memory_barrier()
#endif
#ifndef RELOC_HIDE
# define RELOC_HIDE(ptr, off) \
({ unsigned long __ptr; \
__ptr = (unsigned long) (ptr); \
(typeof(ptr)) (__ptr + (off)); })
#endif
#endif /* __KERNEL__ */
#endif /* __ASSEMBLY__ */
#ifdef __KERNEL__
/*
* Allow us to mark functions as 'deprecated' and have gcc emit a nice
* warning for each use, in hopes of speeding the functions removal.
* Usage is:
* int __deprecated foo(void)
*/
#ifndef __deprecated
# define __deprecated /* unimplemented */
#endif
#ifdef MODULE
#define __deprecated_for_modules __deprecated
#else
#define __deprecated_for_modules
#endif
#ifndef __must_check
#define __must_check
#endif
#ifndef CONFIG_ENABLE_MUST_CHECK
#undef __must_check
#define __must_check
#endif
#ifndef CONFIG_ENABLE_WARN_DEPRECATED
#undef __deprecated
#undef __deprecated_for_modules
#define __deprecated
#define __deprecated_for_modules
#endif
/*
* Allow us to avoid 'defined but not used' warnings on functions and data,
* as well as force them to be emitted to the assembly file.
*
* As of gcc 3.4, static functions that are not marked with attribute((used))
* may be elided from the assembly file. As of gcc 3.4, static data not so
* marked will not be elided, but this may change in a future gcc version.
*
* NOTE: Because distributions shipped with a backported unit-at-a-time
* compiler in gcc 3.3, we must define __used to be __attribute__((used))
* for gcc >=3.3 instead of 3.4.
*
* In prior versions of gcc, such functions and data would be emitted, but
* would be warned about except with attribute((unused)).
*
* Mark functions that are referenced only in inline assembly as __used so
* the code is emitted even though it appears to be unreferenced.
*/
#ifndef __used
# define __used /* unimplemented */
#endif
#ifndef __maybe_unused
# define __maybe_unused /* unimplemented */
#endif
#ifndef noinline
#define noinline
#endif
#ifndef __always_inline
#define __always_inline inline
#endif
#endif /* __KERNEL__ */
/*
* From the GCC manual:
*
* Many functions do not examine any values except their arguments,
* and have no effects except the return value. Basically this is
* just slightly more strict class than the `pure' attribute above,
* since function is not allowed to read global memory.
*
* Note that a function that has pointer arguments and examines the
* data pointed to must _not_ be declared `const'. Likewise, a
* function that calls a non-`const' function usually must not be
* `const'. It does not make sense for a `const' function to return
* `void'.
*/
#ifndef __attribute_const__
# define __attribute_const__ /* unimplemented */
#endif
/*
* Tell gcc if a function is cold. The compiler will assume any path
* directly leading to the call is unlikely.
*/
#ifndef __cold
#define __cold
#endif
/* Simple shorthand for a section definition */
#ifndef __section
# define __section(S) __attribute__ ((__section__(#S)))
#endif
#endif /* __LINUX_COMPILER_H */

View File

@@ -1,7 +1,7 @@
#ifndef __LINUX_NETFILTER_H
#define __LINUX_NETFILTER_H
#include <linux/compiler.h>
#include <linux/types.h>
/* Responses from hook functions. */
#define NF_DROP 0
@@ -20,7 +20,7 @@
#define NF_VERDICT_QMASK 0xffff0000
#define NF_VERDICT_QBITS 16
#define NF_QUEUE_NR(x) (((x << NF_VERDICT_QBITS) & NF_VERDICT_QMASK) | NF_QUEUE)
#define NF_QUEUE_NR(x) ((((x) << NF_VERDICT_BITS) & NF_VERDICT_QMASK) | NF_QUEUE)
/* only for userspace compatibility */
/* Generic cache responses from hook functions.
@@ -38,7 +38,7 @@ enum nf_inet_hooks {
};
union nf_inet_addr {
u_int32_t all[4];
__u32 all[4];
__be32 ip;
__be32 ip6[4];
struct in_addr in;

View File

@@ -2,12 +2,17 @@
#
build_CHAOS=m
build_DELUDE=m
build_DHCPADDR=m
build_ECHO=
build_IPMARK=m
build_LOGMARK=m
build_SYSRQ=m
build_TARPIT=m
build_TEE=m
build_condition=m
build_fuzzy=m
build_geoip=m
build_ipp2p=m
build_ipset=m
build_portscan=m
build_quota2=m