pax_global_header00006660000000000000000000000064150114316300014504gustar00rootroot0000000000000052 comment=9030919ddf7fbd4c6ff07e3d4ab2b9316843b672
netsed-1.4/000077500000000000000000000000001501143163000126325ustar00rootroot00000000000000netsed-1.4/LICENSE000066400000000000000000000430761501143163000136510ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, 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 Library 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
Appendix: 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.
Copyright (C) 19yy
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.
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) 19yy 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.
, 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 Library General
Public License instead of this License.
netsed-1.4/Makefile000066400000000000000000000027521501143163000143000ustar00rootroot00000000000000CFLAGS += -Wall -fomit-frame-pointer
PREFIX ?= /usr/local
ifeq "$(shell uname -s)" "SunOS"
LDFLAGS += -lsocket
endif
VERSION := $(shell grep '\#define VERSION' netsed.c|sed 's/\#define VERSION "\(.*\)"/\1/')
all: netsed
install: netsed
install -d $(DESTDIR)$(PREFIX)/bin
install -m 0755 netsed $(DESTDIR)$(PREFIX)/bin/
clean:
rm -f netsed core *.o netsed.tgz
doc:
doxygen doxygen.conf
check_version:
@echo netsed $(VERSION)
@grep "netsed $(VERSION)" NEWS>/dev/null ||(echo "version should appear in NEWS file"; exit 1)
@grep "netsed $(VERSION)" README>/dev/null ||(echo "version should appear in README file"; exit 1)
.PHONY: test
test: netsed
ruby test/ts_full.rb
test/doc:
cd test;LANG=C rdoc -a --inline-source -d *.rb
release_tag: check_version
@if (git status --porcelain | grep '^ M') then echo "you have modified files, cannot tag"; exit 2; else exit 0; fi
git tag -s $(VERSION) -m "Version $(VERSION)"
quick_archive: clean check_version
tar cfvz ../netsed-$(VERSION).tar.gz *
release_archive: | release_tag
@git show-ref --tags $(VERSION) > /dev/null ||(echo "to release first create a tag with the current version $(VERSION).\nJust type:\n make release_tag"; exit 3)
fakeroot git archive --format=tar --prefix=netsed-$(VERSION)/ $(VERSION) | gzip > ../netsed-$(VERSION).tar.gz
release: release_tag release_archive
@echo "netsed-$(VERSION) release"
@gpg --armor --detach-sign ../netsed-$(VERSION).tar.gz
# and upload netsed-$(VERSION).tar.gz netsed-$(VERSION).tar.gz.asc
netsed-1.4/NEWS000066400000000000000000000045721501143163000133410ustar00rootroot000000000000002025-05-15; netsed 1.4:
- fix from debian package thanks Andreas Tille
- Accept nil and "" as test result
2019-01-06; netsed 1.3:
- fix from debian package thanks Mats Erik Anersson:
- Build failure during test phase. (ie fix uninitialized alloc)
- Ruby interpreter complains. (ie fix test)
- Remove gitignore from release archive.
- Fix warning: ‘*’ in boolean context.
- Implement standard release signature.
2013-10-11; netsed 1.2:
- new feature from Mats Erik Anersson:
- Direction dependant rules.
2012-08-15; netsed 1.1:
- several fix from Mats Erik Anersson:
- Let Makefile use externally exported CFLAGS.
- Make the macro LINUX_NETFILTER be conditionally active.
- Allow traditionally delimited rules.
- Regulate dual-stacking of listener.
- Linking flag needed for OpenSolaris.
- Fix for option IPV6_V6ONLY.
- License clarification.
- Implemented options to force IP version 4 or 6.
- Added long options --ipv4, --ipv6 and --ipany.
- Changed help display.
- Adjust to changes in the Ruby 1.9 require syntax. By Sven Hoexter
2010-09-02; netsed 1.00b:
- Transparent proxy mode for netfilter (linux 2.4 and 2.6)
2010-07-15; netsed 1.00a:
- major architecture rework:
- only one process is needed
- added tracking connection structure
- all receive sockets are select()ed
- udp is implemented
- improved tests.
- added developers documentation in source code (doxygen)
2010-07-02, netsed 0.02c:
- added a test suite in test directory
- catching ctrl-C and closing sockets:
- to do that I also used a select for the listening socket, getting rid of
the usleep call ;)
- this also improve batch tests as it wont wait for some timeout to reuse
the socket.
2010-06-19, netsed 0.02b:
- imported patches from '#397420' :
- IPv6 compatible reimplentation of resolving code
- some minor other changes
2010-06-19, netsed 0.02a:
- detecting client/server disconnection (not only on write fail)
- using select in treatment process to avoid useless cpu load 'Debian Bug #586037'
- resolving rhost address if needed 'Debian Bug #397420'
- rule replacement was replacing all occurence of any rule,
but will leave 1 char between any rule match,
fixed to replace all occurence of the rules directly.
someday, netsed 0.01c:
- last available netsed version taken from debian archive.
netsed-1.4/README000066400000000000000000000207131501143163000135150ustar00rootroot00000000000000
netsed 1.4 (C) 2010-2025 Julien VdG
--------------------------------------------------------------------------
This work is based on the original netsed:
netsed 0.01c (C) 2002 Michal Zalewski
Please contact Julien VdG if you encounter
any problems with this version.
The changes compared to version 0.01c are related in the NEWS file.
--------------------------------------------------------------------------
"When things go well, expect something to explode, erode, collapse or
just disappear." -- anonymous
NetSED is small and handful utility designed to alter the contents of
packets forwarded thru your network in real time. It is really useful
for network hackers in following applications:
* black-box protocol auditing - whenever there are two or more
propertiary boxes communicating over undocumented protocol (by enforcing
changes in ongoing transmissions, you will be able to test if tested
application is secure),
* fuzz-alike experiments, integrity tests - whenever you want to test
stability of the application and see how it ensures data integrity,
* other common applications - fooling other people, content filtering,
etc etc - choose whatever you want to.
It perfectly fits netgrep, netcat and tcpdump tools suite :P
It has been designed because I was suspicious about Lotus Domino carrying
mailbox path in every packet after authorization. Having no Lotus Domino
client software under Linux, I needed something to install on my bridging
firewall to modify this mailbox path and try to read someone's else
mailbox. Guess what happened?:P
This is release 0.01b, which isn't really effective or stable, and I
wouldn't suggest you putting it nowhere in your production systems ;)
But - well - any suggestions, fixes, comments and ideas are welcome. For
now, only TCP and UDP user-space filtering is possible - no support for
kernel firewalling / routing, raw packets, ICMP and other things.
I bet it won't compile on platforms other than Linux, as I haven't tested
it, but it shouldn't be too difficult to run it on *BSD, IRIX, Solaris
etc.
Setting up netsed - theory
--------------------------
There are two possible ways of using netsed. Basic configuration looks this
way:
( client software ) --->------+
|
< local port >
|
[ netsed engine ]
|
+-------------> ( remote server )
In this solution, client software has to connect specified port on specified
machine - which is not always possible, and not always expected. So,
there is a second way - which is completely system-dependent. It is called
transparent proxy.
NetSED supports kernel-level transparent proxy. This means you can set up
your gateway machine (firewall, router, ethernet bridge) to transparently
redirect all traffic coming from client software to remote server without
touching anything outside this box. On Linux, you can set up transparent
proxying in pretty easy way:
ipfwadm -I -i accept -S source_ip -D destination_ip port -P protocol -r lport
For example, if you want to redirect all traffic coming from host
1.2.3.4 to network 5.6.0.0/16 with destination port 12345/tcp, and you
have netsed working on port 10101 on your local machine, you should do
something like:
ipfwadm -I -i accept -S 1.2.3.4 -D 5.6.0.0/16 12345 -P tcp -r 10101
By setting up netsed properly, content will be transparenly modified and
forwarded to the destination:
NetSED
______|______
( client software ) --->---| - - -+- - - |--------> ( server host )
| transparent |
| proxy |
|_____________|
For more instructions on rules syntax and transparent proxies in general,
refer your OS documentation.
Update for linux 2.4 and later with netfilter:
First you need to make sure LINUX_NETFILTER is defined in source code
before compiling.
Then the command are as follows:
iptables -t nat -D PREROUTING -s source_ip -d destination_ip -p protocol --dport port -j REDIRECT --to lport
So the previous example becomes:
iptables -t nat -D PREROUTING -s 1.2.3.4 -d 5.6.0.0/16 -p tcp --dport 12345 -j REDIRECT --to 10101
Setting up netsed - practice
----------------------------
Ok, here we are. First of all, you should know how to set up the first
configuration I've been talking about - static, user-space forwarder.
NetSED accepts following parameters:
netsed proto lport rhost rport rule1 [ rule2 ... ]
First parameter, 'proto', means, obviously, the protocol. You might choose
'tcp' or 'udp'. Then, you have to specify 'lport' - local listening port.
Next argument, 'rhost', is the remote server address where the connection
should be forwarded. ONLY IP ADDRESSES ARE SUPPORTED BY NOW. Then, we
have 'rport' - remote port number, and up to 50 filtering rules.
General replacement rules syntax is:
s/pat1/pat2[/expire]
This will replace all occurrences of pat1 with pat2 in matching packets.
An additional parameter (count) can be used to expire rule after 'count'
successful substitutions for a given connection. Eight-bit characters,
including NULL and '/', can be passed using HTTP-alike hex escape
sequences (eg. %0a%0d). Single '%' can be reached by using '%%'.
Examples:
's/andrew/mike/1' - replace 'andrew' with 'mike' (only first time)
's/andrew/mike' - replace all occurrences of 'andrew' with 'mike'
's/andrew/mike%00%00' - replace 'andrew' with 'mike\x00\x00'
(manually padding to keep original size)
's/%%/%2f/20' - replace the 20 first occurence of '%' with '/'
Rules are not working on cross-packet boundaries and are evaluated from
first to last not expired rule.
Per-rule TTLs (time-to-live) are useful if you want to modify eg. only
the first packet, letting other packets unmodified, or to dynamically
change NetSED functionality. This rule, for example, will change 'Henry'
to 'William' in the first packet, and to 'Mariah' in all other packets:
s/Henry/William/1 s/Henry/Mariah
So, let's try our first command-line example:
./netsed tcp 10101 127.0.0.1 25 s/ehlo/badcommand/1
This should be obvious - connection to local port 10101 will be forwarded
to local smtp service. Take a look:
$ telnet localhost 10101
220 squirrel.tpi.pl ESMTP Sendmail 8.9.3/8.9.3; Fri, 5 Jan 2001 00:15:18 +0100
ehlo
500 Command unrecognized: "badcommand"
ehlo
501 ehlo requires domain address
Apparently, it worked :) Try playing a little with different patterns,
multiple rules etc. Generally, NetSED works by incremental comparsion
of the rules, and then skipping already replaced data. For example:
Rules: s/degener/devi/
s/generation/%20and%20sausages/
s/sausages/chicken/
Input data: 'degenerationgeneration'
Init: degenerationgeneration
^ (replace pointer)
Pass 1: deviationgeneration [degener -> devi]
^ (replace pointer)
Pass 2: deviation and sausages [generation -> and sausages]
^
No futher replacements made - end of input data (so, 'sausages'
won't be replaced with 'chicken').
Now, I suppose you'd like to know how to setup good-working transparent
configuration. Well - nothing easier :) The configuration described above
should work just fine - set up transparent packet redirection to port
10101 in traffic from one remote host to another and watch the results...
Uhm, right. There's one thing. You might want to divert traffic from
one host to whole network - but you do not know how to configure netcat
to preserver original destination addresses? So, for example, connecting
to 5.6.7.1 and to 5.6.7.2 from 1.2.3.4 (example mentioned above) will
establish working session to existing targets? Nothing easier. Just
set rhost and/or rport parameters to '0' while invoking NetSED to preserve
original destination host and port settings while forwarding the connection
via proxy :)
WARNING: nothing will stop you before setting up forwarding loops - you
can eg. forward connections to port 100 to port 1000 using netsed, and then,
using kernel-space transparent proxy, forward connections to local port 1000
back to port 100. This might lead to ugly DoS attack if you do not have
per-user resource limits set. Sorry. Not a Microsoft product.
netsed-1.4/TODO000066400000000000000000000013011501143163000133150ustar00rootroot00000000000000--- TODO and wishlist in no particular order:
- Find a better bugtracker than this file
- tests:
- Improve feature coverage
- investigate why UDP IPv6 tests fail
- When udp datagram is send and nothing gets it, an ICMP response (closed port or something similar) arrives to netsed but netsed does not forward that to the client. Is this needed...
- Improve and update user documentation (and publish it on web ?)
- implementing all sed scripting is not the plan, but :
- implement some regex support (most of sed s// command without all the scripting that sed allows). man 3 regex
- allowing the rule to be processed externally by a filter program (so the real sed can be used). check with popen.
netsed-1.4/doxygen.conf000066400000000000000000000221531501143163000151610ustar00rootroot00000000000000# Doxyfile 1.6.3
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = netsed
PROJECT_NUMBER =
OUTPUT_DIRECTORY =
CREATE_SUBDIRS = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF =
ALWAYS_DETAILED_SEC = NO
INLINE_INHERITED_MEMB = NO
FULL_PATH_NAMES = YES
STRIP_FROM_PATH =
STRIP_FROM_INC_PATH =
SHORT_NAMES = NO
JAVADOC_AUTOBRIEF = NO
QT_AUTOBRIEF = NO
MULTILINE_CPP_IS_BRIEF = YES
INHERIT_DOCS = YES
SEPARATE_MEMBER_PAGES = NO
TAB_SIZE = 8
ALIASES =
OPTIMIZE_OUTPUT_FOR_C = YES
OPTIMIZE_OUTPUT_JAVA = NO
OPTIMIZE_FOR_FORTRAN = NO
OPTIMIZE_OUTPUT_VHDL = NO
EXTENSION_MAPPING =
BUILTIN_STL_SUPPORT = NO
CPP_CLI_SUPPORT = NO
SIP_SUPPORT = NO
IDL_PROPERTY_SUPPORT = YES
DISTRIBUTE_GROUP_DOC = NO
SUBGROUPING = YES
TYPEDEF_HIDES_STRUCT = NO
SYMBOL_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
EXTRACT_ALL = YES
EXTRACT_PRIVATE = YES
EXTRACT_STATIC = YES
EXTRACT_LOCAL_CLASSES = YES
EXTRACT_LOCAL_METHODS = NO
EXTRACT_ANON_NSPACES = NO
HIDE_UNDOC_MEMBERS = NO
HIDE_UNDOC_CLASSES = NO
HIDE_FRIEND_COMPOUNDS = NO
HIDE_IN_BODY_DOCS = NO
INTERNAL_DOCS = NO
CASE_SENSE_NAMES = YES
HIDE_SCOPE_NAMES = NO
SHOW_INCLUDE_FILES = YES
FORCE_LOCAL_INCLUDES = NO
INLINE_INFO = YES
SORT_MEMBER_DOCS = YES
SORT_BRIEF_DOCS = NO
SORT_MEMBERS_CTORS_1ST = NO
SORT_GROUP_NAMES = NO
SORT_BY_SCOPE_NAME = NO
GENERATE_TODOLIST = YES
GENERATE_TESTLIST = YES
GENERATE_BUGLIST = YES
GENERATE_DEPRECATEDLIST= YES
ENABLED_SECTIONS =
MAX_INITIALIZER_LINES = 30
SHOW_USED_FILES = YES
SHOW_DIRECTORIES = NO
SHOW_FILES = YES
SHOW_NAMESPACES = YES
FILE_VERSION_FILTER =
LAYOUT_FILE =
#---------------------------------------------------------------------------
# configuration options related to warning and progress messages
#---------------------------------------------------------------------------
QUIET = NO
WARNINGS = YES
WARN_IF_UNDOCUMENTED = YES
WARN_IF_DOC_ERROR = YES
WARN_NO_PARAMDOC = NO
WARN_FORMAT = "$file:$line: $text"
WARN_LOGFILE =
#---------------------------------------------------------------------------
# configuration options related to the input files
#---------------------------------------------------------------------------
INPUT = netsed.c
INPUT_ENCODING = UTF-8
FILE_PATTERNS =
RECURSIVE = NO
EXCLUDE =
EXCLUDE_SYMLINKS = NO
EXCLUDE_PATTERNS =
EXCLUDE_SYMBOLS =
EXAMPLE_PATH = .
EXAMPLE_PATTERNS =
EXAMPLE_RECURSIVE = NO
IMAGE_PATH =
INPUT_FILTER =
FILTER_PATTERNS =
FILTER_SOURCE_FILES = NO
#---------------------------------------------------------------------------
# configuration options related to source browsing
#---------------------------------------------------------------------------
SOURCE_BROWSER = YES
INLINE_SOURCES = NO
STRIP_CODE_COMMENTS = YES
REFERENCED_BY_RELATION = NO
REFERENCES_RELATION = NO
REFERENCES_LINK_SOURCE = YES
USE_HTAGS = NO
VERBATIM_HEADERS = YES
#---------------------------------------------------------------------------
# configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
ALPHABETICAL_INDEX = NO
COLS_IN_ALPHA_INDEX = 5
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# configuration options related to the HTML output
#---------------------------------------------------------------------------
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
HTML_HEADER =
HTML_FOOTER =
HTML_STYLESHEET =
HTML_TIMESTAMP = YES
HTML_ALIGN_MEMBERS = YES
HTML_DYNAMIC_SECTIONS = NO
GENERATE_DOCSET = NO
DOCSET_FEEDNAME = "Doxygen generated docs"
DOCSET_BUNDLE_ID = org.doxygen.Project
GENERATE_HTMLHELP = NO
CHM_FILE =
HHC_LOCATION =
GENERATE_CHI = NO
CHM_INDEX_ENCODING =
BINARY_TOC = NO
TOC_EXPAND = NO
GENERATE_QHP = NO
QCH_FILE =
QHP_NAMESPACE = org.doxygen.Project
QHP_VIRTUAL_FOLDER = doc
QHP_CUST_FILTER_NAME =
QHP_CUST_FILTER_ATTRS =
QHP_SECT_FILTER_ATTRS =
QHG_LOCATION =
GENERATE_ECLIPSEHELP = NO
ECLIPSE_DOC_ID = org.doxygen.Project
DISABLE_INDEX = NO
ENUM_VALUES_PER_LINE = 4
GENERATE_TREEVIEW = NO
USE_INLINE_TREES = NO
TREEVIEW_WIDTH = 250
FORMULA_FONTSIZE = 10
SEARCHENGINE = YES
SERVER_BASED_SEARCH = NO
#---------------------------------------------------------------------------
# configuration options related to the LaTeX output
#---------------------------------------------------------------------------
GENERATE_LATEX = NO
LATEX_OUTPUT = latex
LATEX_CMD_NAME = latex
MAKEINDEX_CMD_NAME = makeindex
COMPACT_LATEX = NO
PAPER_TYPE = a4wide
EXTRA_PACKAGES =
LATEX_HEADER =
PDF_HYPERLINKS = YES
USE_PDFLATEX = YES
LATEX_BATCHMODE = NO
LATEX_HIDE_INDICES = NO
LATEX_SOURCE_CODE = NO
#---------------------------------------------------------------------------
# configuration options related to the RTF output
#---------------------------------------------------------------------------
GENERATE_RTF = NO
RTF_OUTPUT = rtf
COMPACT_RTF = NO
RTF_HYPERLINKS = NO
RTF_STYLESHEET_FILE =
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# configuration options related to the man page output
#---------------------------------------------------------------------------
GENERATE_MAN = NO
MAN_OUTPUT = man
MAN_EXTENSION = .3
MAN_LINKS = NO
#---------------------------------------------------------------------------
# configuration options related to the XML output
#---------------------------------------------------------------------------
GENERATE_XML = NO
XML_OUTPUT = xml
XML_SCHEMA =
XML_DTD =
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# configuration options related to the Perl module output
#---------------------------------------------------------------------------
GENERATE_PERLMOD = NO
PERLMOD_LATEX = NO
PERLMOD_PRETTY = YES
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = NO
EXPAND_ONLY_PREDEF = NO
SEARCH_INCLUDES = YES
INCLUDE_PATH =
INCLUDE_FILE_PATTERNS =
PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration::additions related to external references
#---------------------------------------------------------------------------
TAGFILES =
GENERATE_TAGFILE =
ALLEXTERNALS = NO
EXTERNAL_GROUPS = YES
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
CLASS_DIAGRAMS = NO
MSCGEN_PATH =
HIDE_UNDOC_RELATIONS = YES
HAVE_DOT = YES
DOT_FONTNAME = FreeSans
DOT_FONTSIZE = 10
DOT_FONTPATH =
CLASS_GRAPH = YES
COLLABORATION_GRAPH = YES
GROUP_GRAPHS = YES
UML_LOOK = NO
TEMPLATE_RELATIONS = NO
INCLUDE_GRAPH = YES
INCLUDED_BY_GRAPH = YES
CALL_GRAPH = YES
CALLER_GRAPH = YES
GRAPHICAL_HIERARCHY = YES
DIRECTORY_GRAPH = YES
DOT_IMAGE_FORMAT = png
DOT_PATH =
DOTFILE_DIRS =
DOT_GRAPH_MAX_NODES = 50
MAX_DOT_GRAPH_DEPTH = 0
DOT_TRANSPARENT = NO
DOT_MULTI_TARGETS = YES
GENERATE_LEGEND = YES
DOT_CLEANUP = YES
netsed-1.4/netsed.c000066400000000000000000000747621501143163000143000ustar00rootroot00000000000000/*
netsed 1.4 (C) 2010-2025 Julien VdG
--------------------------------------------------------------------------
This work is based on the original netsed:
netsed 0.01c (C) 2002 Michal Zalewski
Please contact Julien VdG if you encounter
any problems with this version.
The changes compared to version 0.01c are related in the NEWS file.
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.
*/
///@mainpage
///
/// This documentation is targeting netsed developers, if you are a user
/// either launch netsed without parameters or read the README file
/// (@link README @endlink).
///
///@par
/// - Currently netsed is implemented in a single file: netsed.c
/// - some TODOs are gathered on the @link todo @endlink page,
/// some others are in the TODO file.
/// .
///@file netsed.c
///@brief netsed is implemented in this single file.
///@par Architecture
/// Netsed is implemented as a select socket dispatcher.
/// First a main socket server is created (#lsock), each connection to this
/// socket create a context stored in the tracker_s structure and added to
/// the #connections list.
/// Each connection has
/// - a connected socket (tracker_s::csock) returned by the accept() function
/// for tcp, or
/// - a connection socket address (tracker_s::csa) filled by recvfrom() for udp.
/// - a dedicated forwarding socket (tracker_s::fsock) connected to the server.
/// .
/// All sockets are added to the select() call and managed by the dispatcher
/// as follows:
/// - When packets are received from the client, the rules are applied by
/// sed_the_buffer() and the packet is sent to the server. Direction is OUT.
/// This is the role of client2server_sed() function. It is only used for tcp.
/// - When packets are received from the server, the rules are applied by
/// sed_the_buffer() and the packet is sent to the corresponding client.
/// Direction is IN. This is the role of server2client_sed() function.
/// - For udp only, connection from client to netsed are not established
/// so netsed need to lookup existing #connections to find the corresponding
/// established link, if any. The lookup is done by comparing tracker_s::csa.
/// Once the connection is found or created, the rules are applied
/// by sed_the_buffer() and the packet is sent to the server.
/// This is the role of b2server_sed() function.
/// .
/// @note For tcp tracker_s::csa is NULL and for udp the tracker_s::csock is
/// filled with #lsock. This is done in order to share code and avoid
/// discriminating between tcp or udp everywhere, sendto are done on
/// tracker_s::csock with tracker_s::csa only and the actual value of those
/// will reflect the needs.
///
/// @note I'm saying packets and connections, but for udp these are actually
/// datagrams and pseudo-connections. The pseudo-connection is defined by the
/// fact that the client uses the same address and port (same tracker_s::csa)
/// with a life time defined by #UDP_TIMEOUT to clean the connection list.
///
/// @todo Implements features listed in TODO file.
///@page README User documentation
/// The README file:
///@verbinclude README
///@page todo The TODO list
/// The TODO file:
///@verbinclude TODO
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef __linux__
/// Define for transparent proxy with linux netfilter.
/// Else use getsockname() supposing the socket receive the original
/// destination information directly.
#define LINUX_NETFILTER
#endif
#ifdef LINUX_NETFILTER
#include
#include
#endif
/// Define to use getopt_long: GNU extension, should check _GNU_SOURCE
#define PARSE_LONG_OPT
#ifdef PARSE_LONG_OPT
#include
#endif
/// Current version (recovered by Makefile for several release checks)
#define VERSION "1.4"
/// max size for buffers
#define MAX_BUF 100000
/// printf to stderr
#define ERR(x...) fprintf(stderr,x)
// Uncomment to add a lot of debug information.
//#define DEBUG
#ifdef DEBUG
/// printf for debug information
#define DBG(x...) printf(x)
#else
/// Disabled debug prints.
#define DBG(x...)
#endif
/// Timeout for udp 'connections' in seconds
#define UDP_TIMEOUT 30
/// Rule item.
struct rule_s {
/// binary buffer to match.
char *from;
/// binary buffer replacement.
char *to;
/// match from the command line.
const char *forig;
/// replacement from the command line.
const char *torig;
/// length of #from buffer.
int fs;
/// length of #to buffer.
int ts;
/// direction of rule
int dir;
};
/// Direction specifier of replacement rule.
enum {
ALL = 0,
IN = 1,
OUT = 2,
};
/// Connection state
enum state_e {
/// udp datagram received by netsed and send to server, no response yet.
UNREPLIED,
/// tcp accepted connection or udp 'connection' with a response from server.
ESTABLISHED,
/// tcp or udp disconnected (detected by an error on read or send).
/// @note all values after and including #DISCONNECTED are considered as
/// error and the connection will be discarded.
DISCONNECTED,
/// udp timeout expired.
TIMEOUT
};
/// This structure is used to track information about open connections.
struct tracker_s {
/// recvfrom information: 'connect' address for udp
struct sockaddr* csa;
/// size of #csa
socklen_t csl;
/// Connection socket to client
int csock;
/// Socket to forward to server
int fsock;
/// Last event time, for udp timeout
time_t time;
/// Connection state
enum state_e state;
/// By connection TTL
int* live;
/// chain it !
struct tracker_s * n;
};
/// Store current time (just after select returned).
time_t now;
/// Listening socket.
int lsock;
// Command line parameters are parsed to the following global variables.
/// Address family used for parameter resolution
int family = AF_UNSPEC;
/// TCP or UDP.
int tcp;
/// Local Port.
char* lport;
/// Remote Host.
char* rhost;
/// Remote Port.
char* rport;
/// Number of rules.
int rules;
/// Array of all rules.
struct rule_s *rule;
/// TTL part of the rule as a flat array to be able to copy it
/// in tracker_s::live for each connections.
int *rule_live;
/// List of connections.
struct tracker_s * connections = NULL;
/// True when SIGINT signal was received.
volatile int stop=0;
/// Display an error message followed by short usage information.
/// @param why the error message.
void short_usage_hints(const char* why) {
if (why) ERR("Error: %s\n\n",why);
ERR("Usage: netsed [option] proto lport rhost rport rule1 [ rule2 ... ]\n\n");
ERR(" use netsed -h for more information on usage.\n");
exit(1);
}
/// Display an error message followed by usage information.
/// @param why the error message.
void usage_hints(const char* why) {
if (why) ERR("Error: %s\n\n",why);
ERR("Usage: netsed [option] proto lport rhost rport rule1 [ rule2 ... ]\n\n");
#ifdef PARSE_LONG_OPT
ERR(" options - can be --ipv4 or -4 to force address resolution in IPv4,\n");
ERR(" --ipv6 or -6 to force address resolution in IPv6,\n");
ERR(" --ipany to resolve the address in either IPv4 or IPv6.\n");
ERR(" - --help or -h to display this usage information.\n");
#else
ERR(" options - can be nothing, -4 to force address resolution in IPv4\n");
ERR(" or -6 to force address resolution in IPv6.\n");
ERR(" - -h to display this usage information.\n");
#endif
ERR(" proto - protocol specification (tcp or udp)\n");
ERR(" lport - local port to listen on (see README for transparent\n");
ERR(" traffic intercepting on some systems)\n");
ERR(" rhost - where connection should be forwarded (0 = use destination\n");
ERR(" address of incoming connection, see README)\n");
ERR(" rport - destination port (0 = dst port of incoming connection)\n");
ERR(" ruleN - replacement rules (see below)\n\n");
ERR("General syntax of replacement rules: s/pat1/pat2[/expire]\n\n");
ERR("This will replace all occurrences of pat1 with pat2 in any matching packet.\n");
ERR("An additional parameter, 'expire' of the form [CHAR][NUM], can be used to\n");
ERR("expire a rule after NUM successful substitutions during a given connection.\n");
ERR("The character CHAR is one of \"iIoO\", with the effect of restricting the rule\n");
ERR("to apply to incoming (\"iI\") or to outgoing (\"oO\") packets only, as seen from\n");
ERR("the client's perspective. Both of CHAR and NUM are optional.\n\n");
ERR("Eight-bit characters, including NULL and '/', can be applied using HTTP-like\n");
ERR("hex escape sequences (e.g. CRLF as %%0a%%0d).\n");
ERR("A match on '%%' can be achieved by specifying '%%%%'.\n\nExamples:\n");
ERR(" 's/andrew/mike/1' - replace 'andrew' with 'mike' (only first time)\n");
ERR(" 's/andrew/mike' - replace all occurrences of 'andrew' with 'mike'\n");
ERR(" 's/andrew/mike%%00%%00' - replace 'andrew' with 'mike\\x00\\x00'\n");
ERR(" (manually padding to keep original size)\n");
ERR(" 's/%%%%/%%2f/20' - replace the 20 first occurrence of '%%' with '/'\n");
ERR(" 's/andrew/mike/o' - the server will always see 'mike', never 'andrew'\n\n");
ERR(" 's/Rilke/Proust/o s/Proust/Rilke/i'\n");
ERR(" - let Rilke travel incognito as Proust\n\n");
ERR("Rules are not active across packet boundaries, and they are evaluated\n");
ERR("from first to last, not yet expired rule, as stated on the command line.\n");
exit(1);
}
/// Helper function to free a tracker_s item.
/// csa will be freed if needed, sockets will be closed
/// @param conn pointer to free.
void freetracker (struct tracker_s * conn)
{
if(conn->csa != NULL) { // udp
free(conn->csa);
} else { // tcp
close(conn->csock);
}
close(conn->fsock);
free(conn);
}
/// Close all sockets
/// to use before exit.
void clean_socks(void)
{
close(lsock);
// close all tracker
while(connections != NULL) {
struct tracker_s * conn = connections;
connections = conn->n;
freetracker(conn);
}
}
#ifdef __GNUC__
// avoid gcc from inlining those two function when optimizing, as otherwise
// the function would break strict-aliasing rules by dereferencing pointers...
in_port_t get_port(struct sockaddr *sa) __attribute__ ((noinline));
void set_port(struct sockaddr *sa, in_port_t port) __attribute__ ((noinline));
#endif
/// Extract the port information from a sockaddr for both IPv4 and IPv6.
/// @param sa sockaddr to get port from
in_port_t get_port(struct sockaddr *sa) {
switch (sa->sa_family) {
case AF_INET:
return ntohs(((struct sockaddr_in *) sa)->sin_port);
case AF_INET6:
return ntohs(((struct sockaddr_in6 *) sa)->sin6_port);
default:
return 0;
}
} /* get_port(struct sockaddr *) */
/// Set the port information in a sockaddr for both IPv4 and IPv6.
/// @param sa sockaddr to update
/// @param port port value
void set_port(struct sockaddr *sa, in_port_t port) {
switch (sa->sa_family) {
case AF_INET:
((struct sockaddr_in *) sa)->sin_port = htons(port);
break;
case AF_INET6:
((struct sockaddr_in6 *) sa)->sin6_port = htons(port);
default:
break;
}
} /* set_port(struct sockaddr *, in_port_t) */
/// Detect if address in the addr_any value for both IPv4 and IPv6.
/// @param sa sockaddr to test
/// @return true if sa in addr_any
int is_addr_any(struct sockaddr *sa) {
switch (sa->sa_family) {
case AF_INET:
return (((struct sockaddr_in *) sa)->sin_addr.s_addr == htonl(INADDR_ANY));
case AF_INET6:
return !memcmp(&((struct sockaddr_in6 *) sa)->sin6_addr, &in6addr_any, sizeof(in6addr_any));
default:
return 0;
}
} /* is_addr_any(struct sockaddr *) */
/// Display an error message and exit.
void error(const char* reason) {
ERR("[-] Error: %s\n",reason);
ERR("netsed: exiting.\n");
clean_socks();
exit(2);
}
/// Hex digit to parsing the % notation in rules
char hex[]="0123456789ABCDEF";
/// Convert the % notation in rules to plain binary data
/// @param r rule to update
void shrink_to_binary(struct rule_s* r) {
int i;
r->from=malloc(strlen(r->forig));
r->to=malloc(strlen(r->torig));
if ((!r->from) || (!r->to)) error("shrink_to_binary: unable to malloc() buffers");
for (i=0;iforig);i++) {
if (r->forig[i]=='%') {
// Have to shrink.
i++;
if (r->forig[i]=='%') {
// '%%' -> '%'
r->from[r->fs]='%';
r->fs++;
} else {
int hexval;
char* x;
if (!r->forig[i]) error("shrink_to_binary: src pattern: unexpected end.");
if (!r->forig[i+1]) error("shrink_to_binary: src pattern: unexpected end.");
x=strchr(hex,toupper(r->forig[i]));
if (!x) error("shrink_to_binary: src pattern: non-hex sequence.");
hexval=(x-hex)*16;
x=strchr(hex,toupper(r->forig[i+1]));
if (!x) error("shrink_to_binary: src pattern: non-hex sequence.");
hexval+=(x-hex);
r->from[r->fs]=hexval;
r->fs++; i++;
}
} else {
// Plaintext case.
r->from[r->fs]=r->forig[i];
r->fs++;
}
}
for (i=0;itorig);i++) {
if (r->torig[i]=='%') {
// Have to shrink.
i++;
if (r->torig[i]=='%') {
// '%%' -> '%'
r->to[r->ts]='%';
r->ts++;
} else {
int hexval;
char* x;
if (!r->torig[i]) error("shrink_to_binary: dst pattern: unexpected end.");
if (!r->torig[i+1]) error("shrink_to_binary: dst pattern: unexpected end.");
x=strchr(hex,toupper(r->torig[i]));
if (!x) error("shrink_to_binary: dst pattern: non-hex sequence.");
hexval=(x-hex)*16;
x=strchr(hex,toupper(r->torig[i+1]));
if (!x) error("shrink_to_binary: dst pattern: non-hex sequence.");
hexval+=(x-hex);
r->to[r->ts]=hexval;
r->ts++; i++;
}
} else {
// Plaintext case.
r->to[r->ts]=r->torig[i];
r->ts++;
}
}
}
/// parse the command line parameters
/// @param argc number of arguments
/// @param argv array of string parameters
void parse_params(int argc,char* argv[]) {
int i;
// parse options, GNU allows us to use long options
#ifdef PARSE_LONG_OPT
static struct option long_options[] = {
{"ipv4", 0, 0, '4'},
{"ipv6", 0, 0, '6'},
{"help", 0, 0, 'h'},
{"ipany", 0, &family, AF_UNSPEC},
{0, 0, 0, 0}
};
while ((i = getopt_long(argc, argv, "46h", long_options, NULL)) != -1)
#else
while ((i = getopt(argc, argv, "46h")) != -1)
#endif
{
switch(i) {
case 0: // long option
break;
case '4':
family = AF_INET;
break;
case '6':
family = AF_INET6;
break;
case 'h':
usage_hints(NULL);
default:
usage_hints("unsupported optional parameter");
}
}
// parse remaining positional parameters
if (argc 1) ? "s" : "");
}
/// Bind and optionally listen to a socket for netsed server port.
/// @param af address family.
/// @param tcp 1 tcp, 0 udp.
/// @param portstr string representing the port to bind
/// (will be resolved using getaddrinfo()).
void bind_and_listen(int af, int tcp, const char *portstr) {
int ret;
struct addrinfo hints, *res, *reslist;
memset(&hints, '\0', sizeof(hints));
hints.ai_family = af;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
if ((ret = getaddrinfo(NULL, portstr, &hints, &reslist))) {
ERR("getaddrinfo(): %s\n", gai_strerror(ret));
error("Impossible to resolve listening port.");
}
/* We have useful addresses. */
for (res = reslist; res; res = res->ai_next) {
int one = 1;
if ( (lsock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0)
continue;
setsockopt(lsock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
//fcntl(lsock,F_SETFL,O_NONBLOCK);
/* Make our best to decide on dual-stacked listener. */
one = (family == AF_UNSPEC) ? 0 /* All families */ : 1; /* Preconditioned addr */
if (res->ai_family == AF_INET6)
if (setsockopt(lsock, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)))
printf(" Failed to unset IPV6_V6ONLY: %s.\n", strerror(errno));
if (bind(lsock, res->ai_addr, res->ai_addrlen) < 0) {
ERR("bind(): %s", strerror(errno));
close(lsock);
continue;
}
if (tcp) {
if (listen(lsock, 16) < 0) {
close(lsock);
continue;
}
} else { // udp
int one=1;
setsockopt(lsock,SOL_SOCKET,SO_OOBINLINE,&one,sizeof(int));
}
/* Successfully bound and now also listening. */
break;
}
freeaddrinfo(reslist);
if (res == NULL)
error("Listening socket failed.");
}
/// Buffer for receiving a single packet or datagram
char buf[MAX_BUF];
/// Buffer containing modified packet or datagram
char b2[MAX_BUF];
/// Applies the rules to global buffer buf.
/// @param siz useful size of the data in buf.
/// @param live TTL state of current connection.
/// @param packet direction
int sed_the_buffer(int siz, int* live, int dir) {
int i=0,j=0;
int newsize=0;
int changes=0;
int gotchange=0;
for (i=0;ifsock,buf,sizeof(buf));
if ((rd<0) && (errno!=EAGAIN))
{
DBG("[!] server disconnected. (rd err) %s\n",strerror(errno));
conn->state = DISCONNECTED;
}
if (rd == 0) {
// nothing read but select said ok, so EOF
DBG("[!] server disconnected. (rd)\n");
conn->state = DISCONNECTED;
}
if (rd>0) {
printf("[+] Caught server -> client packet.\n");
rd=sed_the_buffer(rd, conn->live, IN);
conn->time = now;
conn->state = ESTABLISHED;
if (sendto(conn->csock,b2,rd,0,conn->csa, conn->csl)<=0) {
DBG("[!] client disconnected. (wr)\n");
conn->state = DISCONNECTED;
}
}
}
/// Receive a packet from the client, 'sed' it, send it to the server.
/// @param conn connection giving the sockets to use.
void client2server_sed(struct tracker_s * conn) {
ssize_t rd;
rd=read(conn->csock,buf,sizeof(buf));
if ((rd<0) && (errno!=EAGAIN))
{
DBG("[!] client disconnected. (rd err)\n");
conn->state = DISCONNECTED;
}
if (rd == 0) {
// nothing read but select said ok, so EOF
DBG("[!] client disconnected. (rd)\n");
conn->state = DISCONNECTED;
}
b2server_sed(conn, rd);
}
/// Send the content of global buffer b2 to the server as packet or datagram.
/// @param conn connection giving the sockets to use.
/// @param rd size of b2 content.
void b2server_sed(struct tracker_s * conn, ssize_t rd) {
if (rd>0) {
printf("[+] Caught client -> server packet.\n");
rd=sed_the_buffer(rd, conn->live, OUT);
conn->time = now;
if (write(conn->fsock,b2,rd)<=0) {
DBG("[!] server disconnected. (wr)\n");
conn->state = DISCONNECTED;
}
}
}
/// Handle SIGINT signal for clean exit.
void sig_int(int signo)
{
DBG("[!] user interrupt request (%d)\n",getpid());
stop = 1;
}
/// This is main...
int main(int argc,char* argv[]) {
int ret;
in_port_t fixedport = 0;
struct sockaddr_storage fixedhost;
struct addrinfo hints, *res, *reslist;
struct tracker_s * conn;
memset(&fixedhost, '\0', sizeof(fixedhost));
printf("netsed " VERSION " by Julien VdG \n"
" based on 0.01c from Michal Zalewski \n");
setbuffer(stdout,NULL,0);
parse_params(argc, argv);
memset(&hints, '\0', sizeof(hints));
hints.ai_family = family;
hints.ai_flags = AI_CANONNAME;
hints.ai_socktype = tcp ? SOCK_STREAM : SOCK_DGRAM;
if ((ret = getaddrinfo(rhost, rport, &hints, &reslist))) {
ERR("getaddrinfo(): %s\n", gai_strerror(ret));
error("Impossible to resolve remote address or port.");
}
/* We have candidates for remote host. */
for (res = reslist; res; res = res->ai_next) {
int sd = -1;
if ( (sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0)
continue;
/* Has successfully built a socket for this address family. */
/* Record the address structure and the port. */
fixedport = get_port(res->ai_addr);
if (!is_addr_any(res->ai_addr))
memcpy(&fixedhost, res->ai_addr, res->ai_addrlen);
close(sd);
break;
}
freeaddrinfo(reslist);
if (res == NULL)
error("Failed in resolving remote host.");
if (fixedhost.ss_family && fixedport)
printf("[+] Using fixed forwarding to %s,%s.\n",rhost,rport);
else if (fixedport)
printf("[+] Using dynamic (transparent proxy) forwarding with fixed port %s.\n",rport);
else if (fixedhost.ss_family)
printf("[+] Using dynamic (transparent proxy) forwarding with fixed addr %s.\n",rhost);
else
printf("[+] Using dynamic (transparent proxy) forwarding.\n");
bind_and_listen(fixedhost.ss_family, tcp, lport);
printf("[+] Listening on port %s/%s.\n", lport, (tcp)?"tcp":"udp");
signal(SIGPIPE, SIG_IGN);
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = sig_int;
if (sigaction(SIGINT, &sa, NULL) == -1) error("netsed: sigaction() failed");
while (!stop) {
struct sockaddr_storage s;
socklen_t l = sizeof(s);
struct sockaddr_storage conho;
in_port_t conpo;
char ipstr[INET6_ADDRSTRLEN], portstr[12];
int sel;
fd_set rd_set;
struct timeval timeout, *ptimeout;
int nfds = lsock;
FD_ZERO(&rd_set);
FD_SET(lsock,&rd_set);
timeout.tv_sec = UDP_TIMEOUT+1;
timeout.tv_usec = 0;
ptimeout = NULL;
{
conn = connections;
while(conn != NULL) {
if(tcp) {
FD_SET(conn->csock, &rd_set);
if (nfds < conn->csock) nfds = conn->csock;
} else {
// adjust timeout to earliest connection end time
int remain = UDP_TIMEOUT - (now - conn->time);
if (remain < 0) remain = 0;
if (timeout.tv_sec > remain) {
timeout.tv_sec = remain;
// time updated to need to timeout
ptimeout = &timeout;
}
}
FD_SET(conn->fsock, &rd_set);
if (nfds < conn->fsock) nfds = conn->fsock;
// point on next
conn = conn->n;
}
}
sel=select(nfds+1, &rd_set, (fd_set*)0, (fd_set*)0, ptimeout);
time(&now);
if (stop)
{
break;
}
if (sel < 0) {
DBG("[!] select fail! %s\n", strerror(errno));
break;
}
if (sel == 0) {
DBG("[*] select timeout. now: %d\n", now);
// Here we still have to go through the list to expire some udp
// connection if they timed out... But no descriptor will be set.
// For tcp, select will not timeout.
}
if (FD_ISSET(lsock, &rd_set)) {
int csock=-1;
ssize_t rd=-1;
if (tcp) {
csock = accept(lsock,(struct sockaddr*)&s,&l);
} else {
// udp does not handle accept, so track connections manually
// also set csock if a new connection need to be registered
// to share the code with tcp ;)
rd = recvfrom(lsock,buf,sizeof(buf),0,(struct sockaddr*)&s,&l);
if(rd >= 0) {
conn = connections;
while(conn != NULL) {
// look for existing connections
if ((conn->csl == l) && (0 == memcmp(&s, conn->csa, l))) {
// found
break;
}
// point on next
conn = conn->n;
}
// not found
if(conn == NULL) {
// udp 'connection' socket is the listening one
csock = lsock;
} else {
DBG("[+] Got incoming datagram from existing connection.\n");
}
} else {
ERR("recvfrom(): %s", strerror(errno));
}
}
// new connection (tcp accept, or udp conn not found)
if ((csock)>=0) {
int one=1;
getnameinfo((struct sockaddr *) &s, l, ipstr, sizeof(ipstr),
portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
printf("[+] Got incoming connection from %s,%s", ipstr, portstr);
conn = malloc(sizeof(struct tracker_s));
if(NULL == conn) error("netsed: unable to malloc() connection tracker struct");
// protocol specific init
if (tcp) {
setsockopt(csock,SOL_SOCKET,SO_OOBINLINE,&one,sizeof(int));
conn->csa = NULL;
conn->csl = 0;
conn->state = ESTABLISHED;
} else {
conn->csa = malloc(l);
if(NULL == conn->csa) error("netsed: unable to malloc() connection tracker sockaddr struct");
memcpy(conn->csa, &s, l);
conn->csl = l;
conn->state = UNREPLIED;
}
conn->csock = csock;
conn->time = now;
conn->live = malloc(rules*sizeof(int));
if(NULL == conn->live) error("netsed: unable to malloc() connection tracker sockaddr struct");
memcpy(conn->live, rule_live, rules*sizeof(int));
l = sizeof(s);
#ifndef LINUX_NETFILTER
// was OK for linux 2.2 nat
getsockname(csock,(struct sockaddr*)&s,&l);
#else
// for linux 2.4 and later
getsockopt(csock, SOL_IP, SO_ORIGINAL_DST,(struct sockaddr*)&s,&l);
#endif
getnameinfo((struct sockaddr *) &s, l, ipstr, sizeof(ipstr),
portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
printf(" to %s,%s\n", ipstr, portstr);
conpo = get_port((struct sockaddr *) &s);
memcpy(&conho, &s, sizeof(conho));
if (fixedport) conpo=fixedport;
if (fixedhost.ss_family)
memcpy(&conho, &fixedhost, sizeof(conho));
// forward to addr
memcpy(&s, &conho, sizeof(s));
set_port((struct sockaddr *) &s, conpo);
getnameinfo((struct sockaddr *) &s, l, ipstr, sizeof(ipstr),
portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV);
printf("[*] Forwarding connection to %s,%s\n", ipstr, portstr);
// connect will bind with some dynamic addr/port
conn->fsock = socket(s.ss_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
if (connect(conn->fsock,(struct sockaddr*)&s,l)) {
printf("[!] Cannot connect to remote server, dropping connection.\n");
freetracker(conn);
conn = NULL;
} else {
setsockopt(conn->fsock,SOL_SOCKET,SO_OOBINLINE,&one,sizeof(int));
conn->n = connections;
connections = conn;
}
}
// udp has data process forwarding
if((rd >= 0) && (conn != NULL)) {
b2server_sed(conn, rd);
}
} // lsock is set
// all other sockets
conn = connections;
struct tracker_s ** pconn = &connections;
while(conn != NULL) {
// incoming data ?
if(tcp && FD_ISSET(conn->csock, &rd_set)) {
client2server_sed(conn);
}
if(FD_ISSET(conn->fsock, &rd_set)) {
server2client_sed(conn);
}
// timeout ? udp only
DBG("[!] connection last time: %d, now: %d\n", conn->time, now);
if(!tcp && ((now - conn->time) >= UDP_TIMEOUT)) {
DBG("[!] connection timeout.\n");
conn->state = TIMEOUT;
}
if(conn->state >= DISCONNECTED) {
// remove it
(*pconn)=conn->n;
freetracker(conn);
conn=(*pconn);
} else {
// point on next
pconn = &(conn->n);
conn = conn->n;
}
}
}
clean_socks();
exit(0);
}
// vim:sw=2:sta:et:
netsed-1.4/test/000077500000000000000000000000001501143163000136115ustar00rootroot00000000000000netsed-1.4/test/tc_rules.rb000077500000000000000000000076611501143163000157730ustar00rootroot00000000000000#!/usr/bin/ruby
# netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You may also redistribute it or any part of it under the Ruby license to
# better integrate to your ruby scripts.
# The ruby license is available at http://www.ruby-lang.org/en/LICENSE.txt
# ---------------------------------------------------------------------------
#
# this file implements checks for netsed rules in class TC_RuleTest
require 'test/unit'
require './test_helper'
# Test Case for netsed rules
class TC_RuleTest < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
# General rule checker method used by actual tests
# - _datasent_ are send by a server,
# - _dataexpect_ are the corresponding expected data on the client side,
# - _rules_ is a set of rules passed to netsed.
def TCP_RuleCheck(datasent, dataexpect, rules)
serv = TCPServeSingleDataSender.new(SERVER, RPORT, datasent)
netsed = NetsedRun.new('tcp', LPORT, SERVER, RPORT, rules)
datarecv = TCPSingleDataRecv(SERVER, LPORT, 100)
serv.join
netsed.kill
assert_equal(dataexpect, datarecv)
end
# Check a basic rule.
def test_basic_rule
TCP_RuleCheck('test andrew is there' ,"test mike\0\0 is there", ['s/andrew/mike%00%00'])
end
# Check single char replacement.
#
# Note: This one fail without commit 387a9d46387e2488efac08931b0aab57c7594aa2,
# it returns "b b ba bab baba" !!
def test_smallpattern_rule
TCP_RuleCheck('a a aa aaa aaaa' ,"b b bb bbb bbbb", ['s/a/b'])
end
# Check with 2 rules.
def test_chain_2_rule
TCP_RuleCheck('test andrew is there' ,'test mike is here', ['s/andrew/mike', 's/there/here'])
end
# Check traditionally delimited rules
def test_traddelim_rule
TCP_RuleCheck('a a aa aaa aaaa' ,"b b bb bbb bbbb", ['s/a/b/'])
end
# General rule checker method in chat mode
# - _datasent_ is an array of data to sent 0:client 1:server,
# - _dataexpect_ are the corresponding expected data on the other side,
# - _rules_ is a set of rules passed to netsed.
def TCP_RuleChatCheck(datasent, dataexpect, rules)
netsed = NetsedRun.new('tcp', LPORT, SERVER, RPORT, rules)
datarecv = []
serv = TCPServeSingleConnection.new(SERVER, RPORT) { |s|
datarecv[0] = s.recv( 100 )
s.write(datasent[1])
}
streamSock = TCPSocket.new(SERVER, LPORT)
streamSock.write( datasent[0] )
datarecv[1] = streamSock.recv( 100 )
streamSock.close
serv.join
netsed.kill
assert_equal_objects(dataexpect, datarecv)
end
# Check direction rules
# tests based on tcp chat: test_case_04_Chat
def test_direction_rule
TCP_RuleChatCheck(
['client: bla bla Rilke Proust', 'server: ok Proust ok Rilke'],
['client: bla bla Proust Proust', 'server: ok Rilke ok Rilke'],
['s/Rilke/Proust/o', 's/Proust/Rilke/i'])
end
# Check direction+ttl rules
# tests based on tcp chat: test_case_04_Chat
def test_direction_ttl_rule
TCP_RuleChatCheck(
['client: bla bla Rilke Rilke', 'server: ok Proust ok Proust'],
['client: bla bla Proust Rilke', 'server: ok Rilke ok Proust'],
['s/Rilke/Proust/o1', 's/Proust/Rilke/i1'])
end
end
# vim:sw=2:sta:et:
netsed-1.4/test/tc_system.rb000077500000000000000000000051601501143163000161550ustar00rootroot00000000000000#!/usr/bin/ruby
# netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You may also redistribute it or any part of it under the Ruby license to
# better integrate to your ruby scripts.
# The ruby license is available at http://www.ruby-lang.org/en/LICENSE.txt
# ---------------------------------------------------------------------------
#
# this file implements checks for netsed system behaviour in class TC_SystemTest
require 'test/unit'
require './test_helper'
require 'thread'
# Test Case for netsed system behaviour
class TC_SystemTest < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
# Check if netsed can take high CPU load.
#
# Note: case of debian bug #586037.
#
# Actually running it against the old version blocks.
# Old netsed does not have the SIGINT handling (you have to kill it manually)
# but the test detects the load.
def test_TightNonBlockingLoop
mutex=Mutex.new
datasent = 'test andrew and andrew'
dataexpect = 'test mike and andrew'
serv = TCPServeSingleConnection.new(SERVER, RPORT) { |s|
# to ensure the server stays open
mutex.synchronize do
end
}
netsed = NetsedRun.new('tcp', LPORT, SERVER, RPORT, ['s/andrew/mike/1'])
cpuload = 0
# ensure both server and client have open socket to netsed
# and see if it reaches a high load
mutex.synchronize do
streamSock = TCPSocket.new(SERVER, LPORT)
# wait for the cpu load to rise
sleep 1
# check netsed cpu usage
# it's the child process that will take the cpu...
ret = `ps --ppid #{netsed.pid} -o %cpu h`
#puts "#{netsed.pid}: #{ret}"
cpuload = ret.to_i
streamSock.close
end
serv.join
netsed.kill
assert_operator(cpuload, :<, 50, 'netsed child process taking too much CPU.')
end
end
# vim:sw=2:sta:et:
netsed-1.4/test/tc_tcp.rb000077500000000000000000000124151501143163000154200ustar00rootroot00000000000000#!/usr/bin/ruby
# netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You may also redistribute it or any part of it under the Ruby license to
# better integrate to your ruby scripts.
# The ruby license is available at http://www.ruby-lang.org/en/LICENSE.txt
# ---------------------------------------------------------------------------
#
# this file implements checks for netsed behaviour regarding tcp connections.
# * TC_TCPTest run the tests on IPv4.
# * TC_TCPTest6 is a generated class which rerun all the tests on IPv6.
#
require 'test/unit'
require './test_helper'
# Test Case for TCP
#
# Note: it runs netsed in the setup to allow to rerun all tests in a single
# netsed invocation by test_group_all
class TC_TCPTest < Test::Unit::TestCase
CONFIG={:SERVER=>LH_IPv4,:OPTIONS=>'-4'}
# Launch netsed
def setup
#puts self.class::CONFIG[:SERVER]
@netsed = NetsedRun.new('tcp', LPORT, self.class::CONFIG[:SERVER], RPORT, ['s/andrew/mike'], self.class::CONFIG[:OPTIONS])
end
# Kill netsed
def teardown
@netsed.kill
end
# Check when server disconnects
def test_case_01_ServerDisconnect
datasent = 'test andrew and andrew'
dataexpect = 'test mike and mike'
serv = TCPServeSingleDataSender.new(self.class::CONFIG[:SERVER], RPORT, datasent)
datarecv = TCPSingleDataRecv(self.class::CONFIG[:SERVER], LPORT, 100)
serv.join
assert_equal(dataexpect, datarecv)
end
# Check when there is no server
def test_case_02_NoServer
datarecv = TCPSingleDataRecv(self.class::CONFIG[:SERVER], LPORT, 100)
assert([nil, ''].include?(datarecv), "Expected nil or empty string")
end
# Check when the client sends the data
def test_case_03_ClientSendData
datasent = 'test andrew and andrew'
dataexpect = 'test mike and mike'
serv = TCPServeSingleDataReciever.new(self.class::CONFIG[:SERVER], RPORT, 100)
TCPSingleDataSend(self.class::CONFIG[:SERVER], LPORT, datasent)
datarecv=serv.join
assert_equal(dataexpect, datarecv)
end
# Check when both client and server send data
def test_case_04_Chat
datasent = ['client: bla bla andrew', 'server: ok andrew ok']
dataexpect = ['client: bla bla mike', 'server: ok mike ok']
datarecv = []
serv = TCPServeSingleConnection.new(self.class::CONFIG[:SERVER], RPORT) { |s|
datarecv[0] = s.recv( 100 )
s.write(datasent[1])
}
streamSock = TCPSocket.new(self.class::CONFIG[:SERVER], LPORT)
streamSock.write( datasent[0] )
datarecv[1] = streamSock.recv( 100 )
streamSock.close
serv.join
assert_equal_objects(dataexpect, datarecv)
end
# Check when there are multiple clients
def test_case_05_ServeMultiple
datasent = ['0: bla bla andrew', '1: ok andrew ok']
dataexpect = ['0: bla bla mike', '1: ok mike ok']
# open server
datarecv=[]
serv = TCPServeMultipleConnection.new(self.class::CONFIG[:SERVER], RPORT, 2) { |s, j|
#puts "Thread #{j} accepted connection"
datarecv[j] = s.recv( 100 )
}
# open connection to 2 server simultaneously
cs=[]
for i in 0..1 do
#puts "client #{i}"
cs[i] = TCPSocket.new(self.class::CONFIG[:SERVER], LPORT)
sleep 0.001 # sleep to ensure connection order on server thread
end
# write to each connections
for i in 0..1 do
cs[i].write( datasent[i] )
end
cs.each {|s| s.close}
serv.join
assert_equal_objects(dataexpect, datarecv)
end
# Check that netsed is still here for the test_group_all call ;)
def test_case_zz_LastCheck
datasent = 'test andrew and andrew'
dataexpect = 'test mike and mike'
serv = TCPServeSingleDataSender.new(self.class::CONFIG[:SERVER], RPORT, datasent)
datarecv = TCPSingleDataRecv(self.class::CONFIG[:SERVER], LPORT, 100)
serv.join
assert_equal(dataexpect, datarecv)
end
# Rerun all 'test_case*' methods in one test to allow check that netsed is not crashed by any test.
def test_group_all
tests = self.class::get_all_test_case
tests.sort.each { |test|
__send__(test)
}
end
private
# Returns all 'test_case*' methods in the class
def self.get_all_test_case
method_names = public_instance_methods(true)
return method_names.delete_if {|method_name| method_name !~ /^test_case./}
end
end
# Manually generate class TC_TCPTest6
# to rerun all TCP tests with IPv6 localhost,
# inspired by http://www.ruby-forum.com/topic/204730.
TC_TCPTest6=Class.new(TC_TCPTest)
TC_TCPTest6.const_set(:CONFIG, {:SERVER=>LH_IPv6,:OPTIONS=>'-6'})
# vim:sw=2:sta:et:
netsed-1.4/test/tc_ttl.rb000077500000000000000000000036371501143163000154430ustar00rootroot00000000000000#!/usr/bin/ruby
# netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# this file implements checks for the TTL (time-to-live) feature of netsed rules in the class TC_TTLTest.
require 'test/unit'
require './test_helper'
# Test Case for netsed TTL (time-to-live) feature
class TC_TTLTest < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
# Check first occurrence
def test_TTL_1
datasent = 'test andrew and andrew'
dataexpect = 'test mike and andrew'
serv = TCPServeSingleDataSender.new(SERVER, RPORT, datasent)
netsed = NetsedRun.new('tcp', LPORT, SERVER, RPORT, ['s/andrew/mike/1'])
datarecv = TCPSingleDataRecv(SERVER, LPORT, 100)
serv.join
netsed.kill
assert_equal(dataexpect, datarecv)
end
# Check 20 occurrences
def test_TTL_20
datasent = '% %% %%% %%%% %%%%% %%%%%% %%%%%%%'
dataexpect = '/ // /// //// ///// /////% %%%%%%%'
serv = TCPServeSingleDataSender.new(SERVER, RPORT, datasent)
netsed = NetsedRun.new('tcp', LPORT, SERVER, RPORT, ['s/%%/%2f/20'])
datarecv = TCPSingleDataRecv(SERVER, LPORT, 100)
serv.join
netsed.kill
assert_equal(dataexpect, datarecv)
end
# Check first occurrence in several connections: the TTL is not global.
def test_TTL_1_byConnections
datasent = 'test andrew and andrew'
dataexpect = 'test mike and andrew'
netsed = NetsedRun.new('tcp', LPORT, SERVER, RPORT, ['s/andrew/mike/1'])
serv = TCPServeSingleDataSender.new(SERVER, RPORT, datasent)
datarecv = TCPSingleDataRecv(SERVER, LPORT, 100)
serv.join
assert_equal(dataexpect, datarecv, 'At first connection')
# once again
serv = TCPServeSingleDataSender.new(SERVER, RPORT, datasent)
datarecv = TCPSingleDataRecv(SERVER, LPORT, 100)
serv.join
assert_equal(dataexpect, datarecv, 'At second connection')
ensure
netsed.kill
end
end
# vim:sw=2:sta:et:
netsed-1.4/test/tc_udp.rb000077500000000000000000000116551501143163000154270ustar00rootroot00000000000000#!/usr/bin/ruby
# -*- coding: utf-8 -*-
# netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You may also redistribute it or any part of it under the Ruby license to
# better integrate to your ruby scripts.
# The ruby license is available at http://www.ruby-lang.org/en/LICENSE.txt
# ---------------------------------------------------------------------------
#
# this file implements checks for netsed behaviour regarding udp 'connections'.
# * TC_UDPTest run the tests on IPv4.
# * TC_UDPTest6 is a generated class which rerun all the tests on IPv6.
#
require 'test/unit'
require './test_helper'
# Test Case for UDP
#
# Note: it runs netsed in the setup to allow to rerun all tests in a single
# netsed invocation by test_group_all
class TC_UDPTest < Test::Unit::TestCase
SERVER=LH_IPv4
# Launch netsed
def setup
#puts self.class::SERVER
@netsed = NetsedRun.new('udp', LPORT, self.class::SERVER, RPORT, ['s/andrew/mike'])
end
# Kill netsed
def teardown
@netsed.kill
end
# Check single datagram transmission
def test_case_01_single
datasent = 'test andrew and andrew'
dataexpect = 'test mike and mike'
serv = UDPSocket.new
serv.bind(self.class::SERVER, RPORT)
UDPSingleDataSend(self.class::SERVER, LPORT, datasent)
datarecv = serv.recv( 100 )
serv.close
assert_equal(dataexpect, datarecv)
end
# Check when both client and server send datagrams
def test_case_02_Chat
datasent = ['client: bla bla andrew', 'server: ok andrew ok']
dataexpect = ['client: bla bla mike', 'server: ok mike ok']
datarecv = []
serv = UDPSocket.new
serv.bind(self.class::SERVER, RPORT)
dataSock = UDPSocket.new
dataSock.connect(self.class::SERVER, LPORT)
dataSock.write( datasent[0] )
datarecv[0],senderaddr = serv.recvfrom( 100 )
serv.send(datasent[1], 0, senderaddr[3], senderaddr[1])
datarecv[1] = dataSock.recv( 100 )
dataSock.close
serv.close
assert_equal_objects(dataexpect, datarecv)
end
# Check when there are multiple clients
def test_case_03_ServeMultiple
datasent = ['0: bla bla andrew', '1: ok andrew ok', '2: bla andrew', '3: andrew ok']
dataexpect = ['0: bla bla mike', '1: ok mike ok', '2: bla mike', '3: mike ok']
datarecv=[]
# open server
serv = UDPSocket.new
serv.bind(self.class::SERVER, RPORT)
dataSock = UDPSocket.new
dataSock.connect(self.class::SERVER, LPORT)
dataSock.write( datasent[0] )
datarecv[0],senderaddr = serv.recvfrom( 100 )
serv.send(datasent[1], 0, senderaddr[3], senderaddr[1])
datarecv[1] = dataSock.recv( 100 )
cs=[]
for i in 0..1 do
cs[i] = UDPSocket.new
cs[i].connect(self.class::SERVER, LPORT)
cs[i].write( datasent[i] )
end
for i in 0..1 do
datarecv[i],senderaddr = serv.recvfrom( 100 )
serv.send(datasent[i+2], 0, senderaddr[3], senderaddr[1])
end
for i in 0..1 do
datarecv[i+2] = cs[i].recv( 100 )
cs[i].close
end
serv.close
assert_equal_objects(dataexpect, datarecv)
end
# Check that netsed is still here for the test_group_all call ;)
def test_case_zz_LastCheck
datasent = 'test andrew and andrew'
dataexpect = 'test mike and mike'
serv = UDPSocket.new
serv.bind(self.class::SERVER, RPORT)
UDPSingleDataSend(self.class::SERVER, LPORT, datasent)
datarecv = serv.recv( 100 )
serv.close
assert_equal(dataexpect, datarecv)
end
# Rerun all 'test_case*' methods in one test to allow check that netsed is not crashed by any test.
def test_group_all
tests = self.class::get_all_test_case
tests.sort.each { |test|
__send__(test)
}
end
private
# Returns all 'test_case*' methods in the class
def self.get_all_test_case
method_names = public_instance_methods(true)
return method_names.delete_if {|method_name| method_name !~ /^test_case./}
end
end
# Manually generate class TC_UDPTest6
# to rerun all UDP tests with IPv6 localhost,
# inspired by http://www.ruby-forum.com/topic/204730.
#TC_UDPTest6=Class.new(TC_UDPTest)
#TC_UDPTest6.const_set(:SERVER, LH_IPv6)
# for some reasons UDPSocket.connect fails with IPv6 addr :(
# vim:sw=2:sta:et:
netsed-1.4/test/test_helper.rb000066400000000000000000000146651501143163000164700ustar00rootroot00000000000000#!/usr/bin/ruby
# helper function for netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You may also redistribute it or any part of it under the Ruby license to
# better integrate to your ruby scripts.
# The ruby license is available at http://www.ruby-lang.org/en/LICENSE.txt
# ---------------------------------------------------------------------------
require 'socket'
LH_IPv4 = '127.0.0.1'
LH_IPv6 = '::1'
#default values for all test classes
LPORT=20000
RPORT=20001
SERVER=LH_IPv4
# Run a netsed instance with given parameters.
class NetsedRun
attr_reader :data
# Launch netsed with given parameters.
def initialize(proto, lport, rhost, rport, rules, options='')
@cmd="../netsed #{options} #{proto} #{lport} #{rhost} #{rport} #{rules.join(' ')}"
@pipe=IO.popen(@cmd)
@data=''
@pipe.sync = true
# waiting for netsed to listen
begin
line = @pipe.gets
@data << line.to_s
end until line =~ /^\[\+\] Listening on port/
end
# Kill (INT) and wait netsed exit
# also returns standard output
def kill
Process.kill('INT', @pipe.pid)
Process.wait(@pipe.pid)
@data << @pipe.read
@pipe.close
return @data
end
# Returns netsed PID
def pid
@pipe.pid
end
end
# TCP Server that accept multiple connections
class TCPServeMultipleConnection
# Creates a thread server on _addr_, _port_
# the block is called for every accepted connections (up to _nbconnections_)
# once the block exits, the socket is closed.
def initialize(addr, port, nbconnections) # :yields: socket, index
dts = TCPServer.new(addr, port)
@th = Thread.start {
ths=[]
for i in 0..nbconnections-1 do
sa=dts.accept
ths[i] = Thread.start(i, sa) {|j, s|
yield s,j
s.close
}
end
ths.each {|tha| tha.join}
dts.close
}
end
# Wait for the server to complete, it will once all connections are processed.
def join
@th.join
end
end
# TCP Server that accept a single connection
class TCPServeSingleConnection
# Creates a thread server on _addr_, _port_
# the block is called for first accepted connection
# once the block exits, the socket is closed.
def initialize(addr, port) # :yields: socket
dts = TCPServer.new(addr, port)
@th = Thread.start {
s=dts.accept
yield s
s.close
dts.close
}
end
# Wait for the server to complete, it will once the connection is processed.
def join
@th.join
end
end
# TCP Server that accept a single connection and sent data to it
class TCPServeSingleDataSender < TCPServeSingleConnection
# Creates a thread server on _addr_, _port_ that send _data_ on connection,
# then closes the socket.
def initialize(addr, port, data)
super(addr, port) { |s|
s.write(data)
}
end
end
# TCP Server that accept a single connection and receive data from it
class TCPServeSingleDataReciever < TCPServeSingleConnection
# Creates a thread server on _addr_, _port_ that receive up to _maxlen_
# on connection, then closes the socket.
def initialize(addr, port, maxlen)
super(addr, port) { |s|
@datarecv=s.recv(maxlen)
}
end
# Wait for the server to complete, and return the received data.
def join
super
return @datarecv
end
end
# Receive up to _maxlen_ data from a TCP Socket on _addr_,_port_
def TCPSingleDataRecv(addr, port, maxlen)
streamSock = TCPSocket.new(addr, port)
data = streamSock.recv( maxlen )
streamSock.close
return data
end
# Send _data_ to a TCP Socket on _addr_,_port_
def TCPSingleDataSend(addr, port, data)
streamSock = TCPSocket.new(addr, port)
streamSock.write( data )
streamSock.close
end
# Send _data_ to a UDP Socket on _addr_,_port_
def UDPSingleDataSend(addr, port, data)
dataSock = UDPSocket.new
dataSock.connect(addr, port)
dataSock.write( data )
dataSock.close
end
# Recursively compare two objects. Asserts if a difference was found.
#
# Note: The function is mostly inspired from the code snippet published
# by Scott Bronson on http://gist.github.com/287675
# rewritten using Test::Unit::Assertions to better fit in tests
def assert_equal_objects(expected, actual, message=nil, path='')
if path=='' then
prefix="Objects differ:"
else
prefix="Objects differ at #{path}:"
end
if expected.kind_of?(Hash)
extraexpectedkeys = expected.keys - actual.keys
full_message = build_message(message, "#{prefix} extra keys in expected: .\n", extraexpectedkeys)
assert_block(full_message) { extraexpectedkeys.length == 0 }
extraactualkeys = actual.keys - expected.keys
full_message = build_message(message, "#{prefix} extra keys in actual: .\n", extraactualkeys)
assert_block(full_message) { extraactualkeys.length == 0 }
expectedkeys=expected.keys
begin
expectedkeys.sort!
rescue NoMethodError
end
expectedkeys.each do |key|
assert_equal_objects expected[key], actual[key], message, path.dup << build_message(nil,"[?]",key).to_s
end
elsif (expected.kind_of?(Enumerable) && !expected.kind_of?(String)) && (actual.kind_of?(Enumerable) && !actual.kind_of?(String))
full_message = build_message(message, "#{prefix} expected has #{expected.length} and actual has #{actual.length} items.\n expected but was\n.\n", expected, actual)
assert_block(full_message) { expected.length == actual.length }
(0..expected.length).each do |i|
assert_equal_objects expected[i], actual[i], message, path.dup << "[#{i}]"
end
elsif expected != actual
full_message = build_message(message, "#{prefix}\n expected but was\n.\n", expected, actual)
assert_block(full_message) { false }
end
end
# vim:sw=2:sta:et:
netsed-1.4/test/ts_full.rb000077500000000000000000000030651501143163000156150ustar00rootroot00000000000000#!/usr/bin/ruby
# netsed Unit::Tests
# (c) 2010 Julien Viard de Galbert
#
# ---------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You may also redistribute it or any part of it under the Ruby license to
# better integrate to your ruby scripts.
# The ruby license is available at http://www.ruby-lang.org/en/LICENSE.txt
# ---------------------------------------------------------------------------
#
# This test suite run all available tests named tc_*.rb
#
# It also makes sure the tests are run from the directory where the script is
# ( hopefully test/ in netsed source directory, so that netsed binary can be
# found in ../netsed ).
#
# :main:ts_full.rb
require 'test/unit'
Dir.chdir(File.dirname(__FILE__))
require './test_helper'
Dir .glob('tc_*.rb') { |f|
#puts "adding #{f}"
require "./" + f
}
# vim:sw=2:sta:et: