Net-Proxy-0.13000755001750001750 012425533446 12361 5ustar00bookbook000000000000README100644001750001750 111612425533446 13321 0ustar00bookbook000000000000Net-Proxy-0.13Net::Proxy ---------- This module is a framework for creating various kinds of network proxies in a very simple way. A proxy is a program that transfer data across a network boundary between a client and a server. Net::Proxy introduces the concept of "connectors", which abstract the server part (connected to the client) and the client part (connected to the server) of the proxy. This makes it very easy to implement specific techniques to cross a given network boundary, possibly by using a proxy on one side of the network fence, and a reverse-proxy on the other side of the fence. Changes100644001750001750 1137412425533446 13763 0ustar00bookbook000000000000Net-Proxy-0.13Revision history for Perl extension Net::Proxy 0.13 Sun Nov 2 2014 [ENHANCEMENTS] - dependency on perl 5.6 should be written as 5.006 (RT #36752, Andreas König) - Make maximum buffer size user-configurable (RT #60751, Daniel Burr) - Fix several bugs happening when a connection closes (RT #60641, Daniel Burr) [DOCUMENTATION] - reformat the documentation for better linkability [SCRIPTS] - connect-tunnel: Fix RT #42525 (Peter Oliver) by making the --tunnel regexp more liberal - added the eg/forwarder.pl example script [PACKAGING] - the distribution is now packaged using Dist::Zilla [TESTS] - pod and compilation tests are now handled by Dist::Zilla plugins 0.12 Thu Oct 18 00:49:42 CEST 2007 [ENHANCEMENTS] - print a meaningful error message when the ssl connector can't listen [SCRIPTS] - connect-tunnel now dies early if LWP::UserAgent is not installed (and t/90compile.t does pass as well) [TESTS] - prevent t/21connect.t to fail when a environment proxy is defined 0.11 Mon Oct 15 03:44:30 CEST 2007 [ENHANCEMENTS] - added an error() method, for messages that must always be shown - better support for the cases where accept() fails - better error message when accept() fails for a SSL socket [DOCUMENTATION] - added a tutorial about Net::Proxy, with code examples [TESTS] - prevent t/pod-coverage.t to fail on the upgrade_SSL method mixed in Net::Proxy::Connector::connect_ssl 0.10 Mon Oct 1 22:26:50 CEST 2007 [DOCUMENTATION] - added information about the public SVN repository and the mailing-list [TESTS] - prevent t/21connect.t, t/32tcp_connect.t, t/90compile.t to fail when LWP::UserAgent is not installed 0.09 Thu Sep 13 11:01:21 CEST 2007 [ENHANCEMENTS] - the notice(), info() and debug() methods now have a timestamp [TESTS] - prevent the t/37connectssl_tcp.t test script to die when one of the prerequisites is missing (thus removing many FAILs) 0.08 Mon Apr 23 19:08:30 CEST 2007 [ENHANCEMENTS] - the hook callback now receives the socket on which the data was received, in addition to the connector [NEW CONNECTOR] - Net::Proxy::Connector::connect_ssl (combines Net::Proxy::Connector::connect and Net::Proxy::Connector::ssl in a single connector) [TESTS] - made tests more robust when connector prerequisites are missing - test Net::Proxy::Connector::ssl as an "in" connector - test the start_cleartext option of Net::Proxy::Connector::ssl 0.07 Sat Sep 2 19:47:24 CEST 2006 [ENHANCEMENTS] - added support for SSL proxies (ssl connector) [NEW CONNECTOR] - Net::Proxy::Connector::ssl [TESTS] - add support for NET_PROXY_VERBOSITY environnement variable in the tests, to have more verbose tests if needed 0.06 Thu Apr 20 21:27:00 CEST 2006 [ENHANCEMENTS] - add support for "hooks" on received data, as proposed by Martin Werthmöller (see http://www.cpanforum.com/threads/1991), but with a different implementation 0.05 Mon Apr 17 20:42:22 CEST 2006 [ENHANCEMENTS] - added a debug() method (but all uses of it are commented out) - better socket management algorithm: + prevents deadlocks (as could occur when having a connection and a tunneled connection within it both going through Net::Proxy) + limits buffering (so as to avoid sucking a lot of memory when one socket sends data faster than its peer can accept it) [SCRIPTS] - patched sslh so that it can listen not only on localhost. (Thanks to Dieter Voegtli.) 0.04 Tue Jan 17 14:47:20 CET 2006 [ENHANCEMENTS] - added some basic information logging (enable with Net::Proxy->set_verbosity( $level )) [TESTS] - test for several failure cases - the test suite now covers more than 95% of the code [SCRIPTS] - patched sslh so that it works correctly, now 0.03 Wed Jan 11 02:10:52 CET 2006 [DOCUMENTATION] - Correct SYNOPSIS for Net::Proxy::Connector::tcp - Added a SYNOPSIS for Net::Proxy::Connector::connect [NEW CONNECTOR] - Net::Proxy::Connector::dual [SCRIPTS] - previously unreleased sslh script ported to use Net::Proxy 0.02 Tue Jan 10 09:43:23 CET 2006 [ENHANCEMENTS] - added the README and Changes files - added statistical methods to Net::Proxy - mainloop($max) will refuse new connections after $max connections have started [NEW CONNECTOR] - Net::Proxy::Connector::connect [SCRIPTS] - connect-tunnel ported to use Net::Proxy 0.01 Fri Jan 6 03:32:46 CET 2006 [FEATURES] - The proxy is fully functionnal, but lacks several types of connectors [CONNECTORS] - Net::Proxy::Connector::tcp - Net::Proxy::Connector::dummy LICENSE100644001750001750 4371112425533446 13475 0ustar00bookbook000000000000Net-Proxy-0.13This software is copyright (c) 2014 by Philippe Bruhat (BooK). This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2014 by Philippe Bruhat (BooK). This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our 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. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, 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 a 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 tell them 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. 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 Agreement 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 work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 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 General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual 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 General Public License. d) 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. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 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 Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying 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. 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. 7. 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 the 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 the license, you may choose any version ever published by the Free Software Foundation. 8. 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 9. 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. 10. 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 humanity, 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 1, 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) 19xx 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 a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2014 by Philippe Bruhat (BooK). This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End dist.ini100644001750001750 154412425533446 14112 0ustar00bookbook000000000000Net-Proxy-0.13name = Net-Proxy author = Philippe Bruhat (BooK) license = Perl_5 copyright_holder = Philippe Bruhat (BooK) ; copyright_year = 2005-2014 [PkgVersion] [@Filter] -bundle = @Basic -remove = Readme [PruneFiles] filename = check [ExecDir] dir = script [AutoPrereqs] [ReportVersions::Tiny] [MetaJSON] [MetaResources] repository.web = http://github.com/book/Net-Proxy repository.url = http://github.com/book/Net-Proxy.git repository.type = git bugtracker.web = http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Proxy bugtracker.mailto = bug-net-proxy@rt.cpan.org [Test::Compile] [MetaTests] [PodSyntaxTests] [PodCoverageTests] [NextRelease] format = %v %{EEE MMM d yyyy}d [@Git] changelog = Changes commit_msg = Changes for version %v tag_format = v%v tag_message = %N v%v push_to = origin push_to = github [Git::NextVersion] META.yml100644001750001750 163412425533446 13717 0ustar00bookbook000000000000Net-Proxy-0.13--- abstract: 'Framework for proxying network connections in many ways' author: - 'Philippe Bruhat (BooK) ' build_requires: File::Find: '0' File::Spec: '0' File::Spec::Functions: '0' IO::Handle: '0' IPC::Open3: '0' Test::Builder: '0' Test::More: '0.88' perl: '5.006' configure_requires: ExtUtils::MakeMaker: '6.30' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.016, CPAN::Meta::Converter version 2.133380' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Net-Proxy requires: Carp: '0' Getopt::Long: '0' IO::Select: '0' IO::Socket::INET: '0' IO::Socket::SSL: '0' LWP::UserAgent: '0' POSIX: '0' Pod::Usage: '0' Scalar::Util: '0' strict: '0' warnings: '0' resources: bugtracker: http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Proxy repository: http://github.com/book/Net-Proxy.git version: '0.13' MANIFEST100644001750001750 176712425533446 13606 0ustar00bookbook000000000000Net-Proxy-0.13# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.016. Changes LICENSE MANIFEST META.json META.yml Makefile.PL README dist.ini eg/forwarder.pl lib/Net/Proxy.pm lib/Net/Proxy/Connector.pm lib/Net/Proxy/Connector/connect.pm lib/Net/Proxy/Connector/connect_ssl.pm lib/Net/Proxy/Connector/dual.pm lib/Net/Proxy/Connector/dummy.pm lib/Net/Proxy/Connector/ssl.pm lib/Net/Proxy/Connector/tcp.pm lib/Net/Proxy/Tutorial.pod script/connect-tunnel script/sslh t/00-compile.t t/000-report-versions-tiny.t t/00load.t t/05connector.t t/10proxy_new.t t/11proxy_accessor.t t/12proxy_connectors.t t/13proxy_stat.t t/14proxy_debug.t t/20dummy.t t/21connect.t t/22dual.t t/30tcp_tcp.t t/31tcp_tcp_multi.t t/32tcp_connect.t t/33dual.t t/34hook_in.t t/34hook_out.t t/35hook_dual.t t/35signal.t t/36ctssl_tcp.t t/36ssl_tcp.t t/36tcp_ctssl.t t/36tcp_ssl.t t/37connectssl_tcp.t t/40tcp_fail.t t/41listen_fail.t t/Util.pm t/release-distmeta.t t/release-pod-coverage.t t/release-pod-syntax.t t/test.cert t/test.key t000755001750001750 012425533446 12545 5ustar00bookbook000000000000Net-Proxy-0.13Util.pm100644001750001750 474012425533446 14165 0ustar00bookbook000000000000Net-Proxy-0.13/tuse strict; use warnings; use IO::Socket::INET; # return sockets connected to free ports # we can use sockport() to learn the port values # and close() to close the socket just before reopening it sub find_free_ports { my $n = shift; my @socks; for ( 1 .. $n ) { my $sock = listen_on_port(0); if ($sock) { push @socks, $sock; } } my @ports = map { $_->sockport() } @socks; diag "ports: @ports"; # close the sockets and return the ports $_->close() for @socks; return @ports; } # return a socket connected to port $port on localhost sub connect_to_port { my ($port, %opts) = @_; return IO::Socket::INET->new( PeerAddr => 'localhost', PeerPort => $port, Proto => 'tcp', %opts ); } # return a socket listening on $port on localhost sub listen_on_port { my ($port) = @_; return IO::Socket::INET->new( Listen => 1, LocalAddr => 'localhost', LocalPort => $port, Proto => 'tcp', ); } # fork a proxy with the given args sub fork_proxy { my ( $args, $count ) = @_; my $pid = fork; return if !defined $pid; if ( $pid == 0 ) { # the child process runs the proxy my $proxy = Net::Proxy->new($args); $proxy->register(); Net::Proxy->set_verbosity( $ENV{NET_PROXY_VERBOSITY} || 0 ); Net::Proxy->mainloop( $count || 1 ); exit; } return $pid; } # compute a seed and show it use POSIX qw( INT_MAX ); sub init_rand { my $seed = @_ ? $_[0] : int rand INT_MAX; diag "Random seed $seed"; srand $seed; } # randomly exchange (or not) a pair sub random_swap { my ( $first, $second ) = @_; return rand > 0.5 ? ( $first, $second ) : ( $second, $first ); } # # Testing functions # use Test::Builder; my $Tester = Test::Builder->new(); # skip but fail sub skip_fail { my ($why, $how_many) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; for( 1 .. $how_many ) { $Tester->ok( 0, $why ); } no warnings; last SKIP; } use IO::Select; use Test::More; sub is_closed { my ($sock, $name) = @_; local $Test::Builder::Level = $Test::Builder::Level + 1; $name ||= "$sock"; my $select = IO::Select->new( $sock ); my @read = $select->can_read(); if( @read ) { my $buf; my $read = $read[0]->sysread( $buf, 4096 ); $Tester->is_eq( $read, 0, "$name closed" ); } } 1; META.json100644001750001750 366212425533446 14072 0ustar00bookbook000000000000Net-Proxy-0.13{ "abstract" : "Framework for proxying network connections in many ways", "author" : [ "Philippe Bruhat (BooK) " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.016, CPAN::Meta::Converter version 2.133380", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Net-Proxy", "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.30" } }, "develop" : { "requires" : { "Pod::Coverage::TrustPod" : "0", "Test::CPAN::Meta" : "0", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08", "version" : "0.9901" } }, "runtime" : { "requires" : { "Carp" : "0", "Getopt::Long" : "0", "IO::Select" : "0", "IO::Socket::INET" : "0", "IO::Socket::SSL" : "0", "LWP::UserAgent" : "0", "POSIX" : "0", "Pod::Usage" : "0", "Scalar::Util" : "0", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "File::Find" : "0", "File::Spec" : "0", "File::Spec::Functions" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Test::Builder" : "0", "Test::More" : "0.88", "perl" : "5.006" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-net-proxy@rt.cpan.org", "web" : "http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-Proxy" }, "repository" : { "type" : "git", "url" : "http://github.com/book/Net-Proxy.git", "web" : "http://github.com/book/Net-Proxy" } }, "version" : "0.13" } 00load.t100644001750001750 145512425533446 14156 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use File::Find; my %prereqs = ( 'Net::Proxy::Connector::connect' => [qw( LWP::UserAgent )], 'Net::Proxy::Connector::ssl' => [qw( IO::Socket::SSL )], 'Net::Proxy::Connector::connect_ssl' => [qw( LWP::UserAgent IO::Socket::SSL )], ); # compute the list of modules my @modules; find( sub { push @modules, $File::Find::name if /\.pm$/ }, 'blib/lib' ); @modules = sort map { s!/!::!g; s/\.pm$//; s/^blib::lib:://; $_ } @modules; plan tests => scalar @modules; for my $module (@modules) { SKIP: { my $missing_prereqs = 0; for my $prereq ( @{ $prereqs{$module} } ) { eval "require $prereq"; $missing_prereqs++ if $@; } skip "Missing prerequisites for $module", 1 if $missing_prereqs; use_ok($module); } } test.key100644001750001750 156712425533446 14407 0ustar00bookbook000000000000Net-Proxy-0.13/t-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDV/n6YLO/dM/kTUEJDnzVq32+O+dP/imsImeHNrnt0vRXqnj2k YOX5JdMg5nUoV0Yl4Dnq7eZLDkhkL+NAeWJY8ZIrgVXctFle+npSUc3h8mOBXAUP 5qy3L/+7S9IxmOAHU3iEl8jxC6//UgoqWROeyK1HEmxudzHj8yuLSPIGxwIDAQAB AoGBAIJMqQa97fvR5qq05vRH3/3IOSRkyIpD3TJqiIx13qRRciPe4IfTnJRdTLYu vU2n/oWXh4yd+OjgtIGUixo6DwAd31oN2yTJab4+VcC25MEkF0X3NV1e50HCoCuM xwHkINXxwoCIOkAONw7GzxDzeVa6Pp4GQ29LXqZ4WvQUC2MhAkEA+ME3bDUHHct3 LPuMoLMMakHF46YZM6OgUeLGADR9Bc21j/Pra/0tmh0RirbRknf/NIoD8aZyTxtV fMIorjWJ9wJBANw6F92J+dZHpeRfOMbp4rj0mcslBiH4XEzsh0fkQX9DWBrGb58P VVRdWUyAHsj3g49A58GvDaia2j7l3RcutbECQQCQqcUyf5A46pfPKCc7WYUx0jhk ULc9Sb41gN1HRz8h/eTF58OUlLNNefQ2qGUueeyHwG/Uu8ikarAHkt6XmXk3AkBx EMZV8FO7ptdN83Fj9op3aOVYva5zXF6PA9TEnTTfUMT4Ii8Gm8m0YaTKOPEVPrZl ou4Zq3U4viAUsNEc6NdRAkBiuM3ZtgwUX8yYYT4DkQHZfBpnePnazNeZYJvmQt7g SNUJ5PwTTG7t/vocr1oXBibWj+A9Hv5/4eDAbhdc4/Ps -----END RSA PRIVATE KEY----- 33dual.t100644001750001750 522412425533446 14170 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use Net::Proxy; use t::Util; my @lines = ( "thwapp qunckkk aiieee flrbbbbb clunk zlonk\n", "tutu bidon toto test3 pipo titi\n", "pique ratatam am gram stram colegram\n", "Signs_Point_to_Yes Reply_Hazy_Try_Again Cannot_Predict_Now\n", ); my $tests = 2 * ( @lines + 1 ); plan tests => $tests; init_rand(@ARGV); my @free = find_free_ports(3); SKIP: { skip 'Not enough available ports', $tests if @free < 3; my ( $proxy_port, $ssl_port, $ssh_port ) = @free; my $pid = fork_proxy( { in => { type => 'dual', port => $proxy_port, timeout => 0.5, server_first => { type => 'tcp', port => $ssh_port, }, client_first => { type => 'tcp', port => $ssl_port, } }, out => { type => 'dummy' }, }, 2 ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $ssh_listener = listen_on_port($ssh_port) or skip "Couldn't start the ssh server: $!", $tests; my $ssl_listener = listen_on_port($ssl_port) or skip "Couldn't start the ssl server: $!", $tests; my ( $client, $server ); # try 'ssh' $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; sleep 1; # wait for the timeout $server = $ssh_listener->accept() or skip_fail "Proxy didn't connect: $!", $tests; # transmit data for my $line (@lines) { print $server $line; # real server speaks first is( <$client>, $line, "SSH line received" ); ( $client, $server ) = random_swap( $client, $server ); } # close connections $server->close(); is_closed( $client, 'peer' ); $client->close(); # try ssl $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; print $client $lines[0]; # real client speaks first $server = $ssl_listener->accept() or skip_fail "Proxy didn't connect: $!", $tests; is( <$server>, $lines[0], "SSL line received" ); # transmit the rest of the data shift @lines; for my $line (@lines) { ( $client, $server ) = random_swap( $client, $server ); print $client $line; # real client speaks first is( <$server>, $line, "SSL line received" ); } # close connections $client->close(); is_closed( $server, 'peer' ); $server->close(); } 22dual.t100644001750001750 350512425533446 14166 0ustar00bookbook000000000000Net-Proxy-0.13/tuse strict; use warnings; use Test::More tests => 10; use Net::Proxy::Connector; use Net::Proxy::Connector::dual; my $c; my $args = {}; eval { $c = Net::Proxy::Connector::dual->new($args); }; like( $@, qr/^'client_first' connector required /, 'No client_first' ); $args->{client_first} = 1; eval { $c = Net::Proxy::Connector::dual->new($args); }; like( $@, qr/^'client_first' connector must be a HASHREF /, 'client_first not HASHREF' ); $args->{client_first} = {}; eval { $c = Net::Proxy::Connector::dual->new($args); }; like( $@, qr/^'type' key required for 'client_first' connector /, 'No type for client_first' ); $args->{client_first} = { type => 'zlonk' }; eval { $c = Net::Proxy::Connector::dual->new($args); }; like( $@, qr/^Couldn't load Net::Proxy::Connector::zlonk for 'client_first' connector: /, 'Bad connector type for client_first' ); $args->{client_first} = { type => 'tcp' }; $args->{_proxy_} = bless {}, 'Net::Proxy'; eval { $c = Net::Proxy::Connector::dual->new( $args ); }; like( $@, qr/^'server_first' connector required /, 'No server_first' ); $args->{server_first} = 1; eval { $c = Net::Proxy::Connector::dual->new($args); }; like( $@, qr/^'server_first' connector must be a HASHREF /, 'server_first not HASHREF' ); $args->{server_first} = { type => 'zowie' }; eval { $c = Net::Proxy::Connector::dual->new($args); }; like( $@, qr/^Couldn't load Net::Proxy::Connector::zowie for 'server_first' connector: /, 'Bad connector type for server_first' ); $args->{server_first} = { type => 'tcp' }; eval { $c = Net::Proxy::Connector::dual->new( $args ); }; like( $@, qr/^Parameter 'port' is required /, 'No port' ); $args->{port} = 444; eval { $c = Net::Proxy::Connector::dual->new( $args ); }; is( $@, '', 'dual object created'); isa_ok( $c, 'Net::Proxy::Connector::dual' ); test.cert100644001750001750 232512425533446 14545 0ustar00bookbook000000000000Net-Proxy-0.13/t-----BEGIN CERTIFICATE----- MIIDYzCCAsygAwIBAgIJALPGz4A6fiErMA0GCSqGSIb3DQEBBQUAMH8xCzAJBgNV BAYTAkZSMQ4wDAYDVQQIEwVDbHVuazEOMAwGA1UEBxMFVXJra2sxETAPBgNVBAoT CEZscmJiYmJiMQ4wDAYDVQQLEwVXaGFtbTEPMA0GA1UEAxMGU3dvb3NoMRwwGgYJ KoZIhvcNAQkBFg1ib29rQGNwYW4ub3JnMB4XDTA2MDcxOTIwNDUzN1oXDTE2MDcx NjIwNDUzN1owfzELMAkGA1UEBhMCRlIxDjAMBgNVBAgTBUNsdW5rMQ4wDAYDVQQH EwVVcmtrazERMA8GA1UEChMIRmxyYmJiYmIxDjAMBgNVBAsTBVdoYW1tMQ8wDQYD VQQDEwZTd29vc2gxHDAaBgkqhkiG9w0BCQEWDWJvb2tAY3Bhbi5vcmcwgZ8wDQYJ KoZIhvcNAQEBBQADgY0AMIGJAoGBANX+fpgs790z+RNQQkOfNWrfb4750/+KawiZ 4c2ue3S9FeqePaRg5fkl0yDmdShXRiXgOert5ksOSGQv40B5YljxkiuBVdy0WV76 elJRzeHyY4FcBQ/mrLcv/7tL0jGY4AdTeISXyPELr/9SCipZE57IrUcSbG53MePz K4tI8gbHAgMBAAGjgeYwgeMwHQYDVR0OBBYEFPCxvrQ+xr3Pds/Vi5nZMbVL4BVS MIGzBgNVHSMEgaswgaiAFPCxvrQ+xr3Pds/Vi5nZMbVL4BVSoYGEpIGBMH8xCzAJ BgNVBAYTAkZSMQ4wDAYDVQQIEwVDbHVuazEOMAwGA1UEBxMFVXJra2sxETAPBgNV BAoTCEZscmJiYmJiMQ4wDAYDVQQLEwVXaGFtbTEPMA0GA1UEAxMGU3dvb3NoMRww GgYJKoZIhvcNAQkBFg1ib29rQGNwYW4ub3JnggkAs8bPgDp+ISswDAYDVR0TBAUw AwEB/zANBgkqhkiG9w0BAQUFAAOBgQC2NEQXiDql6P9rcsDrHWJtFjpQn5Qy4J7G mqWYl8oVaMwwKyS/V0uXnhjkzj1y6HgjTDNKUJ8mTLr98TARxckq1MwEkhrqMRrz TOKr+IzWRB9gySpKAOyIgX+0dSX+dHOn9goNg9tNa47EgHioKRg6hUoSCR+7p8M6 4oSjpGGBpQ== -----END CERTIFICATE----- 20dummy.t100644001750001750 63112425533446 14347 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Net::Proxy::Connector::dummy; use Test::More tests => 4; # these are dummy calls to the dummy connector # (mostly to raise coverage) my $conn = Net::Proxy::Connector::dummy->new(); is( $conn->read_from( '' ), '', 'read_from()' ); eval { $conn->write_to(); }; is( $@, '', 'write_to()' ); eval { $conn->listen(); }; is( $@, '', 'listen()' ); eval { $conn->accept_from(); }; is( $@, '', 'accept_from()' ); script000755001750001750 012425533446 13606 5ustar00bookbook000000000000Net-Proxy-0.13sslh100755001750001750 1336612425533446 14676 0ustar00bookbook000000000000Net-Proxy-0.13/script#!/usr/bin/perl -w use strict; use Getopt::Long; use Net::Proxy; # default values our %CONF = ( port => 'localhost:443', timeout => 2, ssh => 'localhost:22', ssl => 'localhost:443', verbose => 0, ); # get the options Getopt::Long::Configure("bundling"); GetOptions( \%CONF, "help|h", "port|p=s", "timeout|t=i", "verbose|v+", "version|V", "ssh|s=s", "ssl|https|l=s", ) or die << 'USAGE'; Usage: sslh [-v] [-p host:port] [-t timeout] [--ssh host:port] [--ssl host:port] USAGE # set up the verbosity level Net::Proxy->set_verbosity( $CONF{verbose} ); # check the options die "--timeout must be a positive number (possibly fractional)\n" unless $CONF{timeout} > 0; die "--ssh and -ssl must point to different servers\n" if $CONF{ssh} eq $CONF{ssl}; # create the proxy listening socket die "--port option required\n" unless exists $CONF{port}; # compute host / port { my %hostport; for (qw( ssl ssh port )) { $CONF{$_} = "localhost:$CONF{$_}" if index( $CONF{$_}, ':' ) < 0; $CONF{$_} = [ split /:/, $CONF{$_} ]; push @{ $hostport{ join ':', ( gethostbyname( $CONF{$_}[0] ) )[0], $CONF{$_}[1] } }, $_; } # check for duplicates for( keys %hostport ) { if( @{$hostport{$_}} != 1 ) { die "Options " . join( " and ", map {"--$_"} @{ $hostport{$_} } ) . " are identical! ($_)\n"; } } } # create the proxy my $proxy = Net::Proxy->new( { in => { type => 'dual', host => $CONF{port}[0], port => $CONF{port}[1], timeout => $CONF{timeout}, server_first => { type => 'tcp', host => $CONF{ssh}[0], port => $CONF{ssh}[1], }, client_first => { type => 'tcp', host => $CONF{ssl}[0], port => $CONF{ssl}[1], }, }, out => { type => 'dummy'}, }); $proxy->register(); Net::Proxy->mainloop(); __END__ =encoding utf-8 =head1 NAME sslh - Switch incoming connection between SSH and SSL/HTTPS servers =head1 SYNOPSIS B S<[ B<-v> ]> S<[ B<-p> I<[host:]port> ]> S<[ B<-t> I ]> S<[ B<--ssh> I<[host:]port> ]> S<[ B<--ssl> I<[host:]port> ]> =head1 DESCRIPTION B is a simple script that lets you switch an incoming connection on a single port between distinct SSH and SSL/HTTPS servers. B listens for connections on a port and is able to redirect them either to an HTTPS web server or a SSH server. This lets one setup both a HTTPS web server and a SSH server and access them through the same host+port. =head1 OPTIONS The program follows the usual GNU command line syntax, with long options starting with two dashes. =over 4 =item B<-p>, B<--port> I<[host:]port> The port the proxy will listen to. If no port is given, 443 is used by default. If no host is given, C is used by default. =item B<-s>, B<--ssh> I<[host:]port> The SSH server which the SSH connections must be forwarded to. If omitted, the default is I. =item B<-l>, B<--ssl>, B<--https> I<[host:]port> The HTTPS server which the HTTPS connections must be forwarded to. If omitted, the default is I. =item B<-t>, B<--timeout> I Timeout in seconds before a silent incoming connection is considered as a SSH connection. The number can be fractional. The default is I<2>seconds. =item B<-v>, B<--verbose> Verbose output. This option can be used several times for more verbose output. =back =head1 EXAMPLE OF USE Is this tool actually useful? Yes. For example one can use it to access both a SSH server and a secure web server via a corporate proxy that only accepts to relay connections to port 443. Creating a tunnel that passes SSH connection through a CONNECT-enabled web proxy is easy with B (also included in the C distribution). The proxy will let both SSH and HTTPS connections out (since they all point to port 443), and the home server will connect those incoming connections to the appropriate server. This only requires to run the HTTPS server on a non standard port (not 443). =head1 TECHNICAL NOTE How can this proxy find out what kind of protocol is using a TCP connection to port 443, without being connected (yet) to the server? We actually rely on a slight difference between the SSL and SSH protocols (found thanks to B): =over 4 =item SSH Once the TCP connection is established, the server speaks first, presenting itself by saying something like: SSH-2.0-OpenSSH_3.6.1p2 Debian 1:3.6.1p2-1 =item SSL With SSL, it's always the client that speaks first. =back This means that B can be used with any pair of protocols/services that share this property (the client speaks first for one and the server speaks first for the other). =head1 AUTHORS =over 4 =item Original idea and C version Frédéric Plé C<< >>. =item Perl versions Philippe 'BooK' Bruhat C<< >>. =back =head1 SCRIPT HISTORY Version 0.01 of the script was a quick hack designed in 2003 as a proof of concept. Version 0.02 (and higher) are based on C, and included with the C distribution. Version 0.02 didn't work, though. Version 0.03 correctly initialised the C connector. Version 0.04 lets the proxy listen on any address (instead of C, which is still the default). Thanks to Dieter Voegtli for spotting this. =head1 SEE ALSO L, L. =head1 COPYRIGHT Copyright 2003-2008, Philippe Bruhat. All rights reserved. =head1 LICENSE This module is free software; you can redistribute it or modify it under the same terms as Perl itself. =cut Makefile.PL100644001750001750 352012425533446 14414 0ustar00bookbook000000000000Net-Proxy-0.13 # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v5.016. use strict; use warnings; use ExtUtils::MakeMaker 6.30; my %WriteMakefileArgs = ( "ABSTRACT" => "Framework for proxying network connections in many ways", "AUTHOR" => "Philippe Bruhat (BooK) ", "BUILD_REQUIRES" => {}, "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => "6.30" }, "DISTNAME" => "Net-Proxy", "EXE_FILES" => [ "script/connect-tunnel", "script/sslh" ], "LICENSE" => "perl", "NAME" => "Net::Proxy", "PREREQ_PM" => { "Carp" => 0, "Getopt::Long" => 0, "IO::Select" => 0, "IO::Socket::INET" => 0, "IO::Socket::SSL" => 0, "LWP::UserAgent" => 0, "POSIX" => 0, "Pod::Usage" => 0, "Scalar::Util" => 0, "strict" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "File::Find" => 0, "File::Spec" => 0, "File::Spec::Functions" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Test::Builder" => 0, "Test::More" => "0.88" }, "VERSION" => "0.13", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "Carp" => 0, "File::Find" => 0, "File::Spec" => 0, "File::Spec::Functions" => 0, "Getopt::Long" => 0, "IO::Handle" => 0, "IO::Select" => 0, "IO::Socket::INET" => 0, "IO::Socket::SSL" => 0, "IPC::Open3" => 0, "LWP::UserAgent" => 0, "POSIX" => 0, "Pod::Usage" => 0, "Scalar::Util" => 0, "Test::Builder" => 0, "Test::More" => "0.88", "strict" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); 35signal.t100644001750001750 122112425533446 14513 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use Net::Proxy; use t::Util; # fetch signal numbers use Config; my %sig_num; my @names = split ' ', $Config{sig_name}; @sig_num{@names} = split ' ', $Config{sig_num}; my $tests = 1; if ( $^O eq 'MSWin32' ) { plan skip_all => 'Test irrelevant on MSWin32'; } else { plan tests => $tests; } my $pid = fork_proxy( { in => { type => 'dummy', }, out => { type => 'dummy', }, } ); SKIP: { skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; kill $sig_num{INT}, $pid; is( wait, $pid, 'Proxy stopped by signal' ); } 34hook_in.t100644001750001750 424712425533446 14676 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use t::Util; use Net::Proxy; my @lines = ( [ "swa_a_p bang swish bap crunch\n", "swa_a_p bang swish bap crunch\n" ], [ "zlonk zok zapeth crunch_eth crraack\n", "zowie zowie zowie crunch_eth crraack\n" ], [ "glipp zwapp urkkk cr_r_a_a_ck glurpp\n", "glipp zowie urkkk cr_r_a_a_ck glurpp\n" ], [ "zzzzzwap thwapp zgruppp awk eee_yow\n", "zowie thwapp zowie awk eee_yow\n" ], ); my $tests = @lines + 1; plan tests => $tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, timeout => 1, hook => sub { my ( $dataref, $sock, $connector ) = @_; $$dataref =~ s/\bz\w+/zowie/g; }, }, out => { type => 'tcp', host => 'localhost', port => $server_port, }, } ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; my $client = connect_to_port($proxy_port) or skip "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; # data from the client is transformed by the hook my $orig_client = $client; for my $line (@lines) { # anyone speaks first ( $client, $server ) = random_swap( $server, $client ); # send some data through print $client $line->[0]; my $trans = $client eq $orig_client; is( <$server>, $line->[$trans], "Line received " . ( "intact", "transformed" )[$trans] ); } $client->close(); is_closed( $server, 'peer' ); $server->close(); } 36ssl_tcp.t100644001750001750 365712425533446 14725 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use File::Spec::Functions; use t::Util; use Net::Proxy; my @lines = ( "swa_a_p bang swish bap crunch\n", "zlonk zok zapeth crunch_eth crraack\n", "glipp zwapp urkkk cr_r_a_a_ck glurpp\n", "zzzzzwap thwapp zgruppp awk eee_yow\n", ); my $tests = @lines + 1; plan tests => $tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { eval { require IO::Socket::SSL; }; skip 'IO::Socket::SSL required to test ssl', $tests if $@; skip 'Not enough available ports', $tests if @free < 2; no warnings 'once'; $IO::Socket::SSL::DEBUG = $ENV{NET_PROXY_VERBOSITY} || 0; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'ssl', port => $proxy_port, timeout => 1, SSL_cert_file => catfile( 't', 'test.cert' ), SSL_key_file => catfile( 't', 'test.key' ), }, out => { type => 'tcp', host => 'localhost', port => $server_port, }, } ); skip 'proxy fork failed', $tests if !defined $pid; # wait for the proxy to set up sleep 1; # start a server my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; # start a client my $client = IO::Socket::SSL->new( PeerAddr => 'localhost', PeerPort => $proxy_port ) or skip "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; for my $line (@lines) { ( $client, $server ) = random_swap( $client, $server ); print $client $line; is( <$server>, $line, "Line received" ); } $client->close(); is_closed( $server, 'peer' ); $server->close(); } 21connect.t100644001750001750 322512425533446 14670 0ustar00bookbook000000000000Net-Proxy-0.13/tuse strict; use warnings; use Test::More; use Net::Proxy::Connector; BEGIN { eval { require LWP::UserAgent; }; plan skip_all => 'LWP::UserAgent not available' if $@; } use Net::Proxy::Connector::connect; plan tests => 13; # delete all proxy keys from the environment delete $ENV{$_} for grep { /_proxy$/i } keys %ENV; my $c; my $args = {}; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; like( $@, qr/^host parameter is required /, 'No host'); $args->{host} = 'example.com'; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; like( $@, qr/^port parameter is required /, 'No port'); $args->{port} = 9999; $ENV{HTTP_PROXY} = 'http://powie:zgruppp@urkk.crunch.com:8888/'; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; is( $@, '', 'env_proxy'); isa_ok( $c, 'Net::Proxy::Connector::connect' ); delete $ENV{HTTP_PROXY}; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; like( $@, qr/^proxy_host parameter is required /, 'No proxy_host'); $args->{proxy_host} = 'urkk.crunch.com'; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; is( $@, '', 'proxy_host'); isa_ok( $c, 'Net::Proxy::Connector::connect' ); $args->{proxy_port} = 8888; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; is( $@, '', 'proxy_port'); isa_ok( $c, 'Net::Proxy::Connector::connect' ); $args->{proxy_user} = 'barkhausen'; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; is( $@, '', 'proxy_user'); isa_ok( $c, 'Net::Proxy::Connector::connect' ); $args->{proxy_pass} = 'gerfaut'; eval { $c = Net::Proxy::Connector::connect->new( $args ); }; is( $@, '', 'proxy_pass'); isa_ok( $c, 'Net::Proxy::Connector::connect' ); 30tcp_tcp.t100644001750001750 342012425533446 14670 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use t::Util; use Net::Proxy; my @lines = ( "swa_a_p bang swish bap crunch\n", "zlonk zok zapeth crunch_eth crraack\n", "glipp zwapp urkkk cr_r_a_a_ck glurpp\n", "zzzzzwap thwapp zgruppp awk eee_yow\n", ); my $tests = @lines + 2; plan tests => $tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, timeout => 1, }, out => { type => 'tcp', host => 'localhost', port => $server_port, }, } ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; my $client = connect_to_port($proxy_port) or skip "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; # mainloop(1) limits incoming connections to 1 sleep 1; my $client2 = connect_to_port($proxy_port); is( $client2, undef, "second client fails: $!" ); for my $line (@lines) { # anyone speaks first ( $client, $server ) = random_swap( $server, $client ); # send some data through print $client $line; is( <$server>, $line, "Line received" ); } $client->close(); is_closed( $server, 'peer' ); $server->close(); } 36tcp_ssl.t100644001750001750 427112425533446 14716 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use File::Spec::Functions; use t::Util; use Net::Proxy; my @lines = ( "oscar delta sierra echo papa\n", "Laurent_Fignon Henri_Pelissier Lucien_Petit_Breton Firmin_Lambot\n", "Toronto London Herzliya Melbourne Munich\n", "holy_icepicks holy_corpusles holy_Luthor_Burbank holy_hyperdermics\n", "Woody_Long Alicia_Rio Dorothy_Le_May Janine_Lindemulder Barbara_Summer\n", ); my $tests = @lines; my $all_tests = $tests + 1; plan tests => $all_tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { eval { require IO::Socket::SSL; }; skip 'IO::Socket::SSL required to test ssl', $all_tests if $@; skip 'Not enough available ports', $all_tests if @free < 2; no warnings 'once'; $IO::Socket::SSL::DEBUG = $ENV{NET_PROXY_VERBOSITY} || 0; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, timeout => 1, }, out => { type => 'ssl', host => 'localhost', port => $server_port, }, } ); skip 'proxy fork failed', $tests if !defined $pid; # wait for the proxy to set up sleep 1; # start a SSL server my $listener = IO::Socket::SSL->new( Listen => 1, LocalAddr => 'localhost', LocalPort => $server_port, Proto => 'tcp', SSL_cert_file => catfile( 't', 'test.cert' ), SSL_key_file => catfile( 't', 'test.key' ), ) or skip "Couldn't start the server: $!", $tests; # start a client my $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; for my $line (@lines) { ( $client, $server ) = random_swap( $client, $server ); print $client $line; is( <$server>, $line, "Line received" ); } $client->close(); is_closed( $server, 'peer' ); $server->close(); } 40tcp_fail.t100644001750001750 251112425533446 15016 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use t::Util; use Net::Proxy; plan tests => my $tests = 1; # lock 2 ports my @free = find_free_ports(2); SKIP: { skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $server_port ) = @free; my $pid = fork; SKIP: { skip "fork failed", $tests if !defined $pid; if ( $pid == 0 ) { # the child process runs the proxy my $proxy = Net::Proxy->new( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, }, out => { type => 'tcp', host => 'localhost', port => $server_port, }, }, ); $proxy->register(); Net::Proxy->mainloop(1); exit; } else { # wait for the proxy to set up sleep 1; # no server my $client = connect_to_port($proxy_port) or skip "Couldn't start the client: $!", $tests; # the client is actually not connected at all is_closed( $client, 'peer' ); $client->close(); } } } 34hook_out.t100644001750001750 424512425533446 15075 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use t::Util; use Net::Proxy; my @lines = ( [ "swa_a_p zamm swish bap crunch\n", "swa_a_p zowie swish bap crunch\n" ], [ "zlonk zok zapeth crunch_eth crraack\n", "zowie zowie zowie crunch_eth crraack\n" ], [ "glipp zwapp urkkk cr_r_a_a_ck glurpp\n", "glipp zowie urkkk cr_r_a_a_ck glurpp\n" ], [ "zzzzzwap thwapp zgruppp awk eee_yow\n", "zowie thwapp zowie awk eee_yow\n" ], ); my $tests = @lines + 1; plan tests => $tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, timeout => 1, }, out => { type => 'tcp', host => 'localhost', port => $server_port, hook => sub { my ( $dataref, $sock, $connector ) = @_; $$dataref =~ s/\bz\w+/zowie/g; }, }, } ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; my $client = connect_to_port($proxy_port) or skip "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; # data from the client is transformed by the hook my $orig_server = $server; for my $line (@lines) { # anyone speaks first ( $client, $server ) = random_swap( $server, $client ); # send some data through print $client $line->[0]; my $trans = $server ne $orig_server; is( <$server>, $line->[$trans], "Line received " . ( "intact", "transformed" )[$trans] ); } $client->close(); is_closed( $server, 'peer' ); $server->close(); } 00-compile.t100644001750001750 406512425533446 14744 0ustar00bookbook000000000000Net-Proxy-0.13/tuse 5.006; use strict; use warnings; # this test was generated with Dist::Zilla::Plugin::Test::Compile 2.039 use Test::More tests => 10 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'Net/Proxy.pm', 'Net/Proxy/Connector.pm', 'Net/Proxy/Connector/connect.pm', 'Net/Proxy/Connector/connect_ssl.pm', 'Net/Proxy/Connector/dual.pm', 'Net/Proxy/Connector/dummy.pm', 'Net/Proxy/Connector/ssl.pm', 'Net/Proxy/Connector/tcp.pm' ); my @scripts = ( 'script/connect-tunnel', 'script/sslh' ); # no fake home requested my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } foreach my $file (@scripts) { SKIP: { open my $fh, '<', $file or warn("Unable to open $file: $!"), next; my $line = <$fh>; close $fh and skip("$file isn't perl", 1) unless $line =~ /^#!.*?\bperl\b\s*(.*)$/; my @flags = $1 ? split(/\s+/, $1) : (); my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, @flags, '-c', $file); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$file compiled ok"); # in older perls, -c output is simply the file portion of the path being tested if (@_warnings = grep { !/\bsyntax OK$/ } grep { chomp; $_ ne (File::Spec->splitpath($file))[2] } @_warnings) { warn @_warnings; push @warnings, @_warnings; } } } is(scalar(@warnings), 0, 'no warnings found') if $ENV{AUTHOR_TESTING}; 36tcp_ctssl.t100644001750001750 570712425533446 15252 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use File::Spec::Functions; use t::Util; use Net::Proxy; my @lines = ( "oscar delta sierra echo papa\n", "Laurent_Fignon Henri_Pelissier Lucien_Petit_Breton Firmin_Lambot\n", "Toronto London Herzliya Melbourne Munich\n", "STARTTLS\n", "barkhausen schoenmaker sferics knoop fenice\n", "holy_icepicks holy_corpusles holy_Luthor_Burbank holy_hyperdermics\n", "STARTTLS\n", "Woody_Long Alicia_Rio Dorothy_Le_May Janine_Lindemulder Barbara_Summer\n", ); my $tests = @lines; my $all_tests = $tests + 1; plan tests => $all_tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { eval { require IO::Socket::SSL; }; skip 'IO::Socket::SSL required to test ssl', $all_tests if $@; skip 'Not enough available ports', $all_tests if @free < 2; no warnings 'once'; $IO::Socket::SSL::DEBUG = $ENV{NET_PROXY_VERBOSITY} || 0; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, timeout => 1, }, out => { type => 'ssl', host => 'localhost', port => $server_port, start_cleartext => 1, hook => sub { my ( $dataref, $sock, $connector ) = @_; if ( $$dataref =~ s/^STARTTLS\n// ) { print $sock "OK\n"; $connector->upgrade_SSL($sock); } }, }, } ); skip 'proxy fork failed', $tests if !defined $pid; # wait for the proxy to set up sleep 1; # start a server my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; # start a client my $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; # remember which was the original server my $o_server = $server; my $is_ssl = 0; for my $line (@lines) { ( $client, $server ) = random_swap( $client, $server ); if ( $line eq "STARTTLS\n" ) { print $o_server $line; is( <$o_server>, "OK\n", "STARTTLS acknowledged" ); IO::Socket::SSL->start_SSL( $o_server, SSL_server => 1, SSL_cert_file => catfile( 't', 'test.cert' ), SSL_key_file => catfile( 't', 'test.key' ), ) if !$is_ssl++; # do not upgrade twice } else { print $client $line; is( <$server>, $line, "Line received" ); } } $client->close(); is_closed( $server, 'peer' ); $server->close(); } 35hook_dual.t100644001750001750 764312425533446 15221 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use Net::Proxy; use t::Util; my @lines = ( [ "thwapp qunckkk aiieee flrbbbbb clunk zlonk\n", "thwapp qunckkk aiieee flrbbbbb clunk zowie\n", "thwapp qunckkk aiieee flrbbbbb clunk zlonk\n", ], [ "cr_r_a_a_ck splatt crr_aaack awkkkkkk clunk zlopp ooooff pow\n", "cr_r_a_a_ck splatt crr_aaack awkkkkkk clunk zowie ooooff pow\n", "cr_r_a_a_ck splatt crr_aaack awkkkkkk clunk zlonk ooooff pow\n", ], [ "zgruppp clange clank_est whack zlopp pow awk swish\n", "zowie clange clank_est whack zowie pow awk swish\n", "zlonk clange clank_est whack zlonk pow awk swish\n", ], [ "bonk ouch_eth swa_a_p clank_est clash whack splatt zamm\n", "bonk ouch_eth swa_a_p clank_est clash whack splatt zowie\n", "bonk ouch_eth swa_a_p clank_est clash whack splatt zlonk\n", ], ); my $tests = 2 * ( @lines + 1 ); plan tests => $tests; init_rand(@ARGV); my @free = find_free_ports(3); SKIP: { skip 'Not enough available ports', $tests if @free < 3; my ( $proxy_port, $ssl_port, $ssh_port ) = @free; my $pid = fork_proxy( { in => { type => 'dual', port => $proxy_port, timeout => 0.5, hook => sub { my ( $dataref, $sock, $connector ) = @_; $$dataref =~ s/\bz\w+/zowie/g; }, server_first => { type => 'tcp', port => $ssh_port, }, client_first => { type => 'tcp', port => $ssl_port, hook => sub { my ( $dataref, $sock, $connector ) = @_; $$dataref =~ s/\bz\w+/zlonk/g; }, } }, out => { type => 'dummy' }, }, 2 ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $ssh_listener = listen_on_port($ssh_port) or skip "Couldn't start the ssh server: $!", $tests; my $ssl_listener = listen_on_port($ssl_port) or skip "Couldn't start the ssl server: $!", $tests; my ( $client, $server ); # try 'ssh' $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; sleep 1; # wait for the timeout $server = $ssh_listener->accept() or skip_fail "Proxy didn't connect: $!", $tests; # transmit data my $orig_client = $client; for my $line (@lines) { print $server $line->[0]; # real server speaks first my $trans = $client ne $orig_client; is( <$client>, $line->[$trans], 'SSH line received ' . ( 'intact', 'transformed' )[$trans] ); ( $client, $server ) = random_swap( $client, $server ); } # close connections $server->close(); is_closed( $client, 'peer' ); $client->close(); # try ssl $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; print $client $lines[0][0]; # real client speaks first $server = $ssl_listener->accept() or skip_fail "Proxy didn't connect: $!", $tests; is( <$server>, $lines[0][1], "First SSL line received transformed (client)" ); # transmit the rest of the data shift @lines; $orig_client = $client; for my $line (@lines) { ( $client, $server ) = random_swap( $client, $server ); my $trans = $client eq $orig_client ? 1 : 2; print $client $line->[0]; # real client speaks first is( <$server>, $line->[$trans], 'SSL line received transformed ' . ( '', '(client)', '(server)' )[$trans] ); } # close connections $client->close(); is_closed( $server, 'peer' ); $server->close(); } 10proxy_new.t100644001750001750 431712425533447 15273 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More tests => 13; use strict; use warnings; use Net::Proxy; my $proxy; # test constructor eval { $proxy = Net::Proxy->new(); }; like( $@, qr/^Argument to new\(\) must be a HASHREF/, 'new( HASHREF )' ); eval { $proxy = Net::Proxy->new(1); }; like( $@, qr/^Argument to new\(\) must be a HASHREF/, 'new( HASHREF )' ); # in argument eval { $proxy = Net::Proxy->new( {} ); }; like( $@, qr/^'in' connector required/, 'in arg required' ); eval { $proxy = Net::Proxy->new( { in => 'in' } ); }; like( $@, qr/^'in' connector must be a HASHREF/, 'in must be a HASHREF'); eval { $proxy = Net::Proxy->new( { in => {} } ); }; like( $@, qr/^'type' key required for 'in' connector/, 'type required for in arg' ); eval { $proxy = Net::Proxy->new( { in => { type => 'zlonk', hook => {} } } ); }; like( $@, qr/^'hook' key is not a CODE reference for 'in' connector/, 'hook must be a CODE reference' ); eval { $proxy = Net::Proxy->new( { in => { type => 'zlonk' } } ); }; like( $@, qr/^Couldn't load Net::Proxy::Connector::zlonk for 'in' connector/, q{NPC::zlonk doesn't exist} ); # out argument eval { $proxy = Net::Proxy->new( { in => { type => 'tcp' } } ); }; like( $@, qr/^'out' connector required/, 'out arg required' ); eval { $proxy = Net::Proxy->new( { in => { type => 'tcp' }, out => 'out' } ) }; like( $@, qr/^'out' connector must be a HASHREF/, 'in must be a HASHREF'); eval { $proxy = Net::Proxy->new( { in => { type => 'tcp' }, out => {} } ); }; like( $@, qr/^'type' key required for 'out' connector/, 'type required for out arg' ); eval { $proxy = Net::Proxy->new( { in => { type => 'tcp' }, out => { type => 'zlonk', hook => bless {}, 'CODE' } } ); }; like( $@, qr/^'hook' key is not a CODE reference for 'out' connector/, 'hook must be a CODE reference' ); eval { $proxy = Net::Proxy->new( { in => { type => 'tcp' }, out => { type => 'zlonk' } } ); }; like( $@, qr/^Couldn't load Net::Proxy::Connector::zlonk for 'out' connector/, q{NPC::zlonk doesn't exist} ); # ok eval { $proxy = Net::Proxy->new( { in => { type => 'tcp' }, out => { type => 'tcp' } } ); }; is( $@, '', 'Net::Proxy->new()' ); 05connector.t100644001750001750 64112425533447 15213 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More tests => 3; use strict; use warnings; use Net::Proxy; use Net::Proxy::Connector; my $c = Net::Proxy::Connector->new( ); isa_ok( $c, 'Net::Proxy::Connector' ); # proxy-related methods eval { $c->set_proxy( [] ); }; like( $@, qr/is not a Net::Proxy object/, 'set_proxy() wants a Net::Proxy' ); my $p = bless {}, 'Net::Proxy'; $c->set_proxy( $p ); is( $c->get_proxy, $p, 'Got the Net::Proxy back' ); 36ctssl_tcp.t100644001750001750 526512425533447 15252 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use File::Spec::Functions; use t::Util; use Net::Proxy; my @lines = ( "pete_peters sophie les mr_dork vijay\n", "d_fence abacus_remote ups_onlinet d2k_datamover2 ssslog_mgr\n", "Scooby_Doo Velma Freddy Daphne Shaggy\n", "STARTTLS\n", "Brian Florence Dougal Ermintrude Zebedee\n", "ale sherry cider wine whiskey\n", "Arcadio The_Witch_of_Kaan Drumm Rufferto Gravito\n", ); my $tests = @lines + 1; plan tests => $tests; init_rand(@ARGV); # lock 2 ports my @free = find_free_ports(2); SKIP: { eval { require IO::Socket::SSL; }; skip 'IO::Socket::SSL required to test ssl', $tests if $@; skip 'Not enough available ports', $tests if @free < 2; no warnings 'once'; $IO::Socket::SSL::DEBUG = $ENV{NET_PROXY_VERBOSITY} || 0; my ( $proxy_port, $server_port ) = @free; my $pid = fork_proxy( { in => { type => 'ssl', port => $proxy_port, timeout => 1, start_cleartext => 1, SSL_cert_file => catfile( 't', 'test.cert' ), SSL_key_file => catfile( 't', 'test.key' ), hook => sub { my ( $dataref, $sock, $connector ) = @_; if ( $$dataref =~ s/^STARTTLS\n// ) { print $sock "OK\n"; $connector->upgrade_SSL($sock); } }, }, out => { type => 'tcp', host => 'localhost', port => $server_port, }, } ); skip 'proxy fork failed', $tests if !defined $pid; # wait for the proxy to set up sleep 1; # start a server my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; # start a client my $client = connect_to_port($proxy_port) or skip "Couldn't start the client: $!", $tests; my $server = $listener->accept() or skip "Proxy didn't connect: $!", $tests; # remember which was the original client my $o_client = $client; # exchange the data for my $line (@lines) { ( $client, $server ) = random_swap( $client, $server ); if ( $line eq "STARTTLS\n" ) { print $o_client $line; is( <$o_client>, "OK\n", "STARTTLS acknowledged" ); IO::Socket::SSL->start_SSL($o_client); } else { print $client $line; is( <$server>, $line, "Line received" ); } } $client->close(); is_closed( $server, 'peer' ); $server->close(); } eg000755001750001750 012425533447 12676 5ustar00bookbook000000000000Net-Proxy-0.13forwarder.pl100644001750001750 505712425533447 15375 0ustar00bookbook000000000000Net-Proxy-0.13/eg#!/usr/bin/env perl use strict; use warnings; use Net::Proxy; use Getopt::Long; use Benchmark qw( :hireswallclock timediff ); use Pod::Usage; my %conf = ( proxy => 10000, server => 10001, connections => 1, ); GetOptions( \%conf, 'help', 'manual', 'verbose+', map {"$_=s"} keys %conf ) or pod2usage(2); pod2usage(1) if $conf{help}; pod2usage( -verbose => 2 ) if $conf{manual}; # mark the beginning of the benchmark/profiling my $t0; for my $item (qw( proxy server )) { $conf{$item} = ":$conf{$item}" if $conf{$item} !~ /:/; $conf{$item} = [ split /:/, $conf{$item} ]; } # setup the proxy my $proxy = Net::Proxy->new( { in => { type => 'tcp', host => $conf{proxy}[0] || 'localhost', port => $conf{proxy}[1], timeout => 1, hook => sub { $t0 ||= Benchmark->new; Net::Proxy->set_callback( $_[1] ); # remove ourselves now } }, out => { type => 'tcp', host => $conf{server}[0] || 'localhost', port => $conf{server}[1], }, } ); $proxy->register(); Net::Proxy->set_verbosity( $conf{verbose} || 0 ); Net::Proxy->mainloop( $conf{connections} ); # end of benchmark/profiling my $t1 = timediff( Benchmark->new, $t0 ); print "\nforwarder.pl report: @$t1\n"; __END__ =head1 NAME forwarder.pl - An example TCP port forwarder =head1 SYNOPSIS forwarder.pl [ options ] =head1 OPTIONS --help Display this help --manual Longer manpage --verbose Increase verbosity (may be used several times) --proxy [:] Local port to be forwarded (default: 10000) --server [:] Destination server (default: 10001) --connections Maximum number of connection to accept (0 means never stop, default is 1) =head1 DESCRIPTION This script is an example port forwarder written with C. If run for a limited number of connections, it prints a small wallclock/CPU time report at the end. It is used to profile C itself, by using C and the B script (also distributed in the F directory of the C distribution. =head1 AUTHOR Philippe Bruhat (BooK), C<< >>. =head1 =head1 COPYRIGHT Copyright 2008 Philippe Bruhat (BooK), All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 13proxy_stat.t100644001750001750 206512425533447 15456 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More tests => 10; use Net::Proxy; my $proxy = Net::Proxy->new( { in => { type => 'dummy' }, out => { type => 'dummy' } } ); is( $proxy->stat_opened(), 0, "No opened connection" ); is( $proxy->stat_closed(), 0, "No closed connection" ); $proxy->stat_inc_opened(); is( $proxy->stat_opened(), 1, "1 opened connection" ); $proxy->stat_inc_opened(); $proxy->stat_inc_opened(); is( $proxy->stat_opened(), 3, "3 opened connections" ); $proxy->stat_inc_closed(); is( $proxy->stat_closed(), 1, "1 closed connection" ); $proxy->stat_inc_closed(); $proxy->stat_inc_closed(); is( $proxy->stat_opened(), 3, "3 closed connections" ); my $proxy2 = Net::Proxy->new( { in => { type => 'dummy' }, out => { type => 'dummy' } } ); $proxy2->stat_inc_opened(); is( $proxy2->stat_opened(), 1, "1 opened connection"); is( Net::Proxy->stat_total_opened(), 4, "Total 4 opened connections" ); $proxy2->stat_inc_closed(); is( $proxy2->stat_closed(), 1, "1 closed connection"); is( Net::Proxy->stat_total_closed(), 4, "Total 4 closed connections" ); Net000755001750001750 012425533447 13577 5ustar00bookbook000000000000Net-Proxy-0.13/libProxy.pm100644001750001750 5465512425533447 15455 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Netpackage Net::Proxy; $Net::Proxy::VERSION = '0.13'; use strict; use warnings; use Carp; use Scalar::Util qw( refaddr reftype ); use IO::Select; use POSIX 'strftime'; # interal socket information table my %SOCK_INFO; my %LISTENER; my %CLOSING; my $READERS; my $WRITERS; my %PROXY; my %STATS; # Net::Proxy attributes my %CONNECTOR = ( in => {}, out => {}, ); my $VERBOSITY = 0; # be silent by default my $BUFFSIZE = 16384; # # some logging-related methods # sub set_verbosity { $VERBOSITY = $_[1]; } { my $i; for my $meth (qw( error notice info debug )) { no strict 'refs'; my $level = $i++; *$meth = sub { return if $VERBOSITY < $level; print STDERR strftime "%Y-%m-%d %H:%M:%S $_[1]\n", localtime; }; } } # # constructor # sub new { my ( $class, $args ) = @_; my $self = bless \do { my $anon }, $class; croak "Argument to new() must be a HASHREF" if ref $args ne 'HASH'; for my $conn (qw( in out )) { # check arguments croak "'$conn' connector required" if !exists $args->{$conn}; croak "'$conn' connector must be a HASHREF" if ref $args->{$conn} ne 'HASH'; croak "'type' key required for '$conn' connector" if !exists $args->{$conn}{type}; croak "'hook' key is not a CODE reference for '$conn' connector" if $args->{$conn}{hook} && reftype( $args->{$conn}{hook} ) ne 'CODE'; # load the class my $class = 'Net::Proxy::Connector::' . $args->{$conn}{type}; eval "require $class"; croak "Couldn't load $class for '$conn' connector: $@" if $@; # create and store the Connector object $args->{$conn}{_proxy_} = $self; $CONNECTOR{$conn}{ refaddr $self} = $class->new( $args->{$conn} ); $CONNECTOR{$conn}{ refaddr $self}->set_proxy($self); } return $self; } sub register { $PROXY{ refaddr $_[0] } = $_[0]; } sub unregister { delete $PROXY{ refaddr $_[0] }; } sub get_max_buffer_size { return $BUFFSIZE; } sub set_max_buffer_size { $BUFFSIZE = $_[1]; } # # The Net::Proxy attributes # sub in_connector { return $CONNECTOR{in}{ refaddr $_[0] }; } sub out_connector { return $CONNECTOR{out}{ refaddr $_[0] }; } # # create the socket setter/getter methods # these are actually Net::Proxy clas methods # BEGIN { my $n = 0; my $buffer_id; for my $attr (qw( peer connector state nick buffer callback )) { no strict 'refs'; my $i = $n; *{"get_$attr"} = sub { $SOCK_INFO{ refaddr $_[1] }[$i]; }; *{"set_$attr"} = sub { $SOCK_INFO{ refaddr $_[1] }[$i] = $_[2]; }; $buffer_id = $n if $attr eq 'buffer'; $n++; } # special shortcut sub add_to_buffer { $SOCK_INFO{ refaddr $_[1] }[$buffer_id] .= $_[2] if(!exists($CLOSING{$_[1]})); } } # # create statistical methods # for my $info (qw( opened closed )) { no strict 'refs'; *{"stat_inc_$info"} = sub { $STATS{ refaddr $_[0]}{$info}++; $STATS{total}{$info}++; }; *{"stat_$info"} = sub { $STATS{ refaddr $_[0]}{$info} || 0; }; *{"stat_total_$info"} = sub { $STATS{total}{$info} || 0; }; } # # socket-related methods # sub add_listeners { my ( $class, @socks ) = @_; for my $sock (@socks) { Net::Proxy->notice( 'Add ' . Net::Proxy->get_nick($sock) ); $LISTENER{ refaddr $sock} = $sock; } return; } sub close_sockets { my ( $class, @socks ) = @_; SOCKET: for my $sock (@socks) { my $conn = Net::Proxy->get_connector($sock); next SOCKET if(!defined($conn)); if( my $data = Net::Proxy->get_buffer( $sock ) ) { ## Net::Proxy->debug( length($data) . ' bytes left to write on ' . Net::Proxy->get_nick( $sock ) ); $CLOSING{ refaddr $sock} = $sock; next SOCKET; } Net::Proxy->notice( 'Closing ' . Net::Proxy->get_nick( $sock ) ); # clean up connector $conn->close($sock) if $conn->can('close'); # count connections to the proxy "in connectors" only my $proxy = $conn->get_proxy(); if ( refaddr $conn == refaddr $proxy->in_connector() && !_is_listener($sock) ) { $proxy->stat_inc_closed(); } # clean up internal structures delete $SOCK_INFO{ refaddr $sock}; delete $LISTENER{ refaddr $sock}; delete $CLOSING{ refaddr $sock}; # clean up sockets $READERS->remove($sock); $WRITERS->remove($sock); $sock->close(); } return; } # # select() stuff # sub watch_reader_sockets { my ( $class, @socks ) = @_; $READERS->add(@socks); return; } sub watch_writer_sockets { my ( $class, @socks ) = @_; $WRITERS->add(@socks); return; } sub remove_writer_sockets { my ( $class, @socks ) = @_; $WRITERS->remove(@socks); return; } # # destructor # sub DESTROY { my ($self) = @_; delete $CONNECTOR{in}{ refaddr $self}; delete $CONNECTOR{out}{ refaddr $self}; } # # the mainloop itself # sub mainloop { my ( $class, $max_connections ) = @_; $max_connections ||= 0; # initialise the loop $READERS = IO::Select->new(); $WRITERS = IO::Select->new(); # initialise all proxies for my $proxy ( values %PROXY ) { my $in = $proxy->in_connector(); my @socks = $in->listen(); Net::Proxy->add_listeners(@socks); Net::Proxy->watch_reader_sockets(@socks); Net::Proxy->set_connector( $_, $in ) for @socks; } my $continue = 1; for my $signal (qw( INT HUP )) { $SIG{$signal} = sub { Net::Proxy->notice("Caught $signal signal"); $continue = 0; }; } # loop indefinitely while ( $continue and my @ready = IO::Select->select( $READERS, $WRITERS ) ) { ## Net::Proxy->debug( 0+@{$ready[0]} . " sockets ready for reading" ); ## Net::Proxy->debug( join "\n ", "Readers:", map { Net::Proxy->get_nick($_) } $READERS->handles() ); ## Net::Proxy->debug( 0+@{$ready[1]} . " sockets ready for writing" ); ## Net::Proxy->debug( join "\n ", "Writers:", map { Net::Proxy->get_nick($_) } $WRITERS->handles() ); # first read READER: for my $sock (@{$ready[0]}) { if ( _is_listener($sock) ) { # accept the new connection and connect to the destination Net::Proxy->get_connector($sock)->new_connection_on($sock); } else { # have we read too much? my $peer = Net::Proxy->get_peer($sock); next READER if !$peer || ($BUFFSIZE && length( Net::Proxy->get_buffer($peer) ) >= $BUFFSIZE); # read the data if ( my $conn = Net::Proxy->get_connector($sock) ) { my $data = $conn->read_from($sock); next READER if !defined $data; if ($peer) { # run the hook on incoming data my $callback = Net::Proxy->get_callback( $sock ); $callback->( \$data, $sock, $conn ) if $callback && defined $data; Net::Proxy->add_to_buffer( $peer, $data ); Net::Proxy->watch_writer_sockets($peer); ## Net::Proxy->debug( "Will write " . length( Net::Proxy->get_buffer($peer)). " bytes to " . Net::Proxy->get_nick( $peer )); } } } } # then write for my $sock (@{$ready[1]}) { my $conn = Net::Proxy->get_connector($sock); next if(!defined($conn)); # may happen if read_from() closed socket $conn->write_to($sock); } } continue { if( %CLOSING ) { Net::Proxy->close_sockets( values %CLOSING ); } if( $max_connections ) { # stop after that many connections last if Net::Proxy->stat_total_closed() == $max_connections; # prevent new connections if ( %LISTENER && Net::Proxy->stat_total_opened() == $max_connections ) { Net::Proxy->close_sockets( values %LISTENER ); } } } # close all remaining sockets Net::Proxy->close_sockets( $READERS->handles(), $WRITERS->handles() ); } # # helper private FUNCTIONS # sub _is_listener { return exists $LISTENER{ refaddr $_[0] }; } 1; __END__ =encoding utf-8 =head1 NAME Net::Proxy - Framework for proxying network connections in many ways =head1 SYNOPSIS use Net::Proxy; # proxy connections from localhost:6789 to remotehost:9876 # using standard TCP connections my $proxy = Net::Proxy->new( { in => { type => 'tcp', port => '6789' }, out => { type => 'tcp', host => 'remotehost', port => '9876' }, } ); # register the proxy object $proxy->register(); # and you can setup multiple proxies # and now proxy connections indefinitely Net::Proxy->mainloop(); =head1 DESCRIPTION A Net::Proxy object represents a proxy that accepts connections and then relays the data transfered between the source and the destination. The goal of this module is to abstract the different methods used to connect from the proxy to the destination. A proxy is a program that transfer data across a network boundary between a client and a server. Net::Proxy introduces the concept of "connectors" (implemented as L subclasses), which abstract the server part (connected to the client) and the client part (connected to the server) of the proxy. This architecture makes it easy to implement specific techniques to cross a given network boundary, possibly by using a proxy on one side of the network fence, and a reverse-proxy on the other side of the fence. See L for details about the existing connectors. =head1 METHODS If you only intend to use Net::Proxy and not write new connectors, you only need to know about C, C and C. =head2 Class methods =head3 new my $proxy = Net::Proxy->new( { in => { ... }, { out => { ... } } ); Return a new Net::Proxy object, with two connectors configured as described in the hashref. The connector parameters are described in the table below, as well as in each connector documentation. =head3 mainloop Net::Proxy->mainloop( $max_connections ) This method initialises all the registered C objects and then loops on all the sockets ready for reading, passing the data through the various C objets to handle the specifics of each connection. If C<$max_connections> is given, the proxy will stop after having fully processed that many connections. Otherwise, this method does not return. =head3 add_listeners Net::Proxy->add_listeners( @sockets ); Add the given sockets to the list of listening sockets. =head3 watch_reader_sockets Net::Proxy->watch_reader_sockets( @sockets ); Add the given sockets to the readers watch list. =head3 watch_writer_sockets Net::Proxy->watch_writer_sockets( @sockets ); Add the given sockets to the writers watch list. =head3 remove_writer_sockets Net::Proxy->remove_writer_sockets( @sockets ); Remove the given sockets from the writers watch list. =head3 close_sockets Net::Proxy->close_sockets( @sockets ); Close the given sockets and cleanup the related internal structures. =head3 set_verbosity Net::Proxy->set_verbosity( $level ); Set the logging level. C<0> means not messages except warnings and errors. =head3 error Net::Proxy->error( $message ); Log C<$message> to STDERR, always. =head3 notice Net::Proxy->notice( $message ); Log C<$message> to STDERR if verbosity level is equal to C<1> or more. =head3 info Net::Proxy->info( $message ); Log C<$message> to STDERR if verbosity level is equal to C<2> or more. =head3 debug Net::Proxy->debug( $message ); Log C<$message> to STDERR if verbosity level is equal to C<3> or more. (Note: throughout the Net::Proxy source code, calls to C are commented with C<##>.) =head3 get_max_buffer_size my $buffsize = Net::Proxy->get_max_buffer_size; Get the maximum allowed length of the internal write buffers used by each connector. =head3 set_max_buffer_size Net::Proxy->set_max_buffer_size($buffsize); Get or set the maximum allowed length of the internal write buffers used by each connector. A value of 0 means that the maximum length is not checked. The default value is 16384 bytes (16kB). Note that this is a global value, shared by all proxies and connectors. =head2 Class methods related to sockets Some of the class methods are related to the socket objects that handle the actual connections. =head3 get_peer my $peer = Net::Proxy->get_peer( $socket ); Get the socket peer. =head3 set_peer Net::Proxy->set_peer( $socket, $peer ); Set the socket peer. =head3 get_connector my $connector = Net::Proxy->get_connector( $socket ); Get the socket connector (a L object). =head3 set_connector Net::Proxy->set_connector( $socket, $connector ); Set the socket connector (a L object). =head3 get_state my $state = Net::Proxy->get_state( $socket ); Get the socket state. =head3 set_state Net::Proxy->set_state( $socket, $state ); Set the socket state. Some C subclasses may wish to use this to store some internal information about the socket or the connection. =head3 get_nick my $nick = Net::Proxy->get_nick( $socket ); Get the socket nickname. =head3 set_nick Net::Proxy->set_nick( $socket, $nickname ); Set the socket nickname. Typically used by L to give informative names to socket (used in the log messages). =head3 get_buffer my $buffer = Net::Proxy->get_buffer( $socket ); Get the content of the writing buffer for the socket. =head3 set_buffer Net::Proxy->set_buffer( $socket, $data ); Set the content of the writing buffer for the socket. Used by L in C and C. =head3 get_callback Net::Proxy->get_callback( $socket ); Get the callback currently associated with the socket. =head3 set_callback Net::Proxy->set_callback( $socket, $coderef ); Set the callback currently associated with the socket. =head3 add_to_buffer Net::Proxy->add_to_buffer( $socket, $data ); Add data to the writing buffer of the socket. =head2 Instance methods =head3 register $proxy->register(); Register a Net::Proxy object so that it will be included in the C processing. =head3 unregister $proxy->unregister(); Unregister the Net::Proxy object. =head3 in_connector my $connector = $proxy->in_connector(); Return the L objet that handles the incoming connection and handles the data coming from the "client" side. =head3 out_connector my $connector = $proxy->out_connector(); Return the L objet that creates the outgoing connection and handles the data coming from the "server" side. =head2 Statistical methods The following methods manage some statistical information about the individual proxies: =head3 stat_inc_opened $proxy->stat_inc_opened(); Increment the "opened" connection counter for this proxy. =head3 stat_inc_closed $proxy->stat_inc_closed(); Increment the "closed" connection counter for this proxy. =head3 stat_opened my $opened = $proxy->stat_opened(); Return the count of "opened" connections for this proxy. =head3 stat_closed my $closed = $proxy->stat_closed(); Return the count of "closed" connections for this proxy. =head3 stat_total_opened my $opened = $proxy->stat_total_opened(); Return the total count of "opened" connections across all proxy objects. =head3 stat_total_closed my $closed = $proxy->stat_total_closed(); Return the total count of "closed" connections across all proxy objects. =head1 CONNECTORS All connection types are provided with the help of specialised classes. The logic for protocol C is provided by the C class. =head2 Connector hooks There is a single parameter that all connectors accept: C. Given a code reference, the code reference will be called when data is I on the corresponding socket. The code reference should have the following signature: sub callback { my ($dataref, $sock, $connector) = @_; ... } C<$dataref> is a reference to the chunk of data received, C<$sock> is a reference to the socket that received the data, and C<$connector> is the C object that created the socket. This allows someone to eventually store data in a stash stored in the connector, so as to share data between sockets. =head2 Available connectors =over 4 =item tcp (L) This is the simplest possible proxy connector. On the "in" side, it sits waiting for incoming connections, and on the "out" side, it connects to the configured host/port. =item connect (L) This proxy connector can connect to a TCP server though a web proxy that accepts HTTP CONNECT requests. =item dual (L) This proxy connector is a Y-shaped connector: depending on the client behaviour right after the connection is established, it connects it to one of two services, handled by two distinct connectors. =item dummy (L) This proxy connector does nothing. You can use it as a template for writing new L classes. =back =head2 Summary This table summarises all the available L classes and the parameters their constructors recognise. C means that the given L cannot be used in that position (either C or C). Connector | in parameters | out parameters ------------+-----------------+----------------- tcp | host | host | port | port ------------+-----------------+----------------- connect | N/A | host | | port | | proxy_host | | proxy_port | | proxy_user | | proxy_pass | | proxy_agent ------------+-----------------+----------------- dual | host | N/A | port | | timeout | | server_first | | client_first | ------------+-----------------+----------------- dummy | N/A | N/A ------------+-----------------+----------------- ssl | host | host | port | port | start_cleartext | start_cleartext ------------+-----------------+----------------- connect_ssl| N/A | host | | port | | proxy_host | | proxy_port | | proxy_user | | proxy_pass | | proxy_agent L is used as the C parameter for a L, since the later is linked to two different connector objects. =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 TODO Here's my own wishlist: =over 4 =item * Write a connector fully compatible with GNU httptunnel (L). This one will probably be named C. =item * Enhance the httptunnel protocol to support multiple connections. =item * Implement RFC 3093 - Firewall Enhancement Protocol (FEP), as C. This RFC was published on April 1, 2001. This is probably impossible with Net::Proxy, since the FEP driver is a rather low-level driver (at the IP level of the network stack). =item * Implement DNS tunnel connectors. See L, OzymanDNS, L. L for examples. =item * Implement an UDP connector. (Is it feasible?) =item * Implement a connector that can be plugged to the STDIN/STDOUT of an external process, like the C option of OpenSSH. =item * Implement C, for UNIX sockets. =item * Implement ICMP tunnel connectors. See L, L, L, L for examples. Since ICMP implies low-level packet reading and writing, it may not be possible for Net::Proxy to handle it. =item * Look for inspiration in the I, at L. Look also here: L =item * Implement a C connector that can upgrade upgrade a connection to SSL transparently, even if the client or server doesn't support STARTTLS. Martin Werthmöller provided a full implementation of a connector that can handle IMAP connections and upgrade them to TLS if the client sends a C command. My implementation will split this in two parts L and C, that inherits from the former. =back =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Net::Proxy You can also look for information at: =over 4 =item The public source repository L =item AnnoCPAN: Annotated CPAN documentation L =item CPAN Ratings L =item RT: CPAN's request tracker L =item Search CPAN L =back =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 41listen_fail.t100644001750001750 151612425533447 15534 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use t::Util; use Net::Proxy; plan tests => my $tests = 1; # lock 2 ports my @free = find_free_ports(2); SKIP: { skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $server_port ) = @free; my $server = listen_on_port( $proxy_port ) or skip "Failed to lock port $proxy_port", $tests; my $proxy = Net::Proxy->new( { in => { type => 'tcp', host => 'localhost', port => $proxy_port, }, out => { type => 'tcp', host => 'localhost', port => $server_port, }, }, ); $proxy->register(); eval { Net::Proxy->mainloop(); }; like( $@, qr/^Can't listen on localhost port \d+: /, 'Port in use' ); } 32tcp_connect.t100644001750001750 556212425533447 15547 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use t::Util; use Net::Proxy; my @lines = ( "fettuccia_riccia galla_genovese sedanetti pennine_rigate gobboni\n", "fenescecchie barbina gianduini umbricelli maniche\n", "gozzetti pepe tofarelle anelli_margherite_lisce farfallette\n", "sciviotti_ziti_rigati gobbini gomiti cravattine penne_di_zitoni\n", "amorosi cuoricini cicorie tempestina tortellini\n", ); my $tests = @lines + 3; init_rand(@ARGV); plan tests => $tests; SKIP: { # check required modules for this test case for my $module (qw( LWP::UserAgent HTTP::Daemon )) { eval "require $module;"; skip "$module required to test connect", $tests if $@; } # lock 2 ports my @free = find_free_ports(2); skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $web_proxy_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port }, out => { type => 'connect', host => 'zlonk.crunch.com', port => 443, proxy_host => 'localhost', proxy_port => $web_proxy_port, }, }, 2 ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $daemon = HTTP::Daemon->new( LocalAddr => 'localhost', LocalPort => $web_proxy_port, ) or skip "Couldn't start the server: $!", $tests; my $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; my $server = $daemon->accept() or skip_fail "Proxy didn't connect: $!", $tests; # the server will first play the role of the web proxy, # and after a 200 OK will also act as a real server # check the request my $req = $server->get_request(); is( $req->method(), 'CONNECT', 'Proxy did a CONNECT' ); is( $req->uri()->host_port(), 'zlonk.crunch.com:443', 'host:port' ); # first time, the web proxy says 200 $server->send_response( HTTP::Response->new('200') ); # send some data through # FIXME this blocks when $server speaks first for my $line (@lines) { print $client $line; is( <$server>, $line, "Line received" ); ( $client, $server ) = random_swap( $client, $server ); } $client->close(); $server->close(); # second time, the web proxy says 403 (how to test this?) $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", 1; $server = $daemon->accept() or skip_fail "Proxy didn't connect: $!", 1; $server->get_request(); # ignore it $server->send_response( HTTP::Response->new('403') ); is_closed($client); } 14proxy_debug.t100644001750001750 1043612425533447 15613 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use Net::Proxy; my @messages = ( 'ham tomato shrubbery pate herring truffle lobster aubergine', 'kn na vn pk cy hn yu cc', 'thwack kayo zlonk qunckkk zlott cr_r_a_a_ck clunk_eth bang', 'The_Witch_of_Kaan Pipil_Khan Minstrel Sage Captain_Ahax Groo Chakaal', 'barry wendel_j_stone_iv myron laura ed richard millard_bullrush dilbert', 'lbrocard hvds ni_s gbarr lwall cbail mschwern rgarcia', 'XPT MUR CNY MDL GHC MWK YER LTL', 'elk wapiti antler alces_alces oryx moose caribou eland', 'Jimmy_Carter Ronald_Reagan Chester_Arthur George_Washington Gerald_Ford', 'Woodstock Rerun Peppermint_Patty Schroeder Pigpen Lucy Snoopy Linus', 'manganese eckstine lowenstein gebrail gland maijstral girgis godolphin', 'corge quux foobar fred waldo garply fubar grault', 'strontium platine germanium rhodium hafnium californium chrome terbium', 'maxime laboris adipisicing ullamco harum nobis sed inventore', 'Braga Pittsburgh Saint_Louis Merlbourne Ottawa Belfast Chicago Paris', 'mardi jeudi mercredi dimanche vendredi samedi lundi jeudi', 'Gregory_Gaillard Delphine_Moussin Michael_Denard Geraldine_Wiart', 'MONGOLIAN_LETTER_LA COMBINING_LATIN_SMALL_LETTER_X MYANMAR_SIGN_ANUSVARA', 'ansys_lm kis netinfo_local pcia_rxp_b xpl hri_port nkd stmf', 'holy_greed holy_ghost_writer holy_jawbreaker holy_barracuda', 'Rea Sushi Stretch Garfield Clive Caped_Avenger Squeak Arlene', 'spam toast ham lobster beans tomato aubergine', 'period bullet underscore pilcrow ellipsis dagger permille_sign', 'plugh foo quux foobar qux corge xyzzy', 'MBOX SIZE QUIT XFER OK NMBR RETR', 'Rerun Pigpen Charlie_Brown Schroeder Snoopy Marcie Linus', 'orca classroom versatile repay inception narrative chatter', 'Altair Electra Ancha Naos Canopus Merope Sadr', 'greed anger envy laziness gluttony pride lust', ); my @expected = @messages[ 0, 4, 8, 9, 12, 13, 14, 16, 17, 20 .. 24 ]; my $err = 'stderr.out'; plan tests => my $tests = @expected; SKIP: { # logs are sent to STDERR # (this is not a very nice way to spit logging info) # so, dup STDERR and save it to stderr.out open OLDERR, ">&STDERR" or skip "Can't dup STDERR: $!", $tests; open STDERR, '>', $err or skip "Can't redirect STDERR: $!", $tests; select STDERR; $| = 1; # make unbuffered # run our tests now my $i = 0; Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); Net::Proxy->set_verbosity(0); Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); Net::Proxy->set_verbosity(1); Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); Net::Proxy->set_verbosity(2); Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); Net::Proxy->set_verbosity(1); Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); Net::Proxy->set_verbosity(3); Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); Net::Proxy->set_verbosity(0); Net::Proxy->error( $messages[ $i++ ] ); Net::Proxy->notice( $messages[ $i++ ] ); Net::Proxy->info( $messages[ $i++ ] ); Net::Proxy->debug( $messages[ $i++ ] ); # get the old STDERR back open STDERR, ">&OLDERR" or die "Can't dup OLDERR: $!"; close OLDERR; # read stderr.out open my $fh, $err or skip "Unable to open $err: $!"; $i = 0; while (<$fh>) { like( $_, qr/\A\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d $expected[$i]\n\z/, "Expected line $i" ); $i++; } # close and remove all files close $fh or diag "close: $!"; unlink $err or diag "unlink: $!"; } 31tcp_tcp_multi.t100644001750001750 1257212425533447 16134 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use t::Util; use Net::Proxy; # dummy data my @lines = ( "swa_a_p bang swish bap crunch\n", "zlonk zok zapeth crunch_eth crraack\n", "glipp zwapp urkkk cr_r_a_a_ck glurpp\n", "zzzzzwap thwapp zgruppp awk eee_yow\n", "ker_plop spla_a_t swoosh cr_r_a_a_ck bang_eth pam uggh\n", "AEGEAN_NUMBER_NINETY MATHEMATICAL_SANS_SERIF_ITALIC_SMALL_Y\n", "YI_SYLLABLE_SHUX ARABIC_LIGATURE_THEH_WITH_REH_FINAL_FORM\n", "TAG_PLUS_SIGN CYPRIOT_SYLLABLE_RE\n", "TAG_LATIN_CAPITAL_LETTER_S YI_SYLLABLE_QYRX\n", "MATHEMATICAL_DOUBLE_STRUCK_CAPITAL_U HALFWIDTH_HANGUL_LETTER_YEO\n", "linguine lasagne_ricce chiocciole\n", "fusilli_tricolore sedani_corti galla_mezzana\n", "fettucce_ricce maniche chifferi_rigati\n", "mista lasagne_festonate_a_nidi nidi\n", "capelvenere parigine lacchene\n", "occhi_di_passero guanti ditali\n", ); # compute a seed and show it init_rand( @ARGV ); # compute random configurations my @confs = sort { $a->[0] <=> $b->[0] } map { [ int rand 16, int rand 8 ] } 1 .. 3; # compute the total number of tests my $tests = 1 + ( my $first = int rand 8 ); $tests += $_->[1] for @confs; $tests += 1 + @confs; # show the config if if( @ARGV ) { diag sprintf "%2d %2d", @$_ for ( [ 0, $first ], @confs ); } plan tests => $tests; # lock 2 ports my @ports = find_free_ports(3); SKIP: { skip "Not enough available ports", $tests if @ports < 3; my ($proxy_port, $server_port, $fake_port) = @ports; my $pid = fork; SKIP: { skip "fork failed", $tests if !defined $pid; if ( $pid == 0 ) { # the child process runs the proxy my $proxy = Net::Proxy->new( { in => { type => 'tcp', host => 'localhost', port => $proxy_port }, out => { type => 'tcp', host => 'localhost', port => $server_port }, } ); $proxy->register(); # test unregister() my $fake_proxy = Net::Proxy->new( { in => { type => 'tcp', host => 'localhost', port => $fake_port }, out => { type => 'tcp', host => 'localhost', port => $server_port }, } ); $fake_proxy->register(); $fake_proxy->unregister(); Net::Proxy->set_verbosity( $ENV{NET_PROXY_VERBOSITY} || 0 ); Net::Proxy->mainloop( @confs + 1 ); exit; } else { # wait for the proxy to set up sleep 1; # start the server my $listener = listen_on_port($server_port) or skip "Couldn't start the server: $!", $tests; # create the first pair my %pairs; { my $pair = ( [ connect_to_port($proxy_port), scalar $listener->accept(), $first, 0 ] ); %pairs = ( $pair => $pair ); } # check the other proxy is not listening { my $client = connect_to_port($fake_port); is( $client, undef, "Second proxy not here: $!" ); } my $step = my $n = my $count = 0; while (%pairs || @confs) { # create a new connection CONF: while ( @confs && $confs[0][0] == $step ) { my $conf = shift @confs; my $client = connect_to_port($proxy_port) or do { diag "Couldn't start the client: $!"; next CONF; }; my $server = $listener->accept() or do { diag "Proxy didn't connect: $!"; next CONF; }; my $pair = [ $client, $server, $conf->[1], ++$count ]; $pairs{$pair} = $pair; } PAIR: for my $pair (values %pairs) { # close the connection if finished if ( $pair->[2] <= 0 ) { $pair->[0]->close(); is_closed( $pair->[1], "other socket of pair $pair->[3]" ); $pair->[1]->close(); delete $pairs{$pair}; next PAIR; } # fetch data to send $n %= @lines; my $line = $lines[$n]; # randomly swap client/server @{$pair}[ 0, 1 ] = random_swap(@{$pair}[ 0, 1 ]); # send data through the connection print { $pair->[0] } $line; is( $pair->[1]->getline(), $line, "Step $step: line $n sent through pair $pair->[3]" ); $pair->[2]--; $n++; } $step++; } } } } 11proxy_accessor.t100644001750001750 132312425533447 16277 0ustar00bookbook000000000000Net-Proxy-0.13/tuse strict; use warnings; use Test::More tests => 5; use Net::Proxy; my $sock = []; # dummy socket object my $peer = []; # dummy socket object my $connector = bless {}, 'Net::Proxy::Connector'; my $state = {}; Net::Proxy->set_peer( $sock, $peer ); is( Net::Proxy->get_peer( $sock ), $peer, 'Got back the peer' ); Net::Proxy->set_connector( $sock, $connector ); is( Net::Proxy->get_connector( $sock ), $connector, 'Got back the connector' ); Net::Proxy->set_state( $sock, $state ); is( Net::Proxy->get_state( $sock ), $state, 'Got back the state' ); # data is not clobbered is( Net::Proxy->get_connector( $sock ), $connector, 'Got back the connector' ); is( Net::Proxy->get_peer( $sock ), $peer, 'Got back the peer' ); 37connectssl_tcp.t100644001750001750 607412425533447 16275 0ustar00bookbook000000000000Net-Proxy-0.13/tuse Test::More; use strict; use warnings; use IO::Socket::INET; use File::Spec::Functions; use t::Util; use Net::Proxy; my @lines = ( "saturday wednesday tuesday sunday friday\n", "agnes_nitt granny_weatherwax greebo vorbis jason_ogg\n", "Moins Scrof Ferla_Quist Caine Grove_Of_The_Unicorn\n", "rook pawn queen king bishop\n", "Fedora QiLinux gnuLinEx ZoneCD ROSLIMS\n", ); my $tests = @lines + 3; init_rand(@ARGV); plan tests => $tests; SKIP: { # check required modules for this test case for my $module (qw( LWP::UserAgent HTTP::Daemon IO::Socket::SSL )) { eval "require $module;"; skip "$module required to test connect_ssl", $tests if $@; } # lock 2 ports my @free = find_free_ports(2); skip "Not enough available ports", $tests if @free < 2; my ( $proxy_port, $web_proxy_port ) = @free; my $pid = fork_proxy( { in => { type => 'tcp', host => 'localhost', port => $proxy_port }, out => { type => 'connect_ssl', host => 'zlonk.crunch.com', port => 443, proxy_host => 'localhost', proxy_port => $web_proxy_port, }, }, 2 ); skip "fork failed", $tests if !defined $pid; # wait for the proxy to set up sleep 1; # the parent process does the testing my $daemon = HTTP::Daemon->new( LocalAddr => 'localhost', LocalPort => $web_proxy_port, ) or skip "Couldn't start the server: $!", $tests; my $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", $tests; my $server = $daemon->accept() or skip_fail "Proxy didn't connect: $!", $tests; # the server will first play the role of the web proxy, # and after a 200 OK will also act as a real server # check the request my $req = $server->get_request(); is( $req->method(), 'CONNECT', 'Proxy did a CONNECT' ); is( $req->uri()->host_port(), 'zlonk.crunch.com:443', 'host:port' ); # first time, the web proxy says 200 $server->send_response( HTTP::Response->new('200') ); # now the client will use SSL IO::Socket::SSL->start_SSL( $server, SSL_server => 1, SSL_cert_file => catfile( 't', 'test.cert' ), SSL_key_file => catfile( 't', 'test.key' ), ); # send some data through # FIXME this blocks when $server speaks first for my $line (@lines) { print $client $line; is( <$server>, $line, "Line received" ); ( $client, $server ) = random_swap( $client, $server ); } $client->close(); $server->close(); # second time, the web proxy says 403 (how to test this?) $client = connect_to_port($proxy_port) or skip_fail "Couldn't start the client: $!", 1; $server = $daemon->accept() or skip_fail "Proxy didn't connect: $!", 1; $server->get_request(); # ignore it $server->send_response( HTTP::Response->new('403') ); is_closed($client); } release-distmeta.t100644001750001750 43012425533447 16300 0ustar00bookbook000000000000Net-Proxy-0.13/t#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } # This file was automatically generated by Dist::Zilla::Plugin::MetaTests. use Test::CPAN::Meta; meta_yaml_ok(); connect-tunnel100755001750001750 1732712425533447 16663 0ustar00bookbook000000000000Net-Proxy-0.13/script#!/usr/bin/perl -w use strict; use warnings; use Net::Proxy; use Getopt::Long; use Pod::Usage; # die early if this module is not installed eval { require LWP::UserAgent; }; die "LWP::UserAgent required to run connect-tunnel\n" if $@; # default configuration our %CONF = ( 'proxy-authentication' => '', 'proxy' => $ENV{HTTP_PROXY}, 'user-agent' => "connect-tunnel/$Net::Proxy::VERSION", 'verbose' => 0, ); # # get and check the options # GetOptions( \%CONF, "verbose|v+", "tunnel|T=s@", "proxy|P=s", "proxy-authentication|A=s", "local-only|L", "user-agent|U=s" ) or pod2usage(); # set up the verbosity level Net::Proxy->set_verbosity( $CONF{verbose} ); # check for a proxy if ( $CONF{proxy} ) { $CONF{proxy} .= ":8080" if not $CONF{proxy} =~ /:/; } die "--proxy option required$/" if !$CONF{proxy}; # create the tunnels entrances die "--tunnel option required$/" unless exists $CONF{tunnel}; # split proxy-authentication { my ( $user, $pass ) = split ':', $CONF{'proxy-authentication'}, 2; $CONF{'proxy-authentication'} = $CONF{'proxy-authentication'} ? [ proxy_user => $user, proxy_pass => $pass ] : []; } for my $tunnel ( @{ $CONF{tunnel} } ) { die "--tunnel format required$/" if $tunnel !~ /^\d+:[^:]+:\d+$/; my ( $port, $host, $hostport ) = split ':', $tunnel; my ( $proxy_host, $proxy_port) = split ':', $CONF{proxy}; my $proxy = Net::Proxy->new( { in => { type => 'tcp', port => $port, host => $CONF{'local-only'} ? 'localhost' : '0.0.0.0', }, out => { type => 'connect', host => $host, port => $hostport, proxy_host => $proxy_host, proxy_port => $proxy_port, proxy_agent => $CONF{'user-agent'}, @{ $CONF{'proxy-authentication'} }, }, } ); $proxy->register(); } # the main loop Net::Proxy->mainloop(); __END__ =head1 NAME connect-tunnel - Create CONNECT tunnels through HTTP proxies =head1 SYNOPSIS B S<[ B<-Lv> ]> S<[ B<-A> I ]> S<[ B<-P> I ]> S<[ B<-C> I ]> S<[ B<-T> I ]> =head1 DESCRIPTION B sets up tunneled connections to external hosts by redirecting connections to local ports towards thoses hosts/ports through a HTTP proxy. B makes use of the HTTP C method to ask the proxy to create a tunnel to an outside server. Be aware that some proxies are set up to deny outside tunnels (either to ports other than 443 or outside a specified set of outside hosts). =head1 OPTIONS The program follows the usual GNU command line syntax, with long options starting with two dashes. =over 4 =item B<-A>, B<--proxy-authentication> I Proxy authentication information. Please note that all the authentication schemes supported by C are supported (we use an C internally to contact the proxy). =item B<-C>, B<--control-port> I The port to which one can connect to issue control commands to B. See L for more details about the available commands. =item B<-L>, B<--local-only> Create the tunnels so that they will only listen on C. Thus, only connections originating from the machine that runs B will be accepted. That was the default behaviour in B version 0.02. =item B<-P>, B<--proxy> I[I<:port>] The proxy is required to connect the tunnels. If no port is given, 8080 is used by default. See also L. =item B<-T>, B<--tunnel> I Specifies that the given I on the local host is to be forwarded to the given I and I on the remote side. This works by allocating a socket to listen to I on the local side, and whenever a connection is made to this I, B forwards it to the proxy (with the credentials, if required), which in turn forwards it to the final destination. Note that this does not imply the use of any cryptographic system (SSL or any other). This is a simple TCP redirection. The security if any, is the one provided by the protocol used to connect to the destination through B. On Unix systems, only root can forward privileged ports. Note that you can setup tunnels to multiple destinations, by using the B<--tunnel> option several times. =item B<-U>, B<--user-agent> I Specify User-Agent value to send in HTTP requests. The default is to send C>. =item B<-v>, B<--verbose> Verbose output. This option can be used several times for more verbose output. =back =head1 EXAMPLES To connect to a SSH server running on C, on port 443, through the proxy C, running on port 8080, use the following command: connect-tunnel -P proxy.company.com:8080 -T 22:ssh.example.com:443 And now point your favorite ssh client to the machine running B. You can also emulate a "standard" user-agent: connect-tunnel -U "Mozilla/4.03 [en] (X11; I; Linux 2.1.89 i586)" -P proxy.company.com:8080 -T 22:ssh.example.com:443 B can easily use your proxy credentials to connect outside: connect-tunnel -U "Mozilla/4.03 [en] (X11; I; Linux 2.1.89 i586)" -P proxy.company.com:8080 -T 22:ssh.example.com:443 -A book:s3kr3t But if you don't want anybody else to connect to your tunnels and through the proxy with I credentials, use the B<--local-only> option: connect-tunnel -U "Mozilla/4.03 [en] (X11; I; Linux 2.1.89 i586)" -P proxy.company.com:8080 -T 22:ssh.example.com:443 -A book:s3kr3t -L If you have several destinations, there is no need to run several instances of B: connect-tunnel -U "Mozilla/4.03 [en] (X11; I; Linux 2.1.89 i586)" -P proxy.company.com:8080 -A book:s3kr3t -L -T 22:ssh.example.com:443 -T 222:ssh2.example.com:443 But naturally, you will need to correctly set up the ports in your clients. Mmm, such a long command line would perfectly fit in an alias or a F<.BAT> file. C<;-)> =head1 ENVIRONMENT VARIABLES The environment variable C can be used to provide a proxy definition. The environment variable is overriden by the B<--proxy> option, if passed to B. =head1 AUTHOR Philippe "BooK" Bruhat, C<< >>. I seem to have re-invented a well-known wheel with that script, but at least, I hope I have added a few interesting options to it. =head1 SCRIPT HISTORY The first version of the script was a quick hack that let me go through a corporate proxy. Version 0.02 and version 0.03 were released on CPAN in 2003. Version 0.04 sits half-finished in a CVS repository at home: I couldn't decypher the spaghetti of my data structures any more. C<:-(> Version 0.05 (and higher) are based on C, and included with the C distribution. =head1 Even though it's not rocket science, B has been cited in at least one academic works: =over 4 =item * I, Daniel Alman Available at SANS InfoSec Reading Room: Covert Channels L Direct link: L =back =head1 COPYRIGHT Copyright 2003-2007, Philippe Bruhat. All rights reserved. =head1 LICENSE This module is free software; you can redistribute it or modify it under the same terms as Perl itself. =cut 12proxy_connectors.t100644001750001750 104412425533447 16653 0ustar00bookbook000000000000Net-Proxy-0.13/tuse strict; use warnings; use Test::More tests => 5; use Net::Proxy; my $proxy = Net::Proxy->new( { in => { type => 'dummy' }, out => { type => 'dummy' }, } ); isnt( $proxy->in_connector(), $proxy->out_connector(), 'Distinct connectors' ); ok( $proxy->in_connector()->is_in(), 'in_connector() is "in"' ); ok( !$proxy->out_connector()->is_in(), 'out_connector() is not "in"' ); ok( !$proxy->in_connector()->is_out(), 'in_connector() is not "out"' ); ok( $proxy->out_connector()->is_out(), 'out_connector() is "out"' ); release-pod-syntax.t100644001750001750 45612425533447 16604 0ustar00bookbook000000000000Net-Proxy-0.13/t#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use Test::More; use Test::Pod 1.41; all_pod_files_ok(); release-pod-coverage.t100644001750001750 57212425533447 17050 0ustar00bookbook000000000000Net-Proxy-0.13/t#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } # This file was automatically generated by Dist::Zilla::Plugin::PodCoverageTests. use Test::Pod::Coverage 1.08; use Pod::Coverage::TrustPod; all_pod_coverage_ok({ coverage_class => 'Pod::Coverage::TrustPod' }); Proxy000755001750001750 012425533447 14720 5ustar00bookbook000000000000Net-Proxy-0.13/lib/NetConnector.pm100644001750001750 2240712425533447 17375 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxypackage Net::Proxy::Connector; $Net::Proxy::Connector::VERSION = '0.13'; use strict; use warnings; use Carp; use Scalar::Util qw( refaddr ); use Net::Proxy; my %PROXY_OF; my $BUFFSIZE = 4096; # # the most basic possible constructor # sub new { my ( $class, $args ) = @_; my $self = bless $args ? {%$args} : {}, $class; $self->init() if $self->can('init'); delete $self->{_proxy_}; # this link back is now unnecessary return $self; } # # Each Connector is managed by a Net::Proxy object # sub set_proxy { my ( $self, $proxy ) = @_; croak "$proxy is not a Net::Proxy object" if !UNIVERSAL::isa( $proxy, 'Net::Proxy' ); return $PROXY_OF{ refaddr $self } = $proxy; } sub get_proxy { return $PROXY_OF{ refaddr $_[0] }; } sub is_in { my $id = refaddr $_[0]; return $id == refaddr $PROXY_OF{$id}->in_connector(); } sub is_out { my $id = refaddr $_[0]; return $id == refaddr $PROXY_OF{$id}->out_connector(); } # # the method that creates all the sockets # sub new_connection_on { my ( $self, $listener ) = @_; Net::Proxy->notice( 'New connection on ' . Net::Proxy->get_nick($listener) ); # call the actual Connector method my $sock = eval { $self->accept_from($listener); }; if( $@ ) { Net::Proxy->error( $@ ); return; } Net::Proxy->set_connector( $sock, $self ); Net::Proxy->set_buffer( $sock, '' ); Net::Proxy->set_callback( $sock, $self->{hook} ) if $self->{hook}; Net::Proxy->watch_reader_sockets($sock); # connect to the destination my $out = $self->get_proxy()->out_connector(); $out->_out_connect_from($sock); # update the stats $self->get_proxy()->stat_inc_opened(); return; } sub _out_connect_from { my ( $self, $sock ) = @_; my $peer = eval { $self->connect(); }; if ($@) { # connect() dies if the connection fails $@ =~ s/ at .*?\z//s; warn "connect() failed with error '$@'\n"; Net::Proxy->close_sockets($sock); return; } if ($peer) { # $peer is undef for Net::Proxy::Connector::dummy Net::Proxy->watch_reader_sockets($peer); Net::Proxy->set_connector( $peer, $self ); Net::Proxy->set_buffer( $peer, '' ); Net::Proxy->set_callback( $peer, $self->{hook} ) if $self->{hook}; Net::Proxy->set_nick( $peer, $peer->sockhost() . ':' . $peer->sockport() . ' -> ' . $peer->peerhost() . ':' . $peer->peerport() ); Net::Proxy->notice( 'Connected ' . Net::Proxy->get_nick( $peer ) ); Net::Proxy->set_peer( $peer, $sock ); Net::Proxy->set_peer( $sock, $peer ); Net::Proxy->notice( 'Peered ' . Net::Proxy->get_nick($sock) . ' with ' . Net::Proxy->get_nick($peer) ); } return; } # # base methods for exchanging raw data # # return raw data from the socket sub raw_read_from { my ( $self, $sock ) = @_; # low level read on the socket my $close = 0; my $buffer; my $read = $sock->sysread( $buffer, $BUFFSIZE ); ## Net::Proxy->debug("Read $read bytes from " . Net::Proxy->get_nick($sock)); # check for errors if ( not defined $read ) { warn sprintf( "Read undef from %s:%s (Error %d: %s)\n", $sock->sockhost(), $sock->sockport(), $!, "$!" ); $close = 1; } # connection closed if ( $close || $read == 0 ) { # $sock was closed either forcefully or gracefully, either way # we have no chance to send remaining data Net::Proxy->set_buffer( $sock, '' ); my $peer = Net::Proxy->get_peer($sock); $self->get_proxy()->close_sockets( $sock, $peer ); return; } return $buffer; } # send raw data to the socket sub raw_write_to { my ($self, $sock) = @_; my $data = Net::Proxy->get_buffer( $sock ); ## Net::Proxy->debug("Writing @{[length $data]} bytes (max $BUFFSIZE) to " . Net::Proxy->get_nick($sock)); my $written = $sock->syswrite( $data, $BUFFSIZE ); ## Net::Proxy->debug("Wrote $written bytes to " . Net::Proxy->get_nick($sock)); if( ! defined $written ) { warn sprintf("Read undef from %s:%s (Error %d: %s)\n", $sock->sockhost(), $sock->sockport(), $!, "$!"); } elsif ( $written == length $data ) { Net::Proxy->remove_writer_sockets( $sock ); Net::Proxy->set_buffer( $sock, '' ); } else { # there is some data left to write Net::Proxy->set_buffer( $sock, substr( $data, $written ) ); } return; } # # base methods for listen() and accept_from() # # the most basic possible listen() sub raw_listen { my $self = shift; my $sock = IO::Socket::INET->new( Listen => 1, LocalAddr => $self->{host}, LocalPort => $self->{port}, Proto => 'tcp', ReuseAddr => $^O eq 'MSWin32' ? 0 : 1, ); # this exception is not catched by Net::Proxy die "Can't listen on $self->{host} port $self->{port}: $!" unless $sock; Net::Proxy->set_nick( $sock, 'listener ' . $sock->sockhost() . ':' . $sock->sockport() ); return $sock; } # accept on a socket and return the new connected socket sub raw_accept_from { my ($self, $listen) = @_; my $sock = $listen->accept(); die $! unless $sock; Net::Proxy->set_nick( $sock, $sock->peerhost() . ':' . $sock->peerport() . ' -> ' . $sock->sockhost() . ':' . $sock->sockport() ); Net::Proxy->notice( 'Accepted ' . Net::Proxy->get_nick( $sock ) ); return $sock; } 1; __END__ =head1 NAME Net::Proxy::Connector - Base class for Net::Proxy protocols =head1 SYNOPSIS # # template for the zlonk connector # package Net::Proxy::Connector::zlonk; use strict; use Net::Proxy::Connector; our @ISA = qw( Net::Proxy::Connector ); # here are the methods you need to write for your connector # if it can be used as an 'in' connector sub listen { } sub accept_from { } # if it can be used as an 'out' connector sub connect { } # to process data sub read_from { } sub write_to { } 1; =head1 DESCRIPTION Net::Proxy::Connector is the base class for all specialised protocols used by L. =head1 METHODS =head2 Class methods The base class provides the following methods: =head3 new The constructor. =head2 Instance methods =head3 set_proxy $connector->set_proxy( $proxy ); Define the proxy that "owns" the connector. =head3 get_proxy my $proxy = $connector->get_proxy(); Return the L object that "owns" the connector. =head3 is_in $connector->is_in(); Return a boolean value indicating if the Net::Proxy::Connector object is the C connector of its proxy. =head3 is_out $connector->is_out(); Return a boolean value indicating if the Net::Proxy::Connector object is the C connector of its proxy. =head3 new_connection_on $connector->new_connection_on( $socket ); This method is called by L to handle incoming connections, and in turn call C on the 'in' connector and C on the 'out' connector. =head3 raw_read_from my $data = $connector->raw_read_from( $socket ); This method can be used by Net::Proxy::Connector subclasses in their C methods, to fetch raw data on a socket. =head3 raw_write_to $connector->raw_write_to( $socket, $data ); This method can be used by Net::Proxy::Connector subclasses in their C methods, to send raw data on a socket. =head3 raw_listen my $sock = $connector->raw_listen(); This method can be used by Net::Proxy::Connector subclasses in their C methods, to create a listening socket on their C and C parameters. =head3 raw_accept_from my $sock = $connector->raw_accept_from( $socket ); This method can be used internaly by Net::Proxy::Connector subclasses in their C methods, to accept a newly connected socket. =head1 SUBCLASS METHODS The following methods should be defined in Net::Proxy::Connector subclasses: =head2 Initialisation =head3 init $connector->init; This method initalizes the connector. =head2 Processing incoming/outgoing data =head3 read_from my $data = $connector->read_from( $socket ); Return the data that was possibly decapsulated by the connector. =head3 write_to $connector->write_to( $socket, $data ); Write C<$data> to the given C<$socket>, according to the connector scheme. =head2 C connector =head3 listen my $sock = $connector->listen(); Initiate listening sockets and return them. This method can use the C method to do the low-level listen call. =head3 accept_from my $sock = $connector->accept_from( $socket ); C<$socket> is a listening socket created by C. This method returns the connected socket. This method can use the C method to do the low-level accept call. =head2 C connector =head3 connect my $sock = $connector->connect(); Return a socket connected to the remote server. =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut Tutorial.pod100644001750001750 3535412425533447 17421 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy=encoding utf-8 =head1 NAME Net::Proxy::Tutorial - Network proxies for fun and profit =head1 SYNOPSIS This document describes in detail how to use L in several real-life situations. =head1 DEFINITIONS =head2 What is a proxy? You need a proxy every time you need to cross network boundaries to reach a service that is not directly accessible. The typical example is the corporate web proxy in a company. The corporate firewall is a boundary, usually very tightly closed, between the corporate network and the outside world (wild wild Internet). To let the employees access all the nice web sites outside, the company sets up a web proxy, which is authorised to cross the boundary (firewall) on your behalf. The web browser asks the proxy for whatever it needs, and the proxy goes and fetches the requested stuff on the web. Since the proxy sees the client requests, it can check if they fit the corporate browsing policy and decide if it will fetch the document for the requestor. It can also request authentication, and log the username with the request. Transparent proxies mimic the actual service you asked for, and reply as if they were the actual service provider. Except that the client doesn't notice there is a proxy in between. Most transparent web proxies grab outgoing traffic on port 80. Some ISP do this to cache responses and spare their bandwidth. =head2 Why do I need a proxy? Sometimes, the traffic you want to send or receive doesn't quite fit the model that the network designers had in mind. For example, if you need to modify network traffic, almost transparently, at a high level, you probably need L. =head1 DESCRIPTION In this section, we will see actual examples of use of L. =head2 A basic L script Most L based scripts look like the following: =over 4 =item * The usual boilerplate: #!perl use strict; use warnings; use Net::Proxy; =item * One or more proxies are created by calling C with the appropriate parameters: my $proxy = Net::Proxy->new( ... ); =item * The individual proxies are registered with the L framework: $proxy->register(); =item * Some framework options are defined: Net::Proxy->set_verbosity(1); Note: The C method is available only since L version 0.04. =item * The framework is started, sets up the listening sockets, and waits for connections to proxy around: Net::Proxy->mainloop(); =back =head2 The concepts behind L Any time a proxy handles a network connection, it actually manages two connections: a connection from the client to the proxy, and a connection from the proxy to the server. During normal processing, each chunk of data received on one connection is copied to the other connection, and vice-versa. L introduces the concept of "connectors". Connectors are used to represent the ends of the two connections that the proxy handles to create a single client-server connection. +-------+ | proxy | | | "client" --->(xx)[in] [out]---> "server" +-------+ In the above ASCII diagram, C<(xx)> represents the listening port number, and C<[in]> (left) and C<[out]> (right) the L connectors. The C connector accepts incoming connections on a listening port. Once a connection with the client is established, the proxy uses the C connector to connect to the destination server. The simplest connector is named L (we'll use C for short). When placed on the C side, it simply Cs for incoming connections and them Cs them. Then the C connector Cs to the server. Each connector accepts different parameters, which we'll see in the following examples. Since the proxy must handle every item of data going through, it can look at it, and modify it. This is what other connectors do: they can insert or transform data on the fly, which provides us with an incredible amount of power on our network connections, which we will leverage throughout this document. =head1 REAL-LIFE EXAMPLES =head2 Contacting a SSH server through the corporate web proxy (This example requires at least L version 0.02 to work.) In many companies, the corporate firewall doesn't let you connect outside with SSH. The only allowed access to the outside is via the web proxy. Luckily, web proxies are designed to let certain types of TCP connection go through them without modifications: encrypted SSL connections, used in HTTPS. These connections are handled in the following way: the client sends a C connect to the proxy which (according to a policy based on the hostname, port and the user's credentials) actually connects to the remote host and transfers the data between the client and server, without looking at the encrypted data. The proxy doesn't even check that the traffic is actual SSL traffic. So your SSH client could connect to a local proxy, which would send the C request to the web proxy, asking for a connection to your home SSH server. Thereafter, the local proxy would behave like a standard TCP proxy and simply pass the data around. Here is a network diagram showing the network configuration in ASCII-art: ' (internal network) ' (Internet) ' +-------+ +-------+ ' +-------+ | local | | web | ' | ssh | ssh | proxy | | proxy | ' | server| client --->(22)[tcp] | | | ' | | |[connect]-->(8080) |----'--->(22) | +-------+ +-------+ ' +-------+ ' ' Here's how to set up the local L instance: Net::Proxy->new( { in => { type => 'tcp', host => 'localhost', port => 22, }, out => { type => 'connect', host => 'home.example.com', port => 22, # proxy details proxy_host => 'proxy.mycompany.com', proxy_port => 8080, # proxy credentials proxy_user => 'me', proxy_pass => 's3kr3t', }, } )->register(); Most of the time, corporate web proxies do not allow connections on other ports than 443, the standard HTTPS port. You just need to reconfigure your SSH server so that it also listens on port 443: # sshd configuration file Port 22 Port 443 In the exemple above, you need to change the C/C from C<22> to C<443>. Many SSH clients (like PuTTY) already include configuration options to get through web proxies, so L probably isn't necessary any longer to handle this kind of traffic. =head2 Running two services on the same TCP port (This example requires at least L version 0.03 to work.) So you managed to get out of your corporate prison^Wnetwork by setting up your SSH server to listen on port 443. The problem is that you also run a HTTPS server; and if you want it to be accessible to anyone, it must run on port 443 (otherwise the corporate proxy won't let you pass through, and noone will find it anyway). Therefore, the only option is to run both the SSL web server and the SSH server on I. How is that even possible? TCP clearly doesn't allow this (or we wouldn't need those long F files in our F directories). What you need is a proxy that can guess what the client wants, but without contacting the server. If it manages to find out which server the client wants to connect to, it can then contact the expected server and do its usual proxy job. Luckily, there is a fundamental difference of behaviour between a http/s client and a SSH client: =over 4 =item * during a HTTP(S) connection, the client "speaks" first =item * during a SSH connection, the server sends a banner first =back ' (Internet) ' (internal network) ' ' +-------+ ' |reverse| ' | proxy | SSL client ---'--->( | [tcp]---> SSL server ' ((443)[dual] | SSH client ---'--->( | [tcp]---> SSH server ' +-------+ ' L's C connector is able to detect between two such clients with the help of a timeout. Net::Proxy->new( { in => { type => 'dual', host => '0.0.0.0', port => 443, client_first => { type => 'tcp', port => 444, # move the https server to another port }, server_first => { type => 'tcp', port => 22, # good old SSH }, # wait during a 2 second timeout timeout => 2, }, out => { type => 'dummy' }, } )->register(); =head2 Hiding SSH connections going through the corporate proxy from IDS (This example requires at least L version 0.06 to work.) The first technique we presented (using a CONNECT request to get out of the corporate network) is so well-known that many Intrusion Detection Systems (IDS) check the first packets of a connection to try and find hidden SSH connections crossing the corporate boundaries outwards. The server banner looks like this: SSH-2.0-OpenSSH_3.9p1 while the client banner may look like this: SSH-2.0-OpenSSH_4.2p1 Debian-5 You want to deceive Intrusion Detection Systems (IDS) by modifying the cleartext part of your SSH connection. Since the detection code simply looks for the "C" string, an "encryption" scheme as simple as ROT-13 is enough. ' (internal network) ' (Internet) ' +-------+ +-------+ ' +-------+ | local | | web | ' |reverse| ssh | proxy | | proxy | ' | proxy | client --->(22)[tcp] | | | ' | | |[connect]===>(8080) |===='===>(443)[tcp][tcp]---> ssh +-------+ +-------+ ' +-------+ server ' Traffic \________ ________/' ---> ssh v ' ===> ssh + rot13 Traffic scanned ' by the IDS ' ' The C connector option accepts a callback that will be called for each chunk of data received, before sending it out. The callback must have the following signature: # Net::Proxy versions 0.06 and 0.07 sub { my ( $dataref, $connector ) = @_; ... } # As from Net::Proxy version 0.08 sub { my ( $dataref, $socket, $connector ) = @_; ... } The ROT-13 routine is straightforward (and must be defined in both scripts): my $rot13 = sub { ${ $_[0] } =~ y/A-Za-z/N-ZA-Mn-za-m/ }; Client-side proxy: Net::Proxy->new( { in => { type => 'tcp', host => '0.0.0.0', port => 22, hook => $rot13 }, out => { type => 'connect', host => 'home.example.com', port => 22, hook => $rot13, # proxy configuration proxy_host => 'proxy.mycompany.com', proxy_port => 8080, # proxy credentials proxy_user => 'me', proxy_pass => 's3kr3t', }, } )->register(); Server-side proxy: Net::Proxy->new( { in => { type => 'tcp', host => '0.0.0.0', port => 443, hook => $rot13 }, out => { type => 'tcp', port => 22, hook => $rot13 } } )->register(); =head2 Hiding a SSH connection under SSL through a corporate proxy (This example requires at least L version 0.08 to work.) Another option to hide what you are doing in your connection through the corporate proxy, is to actually use SSL to connect to your SSH server (I<à la> B). This is what the proxy expects, after all. ' (internal network) ' (Internet) ' +-----------+ +-------+ ' +-------+ | local | | web | ' |reverse| ssh | proxy | | proxy | ' | proxy | client -->(22)[tcp] | | | ' | | |[connect_ssl]===>(8080) |==='==>(443)[ssl][tcp]---> ssh +-----------+ +-------+ ' +-------+ server ' Traffic \_______ _______/' ---> ssh v ' ===> ssh over SSL Traffic scanned ' by the IDS ' ' Client-side proxy: Net::Proxy->new( { in => { type => 'tcp', host => '0.0.0.0', port => 22, }, out => { type => 'connect_ssl', host => 'home.example.com', port => 443, # proxy configuration proxy_host => 'proxy.mycompany.com', proxy_port => 8080, # proxy credentials proxy_user => 'me', proxy_pass => 's3kr3t', }, } )->register(); Server-side proxy: Net::Proxy->new( { in => { type => 'ssl', host => '0.0.0.0', port => 443, }, out => { type => 'tcp', port => 22, } } )->register(); =head1 AUTHOR Philippe "BooK" Bruhat, C<< >>. =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This tutorial is distributed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License. =cut 000-report-versions-tiny.t100644001750001750 602112425533447 17531 0ustar00bookbook000000000000Net-Proxy-0.13/tuse strict; use warnings; use Test::More 0.88; # This is a relatively nice way to avoid Test::NoWarnings breaking our # expectations by adding extra tests, without using no_plan. It also helps # avoid any other test module that feels introducing random tests, or even # test plans, is a nice idea. our $success = 0; END { $success && done_testing; } # List our own version used to generate this my $v = "\nGenerated by Dist::Zilla::Plugin::ReportVersions::Tiny v1.08\n"; eval { # no excuses! # report our Perl details my $want = '5.006'; $v .= "perl: $] (wanted $want) on $^O from $^X\n\n"; }; defined($@) and diag("$@"); # Now, our module version dependencies: sub pmver { my ($module, $wanted) = @_; $wanted = " (want $wanted)"; my $pmver; eval "require $module;"; if ($@) { if ($@ =~ m/Can't locate .* in \@INC/) { $pmver = 'module not found.'; } else { diag("${module}: $@"); $pmver = 'died during require.'; } } else { my $version; eval { $version = $module->VERSION; }; if ($@) { diag("${module}: $@"); $pmver = 'died during VERSION check.'; } elsif (defined $version) { $pmver = "$version"; } else { $pmver = ''; } } # So, we should be good, right? return sprintf('%-45s => %-10s%-15s%s', $module, $pmver, $wanted, "\n"); } eval { $v .= pmver('Carp','any version') }; eval { $v .= pmver('ExtUtils::MakeMaker','6.30') }; eval { $v .= pmver('File::Find','any version') }; eval { $v .= pmver('File::Spec','any version') }; eval { $v .= pmver('File::Spec::Functions','any version') }; eval { $v .= pmver('Getopt::Long','any version') }; eval { $v .= pmver('IO::Handle','any version') }; eval { $v .= pmver('IO::Select','any version') }; eval { $v .= pmver('IO::Socket::INET','any version') }; eval { $v .= pmver('IO::Socket::SSL','any version') }; eval { $v .= pmver('IPC::Open3','any version') }; eval { $v .= pmver('LWP::UserAgent','any version') }; eval { $v .= pmver('POSIX','any version') }; eval { $v .= pmver('Pod::Coverage::TrustPod','any version') }; eval { $v .= pmver('Pod::Usage','any version') }; eval { $v .= pmver('Scalar::Util','any version') }; eval { $v .= pmver('Test::Builder','any version') }; eval { $v .= pmver('Test::CPAN::Meta','any version') }; eval { $v .= pmver('Test::More','0.88') }; eval { $v .= pmver('Test::Pod','1.41') }; eval { $v .= pmver('Test::Pod::Coverage','1.08') }; eval { $v .= pmver('strict','any version') }; eval { $v .= pmver('version','0.9901') }; eval { $v .= pmver('warnings','any version') }; # All done. $v .= <<'EOT'; Thanks for using my code. I hope it works for you. If not, please try and include this output in the bug report. That will help me reproduce the issue and solve your problem. EOT diag($v); ok(1, "we really didn't test anything, just reporting data"); $success = 1; # Work around another nasty module on CPAN. :/ no warnings 'once'; $Template::Test::NO_FLUSH = 1; exit 0; Connector000755001750001750 012425533447 16652 5ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxytcp.pm100644001750001750 371512425533447 20144 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy/Connectorpackage Net::Proxy::Connector::tcp; $Net::Proxy::Connector::tcp::VERSION = '0.13'; use strict; use warnings; use IO::Socket::INET; use Net::Proxy::Connector; our @ISA = qw( Net::Proxy::Connector ); sub init { my ($self) = @_; # set up some defaults $self->{host} ||= 'localhost'; $self->{timeout} ||= 1; } # IN *listen = \&Net::Proxy::Connector::raw_listen; *accept_from = \&Net::Proxy::Connector::raw_accept_from; # OUT sub connect { my ($self) = @_; my $sock = IO::Socket::INET->new( PeerAddr => $self->{host}, PeerPort => $self->{port}, Proto => 'tcp', Timeout => $self->{timeout}, ); die $! unless $sock; return $sock; } # READ *read_from = \&Net::Proxy::Connector::raw_read_from; # WRITE *write_to = \&Net::Proxy::Connector::raw_write_to; 1; __END__ =head1 NAME Net::Proxy::Connector::tcp - Net::Proxy connector for standard tcp proxies =head1 SYNOPSIS # sample proxy using Net::Proxy::Connector::tcp use Net::Proxy; my $proxy = Net::Proxy->new( in => { type => tcp, port => '6789' }, out => { type => tcp, host => 'remotehost', port => '9876' }, ); $proxy->register(); Net::Proxy->mainloop(); =head1 DESCRIPTION C is a connector for handling basic, standard TCP connections. =head1 CONNECTOR OPTIONS The connector accept the following options: =head2 C =over 4 =item host The listening address. If not given, the default is C. =item port The listening port. =back =head2 C =over 4 =item host The remote host. =item port The remote port. =item timeout The socket timeout for connection (C only). =back =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut ssl.pm100644001750001750 1427012425533447 20175 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy/Connectorpackage Net::Proxy::Connector::ssl; $Net::Proxy::Connector::ssl::VERSION = '0.13'; use strict; use warnings; use Net::Proxy::Connector; use IO::Socket::SSL; use Scalar::Util qw( refaddr ); use Carp; our @ISA = qw( Net::Proxy::Connector ); my %IS_SSL; sub init { my ($self) = @_; # set up some defaults $self->{host} ||= 'localhost'; } # IN sub listen { my ($self) = @_; my $sock; # start as a SSL socket (default) if ( !$self->{start_cleartext} ) { $sock = IO::Socket::SSL->new( Listen => 1, LocalAddr => $self->{host}, LocalPort => $self->{port}, Proto => 'tcp', map { $_ => $self->{$_} } grep { /^SSL_/ } keys %$self ); # this exception is not catched by Net::Proxy die "Can't listen on $self->{host} port $self->{port}: " . IO::Socket::SSL::errstr() unless $sock; } # or as a standard TCP socket, which may be upgraded later else { $sock = IO::Socket::INET->new( Listen => 1, LocalAddr => $self->{host}, LocalPort => $self->{port}, Proto => 'tcp', ); # this exception is not catched by Net::Proxy die "Can't listen on $self->{host} port $self->{port}: $!" unless $sock; } # remember the class of the socket $IS_SSL{ refaddr $sock } = !$self->{start_cleartext}; Net::Proxy->set_nick( $sock, 'SSL listener ' . $sock->sockhost() . ':' . $sock->sockport() ); Net::Proxy->info( 'Started ' . Net::Proxy->get_nick($sock) . ' as ' . ( $self->{start_cleartext} ? 'cleartext' : 'SSL' ) ); return $sock; } sub accept_from { my ($self, $listen) = @_; my $sock = $listen->accept(); die IO::Socket::SSL::errstr() if ! $sock; Net::Proxy->set_nick( $sock, $sock->peerhost() . ':' . $sock->peerport() . ' -> ' . $sock->sockhost() . ':' . $sock->sockport() ); Net::Proxy->notice( 'Accepted ' . Net::Proxy->get_nick( $sock ) ); return $sock; } # OUT sub connect { my ($self) = @_; my $sock; # connect as a SSL socket (default) if ( !$self->{start_cleartext} ) { $sock = IO::Socket::SSL->new( PeerAddr => $self->{host}, PeerPort => $self->{port}, Proto => 'tcp', Timeout => $self->{timeout}, map { $_ => $self->{$_} } grep { /^SSL_/ } keys %$self ); } # or as a standard TCP socket, which may be upgraded later else { $sock = IO::Socket::INET->new( PeerAddr => $self->{host}, PeerPort => $self->{port}, Proto => 'tcp', Timeout => $self->{timeout}, ); } die $self->{start_cleartext} ? $! : IO::Socket::SSL::errstr() unless $sock; return $sock; } # READ *read_from = \&Net::Proxy::Connector::raw_read_from; # WRITE *write_to = \&Net::Proxy::Connector::raw_write_to; # SSL-related methods # upgrade the socket to SSL (if needed) sub upgrade_SSL { my ( $self, $sock ) = @_; if ( $IS_SSL{ refaddr $sock } ) { carp( Net::Proxy->get_nick($sock) . ' already is a SSL socket' ); return $sock; } IO::Socket::SSL->start_SSL( $sock, SSL_server => $self->is_in(), map { $_ => $self->{$_} } grep { /^SSL_/ } keys %$self ); $IS_SSL{ refaddr $sock } = 1; Net::Proxy->notice( 'Upgraded ' . Net::Proxy->get_nick($sock) . ' to SSL' ); return $sock; } 1; __END__ =head1 NAME Net::Proxy::Connector::ssl - SSL Net::Proxy connector =head1 DESCRIPTION C is a C that can manage SSL connections (thanks to C). By default, this connector creates SSL sockets. You will need to subclass it to create "smarter" connectors than can upgrade their connections to SSL. In addition to the options listed below, this connector accepts all C options to C. They are transparently passed through to the appropriate C methods when needed. =head1 CONNECTOR OPTIONS The connector accept the following options: =head2 C =over 4 =item host The listening address. If not given, the default is C. =item port The listening port. =item start_cleartext If true, the connection will start in cleartext. It is possible to upgrade a socket to using SSL with the C method. =back =head2 C =over 4 =item host The listening address. If not given, the default is C. =item port The listening port. =item start_cleartext If true, the connection will start in cleartext. It is possible to upgrade a socket to using SSL with the C method. =back =head1 METHODS The Net::Proxy::Connector::ssl connector has an extra method: =head2 upgrade_SSL $connector->upgrade_SSL( $sock ) This method will upgrade a cleartext socket to SSL. If the socket is already in SSL, it will C. =head1 CREATING A SELF-SIGNED CERTIFICATE I tend to forget this information, and the openssl documentation doesn't make this any clearer, so here are the most basic commands needed to create your own self-signed certificate (courtesy David Morel): $ openssl genrsa -out key.pem 1024 $ openssl req -new -key key.pem -x509 -out cert.pem -days 365 A certificate is required is you want to run a SSL server or a proxy with a C as its C connector. Once the key and certificate have been created, you can use them in your parameter list to C<< Net::Proxy->new() >> (they are passed through to C): Net::Proxy->new( { in => { host => '0.0.0.0', port => 443, SSL_key_file => 'key.pem', SSL_cert_file => 'cert.pem', }, out => { type => 'tcp', port => '80' } } ); =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut dual.pm100644001750001750 1002612425533447 20314 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy/Connectorpackage Net::Proxy::Connector::dual; $Net::Proxy::Connector::dual::VERSION = '0.13'; use strict; use warnings; use Carp; use Scalar::Util qw( reftype ); use Net::Proxy::Connector; our @ISA = qw( Net::Proxy::Connector ); sub init { my ($self) = @_; # check connectors for my $conn (qw( client_first server_first )) { croak "'$conn' connector required" if !exists $self->{$conn}; croak "'$conn' connector must be a HASHREF" if ref $self->{$conn} ne 'HASH'; croak "'type' key required for '$conn' connector" if !exists $self->{$conn}{type}; croak "'hook' key is not a CODE reference for '$conn' connector" if $self->{$conn}{hook} && reftype( $self->{$conn}{hook} ) ne 'CODE'; # load the class my $class = 'Net::Proxy::Connector::' . $self->{$conn}{type}; eval "require $class"; croak "Couldn't load $class for '$conn' connector: $@" if $@; # create and store the Connector object $self->{$conn} = $class->new( $self->{$conn} ); $self->{$conn}->set_proxy($self->{_proxy_}); } # other parameters croak q{Parameter 'port' is required} if !exists $self->{port}; $self->{timeout} ||= 1; # by default wait for one second $self->{host} ||= 'localhost'; # by default listen on localhost return; } # IN *listen = \&Net::Proxy::Connector::raw_listen; sub accept_from { my ( $self, $listen ) = @_; my $sock = $self->raw_accept_from($listen); # find out who speaks first # if the client talks first, it's a client_first connection my $waiter = IO::Select->new($sock); my @waited = $waiter->can_read( $self->{timeout} ); my $type = @waited ? 'client_first' : 'server_first'; # do the outgoing connection $self->{$type}->_out_connect_from($sock); return $sock; } # OUT # READ *read_from = \&Net::Proxy::Connector::raw_read_from; # WRITE *write_to = \&Net::Proxy::Connector::raw_write_to; 1; __END__ =encoding utf-8 =head1 NAME Net::Proxy::Connector::dual - Y-shaped Net::Proxy connector =head1 DESCRIPTION Net::Proxy::Connecter::dual is a L that can forward the connection to two distinct services, based on the client connection, before any data is exchanged. =head1 CONNECTOR OPTIONS This connector can only work as an C connector. The C and C options are required: they are hashrefs containing the options necessary to create two C L objects that will be used to connect to the requested service. The Net::Proxy::Connector::dual object decides between the two services by waiting during a short timeout. If the client sends some data directly, then it is connected via the C connector. Otherwise, at the end of the timeout, it is connected via the C connector. =over 4 =item host The hostname on which the connector will listen for client connections. Default is C. =item port The port on which the connector will listen for client connections. =item server_first Typically an C connector to a SSH server or any service that sends a banner line. =item client_first Typically an C connectrot to a web server or SSL server. =item timeout The timeout in seconds (can be decimal) to make a decision. Default is 1 second. =back =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 ACKNOWLEDGMENTS This module is based on a script named B, which I wrote with Frédéric Plé C<< >> (who had the original insight about the fact that not all servers speak first on the wire). Frédéric wrote a C program, while I wrote a Perl script (based on my experience with B). Now that C is available, I've ported the Perl script to use it. =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut dummy.pm100644001750001750 220712425533447 20504 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy/Connectorpackage Net::Proxy::Connector::dummy; $Net::Proxy::Connector::dummy::VERSION = '0.13'; use strict; use warnings; use Net::Proxy::Connector; our @ISA = qw( Net::Proxy::Connector ); # IN sub listen { } sub accept_from { } # OUT sub connect { } # READ sub read_from { return '' } # WRITE sub write_to { } 1; __END__ =head1 NAME Net::Proxy::Connector::dummy - Dummy Net::Proxy connector =head1 DESCRIPTION C is a C that does I. It doesn't listen for incoming connections and does connect to other hosts. Future connectors may have their C method also handle the connection to a remote host. In this case, C may be used as an 'out' connector. You could also use the source code of this module as a template for writing new C classes. =head1 CONNECTOR OPTIONS None. =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 COPYRIGHT Copyright 2006 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut connect.pm100644001750001750 1035012425533447 21020 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy/Connectorpackage Net::Proxy::Connector::connect; $Net::Proxy::Connector::connect::VERSION = '0.13'; use strict; use warnings; use Carp; use LWP::UserAgent; use Net::Proxy::Connector; our @ISA = qw( Net::Proxy::Connector ); sub init { my ($self) = @_; # check params for my $attr (qw( host port )) { croak "$attr parameter is required" if !exists $self->{$attr}; } # create a user agent class linked to this connector $self->{agent} = my $ua = LWP::UserAgent->new( agent => $self->{proxy_agent}, keep_alive => 1, ); # set the agent proxy if ( $self->{proxy_host} ) { $self->{proxy_port} ||= 8080; $self->{proxy_pass} ||= ''; my $auth = $self->{proxy_user} ? "$self->{proxy_user}:$self->{proxy_pass}\@" : ''; $ua->proxy( http => "http://$auth$self->{proxy_host}:$self->{proxy_port}/" ); } else { $self->{agent}->env_proxy(); } # no proxy defined! croak 'proxy_host parameter is required' unless $ua->proxy('http'); return $self; } # IN # OUT sub connect { my ($self) = (@_); # connect to the proxy my $req = HTTP::Request->new( CONNECT => "http://$self->{host}:$self->{port}/" ); my $res = $self->{agent}->request($req); # authentication failed die $res->status_line() if !$res->is_success(); # the socket connected to the proxy return $res->{client_socket}; } # READ *read_from = \&Net::Proxy::Connector::raw_read_from; # WRITE *write_to = \&Net::Proxy::Connector::raw_write_to; 1; __END__ =head1 NAME Net::Proxy::Connector::connect - Create CONNECT tunnels through HTTP proxies =head1 SYNOPSIS # sample proxy using Net::Proxy::Connector::tcp # and Net::Proxy::Connector::connect use Net::Proxy; # listen on localhost:6789 # and proxy to remotehost:9876 through proxy.company.com:8080 # using the given credentials my $proxy = Net::Proxy->new( in => { type => 'tcp', port => '6789' }, out => { type => 'connect', host => 'remotehost', port => '9876', proxy_host => 'proxy.company.com', proxy_port => '8080', proxy_user => 'jrandom', proxy_pass => 's3kr3t', proxy_agent => 'Mozilla/4.04 (X11; I; SunOS 5.4 sun4m)', }, ); $proxy->register(); Net::Proxy->mainloop(); =head1 DESCRIPTION Net::Proxy::Connecter::connect is a L that uses the HTTP CONNECT method to ask the proxy to create a tunnel to an outside server. Be aware that some proxies are set up to deny the creation of some outside tunnels (either to ports other than 443 or outside a specified set of outside hosts). This connector is only an "out" connector. =head1 CONNECTOR OPTIONS Net::Proxy::Connector::connect accepts the following options: =head1 C =over 4 =item host The destination host. =item port The destination port. =item proxy_host The web proxy name or address. =item proxy_port The web proxy port. =item proxy_user The authentication username for the proxy. =item proxy_pass The authentication password for the proxy. =item proxy_agent The user-agent string to use when connecting to the proxy. =back =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 BUGS All the authentication schemes supported by C should be supported (we use an C internally to contact the proxy). This means we should also support NTLM, since it is supported as from C 5.66. C has not been actually tested with NTLM, though. Any report of success or failure with a NTLM proxy will be appreciated. =head1 HISTORY This module is based on my script C, that provided a command-line interface to create tunnels though HTTP proxies. It was first published on CPAN on March 2003. A better version of C (using C) is provided this distribution. =head1 COPYRIGHT Copyright 2006-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut connect_ssl.pm100644001750001750 765212425533447 21674 0ustar00bookbook000000000000Net-Proxy-0.13/lib/Net/Proxy/Connectorpackage Net::Proxy::Connector::connect_ssl; $Net::Proxy::Connector::connect_ssl::VERSION = '0.13'; use strict; use warnings; use Carp; use Net::Proxy::Connector; use Net::Proxy::Connector::connect; our @ISA = qw( Net::Proxy::Connector::connect ); # we can't subclass Net::Proxy::Connector::ssl, because we don't want listen() # so, mix-in the needed methods from Net::Proxy::Connector::ssl use Net::Proxy::Connector::ssl; *upgrade_SSL = \&Net::Proxy::Connector::ssl::upgrade_SSL; # IN # OUT sub connect { my ($self) = (@_); # connect to the proxy, just like Net::Proxy::Connector::connect my $sock = $self->SUPER::connect(@_); # set a temporary nickname for the socket Net::Proxy->set_nick( $sock, $sock->sockhost() . ':' . $sock->sockport() . ' -> ' . $sock->peerhost() . ':' . $sock->peerport() ); Net::Proxy->notice( 'Connected (HTTP) ' . Net::Proxy->get_nick($sock) ); # and then upgrade the socket to SSL return $self->upgrade_SSL($sock); } # READ # WRITE 1; __END__ =head1 NAME Net::Proxy::Connector::connect_ssl - Create SSL/CONNECT tunnels through HTTP proxies =head1 SYNOPSIS # sample proxy using Net::Proxy::Connector::tcp # and Net::Proxy::Connector::connect_ssl use Net::Proxy; # listen on localhost:6789 # and proxy to remotehost:9876 through proxy.company.com:8080 # using the given credentials my $proxy = Net::Proxy->new( in => { type => 'tcp', port => '6789' }, out => { type => 'connect_ssl', host => 'remotehost', port => '9876', proxy_host => 'proxy.company.com', proxy_port => '8080', proxy_user => 'jrandom', proxy_pass => 's3kr3t', proxy_agent => 'Mozilla/4.04 (X11; I; SunOS 5.4 sun4m)', }, ); $proxy->register(); Net::Proxy->mainloop(); =head1 DESCRIPTION Net::Proxy::Connecter::connect_ssl is a L that uses the HTTP CONNECT method to ask the proxy to create a tunnel to an outside server. The data is then encrypted using SSL. Obviously, you'll need a server that understands SSL (or a proxy using L) at the other end. This connector is only an "out" connector. In addition to the options listed below, this connector accepts all C options to L. They are transparently passed through to the appropriate L methods when upgrading the socket to SSL. =head1 CONNECTOR OPTIONS Net::Proxy::Connector::connect_ssl accepts the following options: =head1 C =over 4 =item host The destination host. =item port The destination port. =item proxy_host The web proxy name or address. =item proxy_port The web proxy port. =item proxy_user The authentication username for the proxy. =item proxy_pass The authentication password for the proxy. =item proxy_agent The user-agent string to use when connecting to the proxy. =back =head1 METHODS The Net::Proxy::Connector::connect_ssl connector has an extra method, obtained from L: =head2 upgrade_SSL $connector->upgrade_SSL( $sock ) This method will upgrade a cleartext socket to SSL. If the socket is already in SSL, it will C. =head1 AUTHOR Philippe 'BooK' Bruhat, C<< >>. =head1 HISTORY Because L blocks when it tries to connect to itself, it wasn't possible to pass an SSL-encrypted connection through a proxy with a single script: you needed one for the SSL encapsulation, and another one for bypassing the proxy with the C HTTP method. See L and L for details. =head1 COPYRIGHT Copyright 2007-2014 Philippe 'BooK' Bruhat, All Rights Reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut