4 # a drop-in replacement for IO::Socket::INET that encapsulates
5 # data passed over a network with SSL.
7 # Current Code Shepherd: Steffen Ullrich <steffen at genua.de>
8 # Code Shepherd before: Peter Behroozi, <behrooz at fas.harvard.edu>
10 # The original version of this module was written by
11 # Marko Asplund, <marko.asplund at kronodoc.fi>, who drew from
12 # Crypt::SSLeay (Net::SSL) by Gisle Aas.
15 package IO::Socket::SSL;
20 use Errno qw( EAGAIN ETIMEDOUT );
24 # from openssl/ssl.h, should be better in Net::SSLeay
25 use constant SSL_SENT_SHUTDOWN => 1;
26 use constant SSL_RECEIVED_SHUTDOWN => 2;
28 # non-XS Versions of Scalar::Util will fail
30 eval { use Scalar::Util 'dualvar'; dualvar(0,'') };
31 die "You need the XS Version of Scalar::Util for dualvar() support"
35 use vars qw(@ISA $VERSION $DEBUG $SSL_ERROR $GLOBAL_CONTEXT_ARGS @EXPORT );
38 # These constants will be used in $! at return from SSL_connect,
39 # SSL_accept, generic_read and write, thus notifying the caller
40 # the usual way of problems. Like with EAGAIN, EINPROGRESS..
41 # these are especially important for non-blocking sockets
43 my $x = Net::SSLeay::ERROR_WANT_READ();
44 use constant SSL_WANT_READ => dualvar( \$x, 'SSL wants a read first' );
45 my $y = Net::SSLeay::ERROR_WANT_WRITE();
46 use constant SSL_WANT_WRITE => dualvar( \$y, 'SSL wants a write first' );
48 @EXPORT = qw( SSL_WANT_READ SSL_WANT_WRITE $SSL_ERROR GEN_DNS GEN_IPADD );
52 # Declare @ISA, $VERSION, $GLOBAL_CONTEXT_ARGS
53 @ISA = qw(IO::Socket::INET);
55 $GLOBAL_CONTEXT_ARGS = {};
57 #Make $DEBUG another name for $Net::SSLeay::trace
58 *DEBUG = \$Net::SSLeay::trace;
63 # Do Net::SSLeay initialization
64 Net::SSLeay::load_error_strings();
65 Net::SSLeay::SSLeay_add_ssl_algorithms();
66 Net::SSLeay::randomize();
70 $DEBUG>=shift or return; # check against debug level
71 my (undef,$file,$line) = caller;
73 $file = '...'.substr( $file,-17 ) if length($file)>20;
74 $msg = sprintf $msg,@_ if @_;
75 print STDERR "DEBUG: $file:$line: $msg\n";
79 # import some constants from Net::SSLeay or use hard-coded defaults
80 # if Net::SSLeay isn't recent enough to provide the constants
86 while ( my ($name,$value) = each %const ) {
88 *{$name} = UNIVERSAL::can( 'Net::SSLeay', $name ) || sub { $value };
91 # check if we have something to handle IDN
92 local $SIG{__DIE__}; local $SIG{__WARN__}; # be silent
93 if ( eval { require Net::IDN::Encode }) {
94 *{idn_to_ascii} = \&Net::IDN::Encode::domain_to_ascii;
95 } elsif ( eval { require Net::LibIDN }) {
96 *{idn_to_ascii} = \&Net::LibIDN::idn_to_ascii;
98 # default: croak if we really got an unencoded international domain
99 *{idn_to_ascii} = sub {
101 return $domain if $domain =~m{^[a-zA-Z0-9-_\.]+$};
102 croak "cannot handle international domains, please install Net::LibIDN or Net::IDN::Encode"
108 # inet4|inet6|debug will be handeled by myself, everything
109 # else will be handeld the Exporter way
116 require IO::Socket::INET;
117 @ISA = 'IO::Socket::INET'
118 } elsif ( /^inet6$/i ) {
119 require IO::Socket::INET6;
121 Socket6->import( 'inet_pton' );
122 @ISA = 'IO::Socket::INET6'
123 } elsif ( /^:?debug(\d+)/ ) {
130 @_ = ( $class,@export );
131 goto &Exporter::import;
134 # You might be expecting to find a new() subroutine here, but that is
135 # not how IO::Socket::INET works. All configuration gets performed in
136 # the calls to configure() and either connect() or accept().
138 #Call to configure occurs when a new socket is made using
139 #IO::Socket::INET. Returns false (empty list) on failure.
141 my ($self, $arg_hash) = @_;
142 return _invalid_object() unless($self);
144 # force initial blocking
145 # otherwise IO::Socket::SSL->new might return undef if the
146 # socket is nonblocking and it fails to connect immediatly
147 # for real nonblocking behavior one should create a nonblocking
148 # socket and later call connect explicitly
149 my $blocking = delete $arg_hash->{Blocking};
151 # because Net::HTTPS simple redefines blocking() to {} (e.g
152 # return undef) and IO::Socket::INET does not like this we
153 # set Blocking only explicitly if it was set
154 $arg_hash->{Blocking} = 1 if defined ($blocking);
156 $self->configure_SSL($arg_hash) || return;
158 $self->SUPER::configure($arg_hash)
159 || return $self->error("@ISA configuration failed");
161 $self->blocking(0) if defined $blocking && !$blocking;
166 my ($self, $arg_hash) = @_;
168 my $is_server = $arg_hash->{'SSL_server'} || $arg_hash->{'Listen'} || 0;
171 SSL_server => $is_server,
172 SSL_ca_file => 'certs/my-ca.pem',
173 SSL_ca_path => 'ca/',
174 SSL_use_cert => $is_server,
176 SSL_version => 'sslv23',
177 SSL_verify_mode => Net::SSLeay::VERIFY_NONE(),
178 SSL_verify_callback => undef,
179 SSL_verifycn_scheme => undef, # don't verify cn
180 SSL_verifycn_name => undef, # use from PeerAddr/PeerHost
183 # SSL_key_file and SSL_cert_file will only be set in defaults if
184 # SSL_key|SSL_key_file resp SSL_cert|SSL_cert_file are not set in
186 foreach my $k (qw( key cert )) {
187 next if exists $arg_hash->{ "SSL_${k}" };
188 next if exists $arg_hash->{ "SSL_${k}_file" };
189 $default_args{ "SSL_${k}_file" } = $is_server
190 ? "certs/server-${k}.pem"
191 : "certs/client-${k}.pem";
194 #Replace nonexistent entries with defaults
195 %$arg_hash = ( %default_args, %$GLOBAL_CONTEXT_ARGS, %$arg_hash );
197 #Avoid passing undef arguments to Net::SSLeay
198 defined($arg_hash->{$_}) or delete($arg_hash->{$_}) foreach (keys %$arg_hash);
200 #Handle CA paths properly if no CA file is specified
201 if ($arg_hash->{'SSL_ca_path'} ne '' and !(-f $arg_hash->{'SSL_ca_file'})) {
202 DEBUG(1, "CA file $arg_hash->{SSL_ca_file} not found, using CA path instead.\n" )
203 if $arg_hash->{SSL_ca_file};
204 $arg_hash->{'SSL_ca_file'} = '';
207 my $vcn_scheme = delete $arg_hash->{SSL_verifycn_scheme};
208 if ( $vcn_scheme && $vcn_scheme ne 'none' ) {
209 my $vcb = $arg_hash->{SSL_verify_callback};
210 $arg_hash->{SSL_verify_callback} = sub {
211 my ($ok,$ctx_store,$cert,$error) = @_;
212 $ok = $vcb->($ok,$ctx_store,$cert,$error) if $vcb;
214 my $depth = Net::SSLeay::X509_STORE_CTX_get_error_depth($ctx_store);
215 return $ok if $depth != 0;
217 # use SSL_peer_hostname or determine from PeerAddr
218 my $arg_hash = ${*$self}{_SSL_arguments};
219 my $host = $arg_hash->{SSL_verifycn_name};
220 if (not defined($host)) {
221 $host = ( $arg_hash->{PeerAddr} || $arg_hash->{PeerHost} );
222 $host =~s{:\w+$}{} if ! $host;
224 $host ||= ref($vcn_scheme) && $vcn_scheme->{callback} && 'unknown';
225 $host or return $self->error( "Cannot determine peer hostname for verification" );
228 my $x509 = Net::SSLeay::X509_STORE_CTX_get_current_cert($ctx_store);
229 my $rv = verify_hostname_of_cert( $host,$x509,$vcn_scheme );
230 # just do some code here against optimization because x509 has no
231 # increased reference and CRYPTO_add is not available from Net::SSLeay
232 DEBUG(99999,"don't to anything with $x509" );
237 ${*$self}{'_SSL_arguments'} = $arg_hash;
238 ${*$self}{'_SSL_ctx'} = IO::Socket::SSL::SSL_Context->new($arg_hash) || return;
239 ${*$self}{'_SSL_opened'} = 1 if $is_server;
246 my ($self,$ssl,$rv) = @_;
247 my $err = Net::SSLeay::get_error($ssl,$rv);
249 $err == Net::SSLeay::ERROR_WANT_READ() ? SSL_WANT_READ :
250 $err == Net::SSLeay::ERROR_WANT_WRITE() ? SSL_WANT_WRITE :
253 ${*$self}{'_SSL_last_err'} = $SSL_ERROR if ref($self);
258 #Call to connect occurs when a new client socket is made using
261 my $self = shift || return _invalid_object();
262 return $self if ${*$self}{'_SSL_opened'}; # already connected
264 if ( ! ${*$self}{'_SSL_opening'} ) {
265 # call SUPER::connect if the underlying socket is not connected
266 # if this fails this might not be an error (e.g. if $! = EINPROGRESS
267 # and socket is nonblocking this is normal), so keep any error
268 # handling to the client
269 DEBUG(2, 'socket not yet connected' );
270 $self->SUPER::connect(@_) || return;
271 DEBUG(2,'socket connected' );
273 return $self->connect_SSL;
279 my $args = @_>1 ? {@_}: $_[0]||{};
282 if ( ! ${*$self}{'_SSL_opening'} ) {
283 # start ssl connection
284 DEBUG(2,'ssl handshake not started' );
285 ${*$self}{'_SSL_opening'} = 1;
286 my $arg_hash = ${*$self}{'_SSL_arguments'};
288 my $fileno = ${*$self}{'_SSL_fileno'} = fileno($self);
289 return $self->error("Socket has no fileno") unless (defined $fileno);
291 $ctx = ${*$self}{'_SSL_ctx'}; # Reference to real context
292 $ssl = ${*$self}{'_SSL_object'} = Net::SSLeay::new($ctx->{context})
293 || return $self->error("SSL structure creation failed");
295 Net::SSLeay::set_fd($ssl, $fileno)
296 || return $self->error("SSL filehandle association failed");
298 if ( my $cl = $arg_hash->{SSL_cipher_list} ) {
299 Net::SSLeay::set_cipher_list($ssl, $cl )
300 || return $self->error("Failed to set SSL cipher list");
303 $arg_hash->{PeerAddr} || $self->_update_peer;
304 my $session = $ctx->session_cache( $arg_hash->{PeerAddr}, $arg_hash->{PeerPort} );
305 Net::SSLeay::set_session($ssl, $session) if ($session);
308 $ssl ||= ${*$self}{'_SSL_object'};
311 my $timeout = exists $args->{Timeout}
313 : ${*$self}{io_socket_timeout}; # from IO::Socket
314 if ( defined($timeout) && $timeout>0 && $self->blocking(0) ) {
315 DEBUG(2, "set socket to non-blocking to enforce timeout=$timeout" );
316 # timeout was given and socket was blocking
317 # enforce timeout with now non-blocking socket
319 # timeout does not apply because invalid or socket non-blocking
323 my $start = defined($timeout) && time();
325 #DEBUG( 'calling ssleay::connect' );
326 my $rv = Net::SSLeay::connect($ssl);
327 DEBUG( 3,"Net::SSLeay::connect -> $rv" );
329 unless ( $self->_set_rw_error( $ssl,$rv )) {
330 $self->error("SSL connect attempt failed with unknown error");
331 delete ${*$self}{'_SSL_opening'};
332 ${*$self}{'_SSL_opened'} = -1;
333 DEBUG(1, "fatal SSL error: $SSL_ERROR" );
334 return $self->fatal_ssl_error();
337 DEBUG(2,'ssl handshake in progress' );
338 # connect failed because handshake needs to be completed
339 # if socket was non-blocking or no timeout was given return with this error
340 return if ! defined($timeout);
342 # wait until socket is readable or writable
346 vec($vec,$self->fileno,1) = 1;
347 DEBUG(2, "waiting for fd to become ready: $SSL_ERROR" );
349 $SSL_ERROR == SSL_WANT_READ ? select( $vec,undef,undef,$timeout) :
350 $SSL_ERROR == SSL_WANT_WRITE ? select( undef,$vec,undef,$timeout) :
353 DEBUG(2,"handshake failed because no more time" );
357 DEBUG(2,"handshake failed because socket did not became ready" );
358 # failed because of timeout, return
360 delete ${*$self}{'_SSL_opening'};
361 ${*$self}{'_SSL_opened'} = -1;
362 $self->blocking(1); # was blocking before
366 # socket is ready, try non-blocking connect again after recomputing timeout
367 DEBUG(2,"socket ready, retrying connect" );
369 $timeout -= $now - $start;
373 } elsif ( $rv == 0 ) {
374 delete ${*$self}{'_SSL_opening'};
375 DEBUG(2,"connection failed - connect returned 0" );
376 $self->error("SSL connect attempt failed because of handshake problems" );
377 ${*$self}{'_SSL_opened'} = -1;
378 return $self->fatal_ssl_error();
382 DEBUG(2,'ssl handshake done' );
383 # ssl connect successful
384 delete ${*$self}{'_SSL_opening'};
385 ${*$self}{'_SSL_opened'}=1;
386 $self->blocking(1) if defined($timeout); # was blocking before
388 $ctx ||= ${*$self}{'_SSL_ctx'};
389 if ( $ctx->has_session_cache ) {
390 my $arg_hash = ${*$self}{'_SSL_arguments'};
391 $arg_hash->{PeerAddr} || $self->_update_peer;
392 my ($addr,$port) = ( $arg_hash->{PeerAddr}, $arg_hash->{PeerPort} );
393 my $session = $ctx->session_cache( $addr,$port );
394 $ctx->session_cache( $addr,$port, Net::SSLeay::get1_session($ssl) ) if !$session;
397 tie *{$self}, "IO::Socket::SSL::SSL_HANDLE", $self;
402 # called if PeerAddr is not set in ${*$self}{'_SSL_arguments'}
403 # this can be the case if start_SSL is called with a normal IO::Socket::INET
404 # so that PeerAddr|PeerPort are not set from args
407 my $arg_hash = ${*$self}{'_SSL_arguments'};
409 my ($port,$addr) = sockaddr_in( getpeername( $self ));
410 $arg_hash->{PeerAddr} = inet_ntoa( $addr );
411 $arg_hash->{PeerPort} = $port;
415 #Call to accept occurs when a new client connects to a server using
418 my $self = shift || return _invalid_object();
419 my $class = shift || 'IO::Socket::SSL';
421 my $socket = ${*$self}{'_SSL_opening'};
423 # underlying socket not done
424 DEBUG(2,'no socket yet' );
425 $socket = $self->SUPER::accept($class) || return;
426 DEBUG(2,'accept created normal socket '.$socket );
429 $self->accept_SSL($socket) || return;
430 DEBUG(2,'accept_SSL ok' );
432 return wantarray ? ($socket, getpeername($socket) ) : $socket;
437 my $socket = ( @_ && UNIVERSAL::isa( $_[0], 'IO::Handle' )) ? shift : $self;
438 my $args = @_>1 ? {@_}: $_[0]||{};
441 if ( ! ${*$self}{'_SSL_opening'} ) {
442 DEBUG(2,'starting sslifying' );
443 ${*$self}{'_SSL_opening'} = $socket;
444 my $arg_hash = ${*$self}{'_SSL_arguments'};
445 ${*$socket}{'_SSL_arguments'} = { %$arg_hash, SSL_server => 0 };
446 my $ctx = ${*$socket}{'_SSL_ctx'} = ${*$self}{'_SSL_ctx'};
448 my $fileno = ${*$socket}{'_SSL_fileno'} = fileno($socket);
449 return $socket->error("Socket has no fileno") unless (defined $fileno);
451 $ssl = ${*$socket}{'_SSL_object'} = Net::SSLeay::new($ctx->{context})
452 || return $socket->error("SSL structure creation failed");
454 Net::SSLeay::set_fd($ssl, $fileno)
455 || return $socket->error("SSL filehandle association failed");
457 if ( my $cl = $arg_hash->{SSL_cipher_list} ) {
458 Net::SSLeay::set_cipher_list($ssl, $cl )
459 || return $socket->error("Failed to set SSL cipher list");
463 $ssl ||= ${*$socket}{'_SSL_object'};
466 #DEBUG(2,'calling ssleay::accept' );
468 my $timeout = exists $args->{Timeout}
470 : ${*$self}{io_socket_timeout}; # from IO::Socket
471 if ( defined($timeout) && $timeout>0 && $socket->blocking(0) ) {
472 # timeout was given and socket was blocking
473 # enforce timeout with now non-blocking socket
475 # timeout does not apply because invalid or socket non-blocking
479 my $start = defined($timeout) && time();
481 my $rv = Net::SSLeay::accept($ssl);
482 DEBUG(3, "Net::SSLeay::accept -> $rv" );
484 unless ( $socket->_set_rw_error( $ssl,$rv )) {
485 $socket->error("SSL accept attempt failed with unknown error");
486 delete ${*$self}{'_SSL_opening'};
487 ${*$socket}{'_SSL_opened'} = -1;
488 return $socket->fatal_ssl_error();
491 # accept failed because handshake needs to be completed
492 # if socket was non-blocking or no timeout was given return with this error
493 return if ! defined($timeout);
495 # wait until socket is readable or writable
499 vec($vec,$socket->fileno,1) = 1;
501 $SSL_ERROR == SSL_WANT_READ ? select( $vec,undef,undef,$timeout) :
502 $SSL_ERROR == SSL_WANT_WRITE ? select( undef,$vec,undef,$timeout) :
508 # failed because of timeout, return
510 delete ${*$self}{'_SSL_opening'};
511 ${*$socket}{'_SSL_opened'} = -1;
512 $socket->blocking(1); # was blocking before
516 # socket is ready, try non-blocking accept again after recomputing timeout
518 $timeout -= $now - $start;
522 } elsif ( $rv == 0 ) {
523 $socket->error("SSL connect accept failed because of handshake problems" );
524 delete ${*$self}{'_SSL_opening'};
525 ${*$socket}{'_SSL_opened'} = -1;
526 return $socket->fatal_ssl_error();
530 DEBUG(2,'handshake done, socket ready' );
532 delete ${*$self}{'_SSL_opening'};
533 ${*$socket}{'_SSL_opened'} = 1;
534 $socket->blocking(1) if defined($timeout); # was blocking before
536 tie *{$socket}, "IO::Socket::SSL::SSL_HANDLE", $socket;
542 ####### I/O subroutines ########################
545 my ($self, $read_func, undef, $length, $offset) = @_;
546 my $ssl = $self->_get_ssl_object || return;
550 my $data = $read_func->($ssl, $length);
551 if ( !defined($data)) {
552 $self->_set_rw_error( $ssl,-1 ) || $self->error("SSL read error");
556 $length = length($data);
557 $$buffer = '' if !defined $$buffer;
559 if ($offset>length($$buffer)) {
560 $$buffer.="\0" x ($offset-length($$buffer)); #mimic behavior of read
563 substr($$buffer, $offset, length($$buffer), $data);
569 return $self->generic_read(
570 $self->blocking ? \&Net::SSLeay::ssl_read_all : \&Net::SSLeay::read,
575 # contrary to the behavior of read sysread can read partial data
578 return $self->generic_read( \&Net::SSLeay::read, @_ );
583 if (Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x0090601f) {
584 return $self->generic_read(\&Net::SSLeay::peek, @_);
586 return $self->error("SSL_peek not supported for OpenSSL < v0.9.6a");
592 my ($self, $write_all, undef, $length, $offset) = @_;
594 my $ssl = $self->_get_ssl_object || return;
597 my $buf_len = length($$buffer);
598 $length ||= $buf_len;
600 return $self->error("Invalid offset for SSL write") if ($offset>$buf_len);
601 return 0 if ($offset == $buf_len);
606 my $data = $length < $buf_len-$offset ? substr($$buffer, $offset, $length) : $$buffer;
607 $written = Net::SSLeay::ssl_write_all($ssl, $data);
609 $written = Net::SSLeay::write_partial( $ssl,$offset,$length,$$buffer );
611 $written = undef if $written < 0; # Net::SSLeay::write returns -1 not undef on error
612 if ( !defined($written) ) {
613 $self->_set_rw_error( $ssl,-1 )
614 || $self->error("SSL write error");
621 # if socket is blocking write() should return only on error or
622 # if all data are written
625 return $self->generic_write( scalar($self->blocking),@_ );
628 # contrary to write syswrite() returns already if only
629 # a part of the data is written
632 return $self->generic_write( 0,@_ );
637 my $string = join(($, or ''), @_, ($\ or ''));
638 return $self->write( $string );
642 my ($self,$format) = (shift,shift);
643 return $self->write(sprintf($format, @_));
647 my ($self, $buffer) = (shift, undef);
648 return $buffer if $self->read($buffer, 1, 0);
653 my $ssl = $self->_get_ssl_object || return;
656 my ($buf,$err) = Net::SSLeay::ssl_read_all($ssl);
657 return $self->error( "SSL read error" ) if $err;
658 if ( !defined($/) ) {
660 } elsif ( ref($/) ) {
662 die "bad value in ref \$/: $size" unless $size>0;
663 return $buf=~m{\G(.{1,$size})}g;
664 } elsif ( $/ eq '' ) {
665 return $buf =~m{\G(.*\n\n+|.+)}g;
667 return $buf =~m{\G(.*$/|.+)}g;
671 if ( !defined($/) ) {
672 my ($buf,$err) = Net::SSLeay::ssl_read_all($ssl);
673 return $self->error( "SSL read error" ) if $err;
675 } elsif ( ref($/) ) {
677 die "bad value in ref \$/: $size" unless $size>0;
678 my ($buf,$err) = Net::SSLeay::ssl_read_all($ssl,$size);
679 return $self->error( "SSL read error" ) if $err;
681 } elsif ( $/ ne '' ) {
682 my $line = Net::SSLeay::ssl_read_until($ssl,$/);
683 return $self->error( "SSL read error" ) if $line eq '';
687 # ^.*?\n\n+, need peek to find all \n at the end
688 die "empty \$/ is not supported if I don't have peek"
689 if Net::SSLeay::OPENSSL_VERSION_NUMBER() < 0x0090601f;
691 # find first occurence of \n\n
695 defined( Net::SSLeay::peek($ssl,1)) || last; # peek more, can block
696 my $pending = Net::SSLeay::pending($ssl);
697 $buf .= Net::SSLeay::peek( $ssl,$pending ); # will not block
699 my $pos = index( $buf,"\n\n");
700 next if $pos<0; # newlines not found
701 $eon = $pos+2; # pos after second newline
703 # $eon >= 2 == bytes incl last known \n
704 while ( index( $buf,"\n",$eon ) == $eon ) {
705 # the next char ist \n too
708 last if $eon < length($buf); # found last \n before end of buf
712 # readed peeked data until $eon from $ssl
713 return Net::SSLeay::ssl_read_all( $ssl,$eon );
716 # return all what we have
717 if ( my $l = length($buf)) {
718 return Net::SSLeay::ssl_read_all( $ssl,$l );
720 return $self->error( "SSL read error" );
727 my $self = shift || return _invalid_object();
728 my $close_args = (ref($_[0]) eq 'HASH') ? $_[0] : {@_};
730 return if ! $self->stop_SSL(
731 SSL_fast_shutdown => 1,
733 _SSL_ioclass_downgrade => 0,
736 if ( ! $close_args->{_SSL_in_DESTROY} ) {
738 return $self->SUPER::close;
744 my $self = shift || return _invalid_object();
745 my $stop_args = (ref($_[0]) eq 'HASH') ? $_[0] : {@_};
746 return $self->error("SSL object already closed")
747 unless (${*$self}{'_SSL_opened'} == 1);
749 if (my $ssl = ${*$self}{'_SSL_object'}) {
751 if ( $stop_args->{SSL_no_shutdown} ) {
754 my $fast = $stop_args->{SSL_fast_shutdown};
755 my $status = Net::SSLeay::get_shutdown($ssl);
756 if ( $status == SSL_RECEIVED_SHUTDOWN
757 || ( $status != 0 && $fast )) {
761 # need to initiate/continue shutdown
762 local $SIG{PIPE} = sub{};
764 my $rv = Net::SSLeay::shutdown($ssl);
766 # non-blocking socket?
767 $self->_set_rw_error( $ssl,$rv );
771 || ( $rv == 0 && $fast )) {
776 # shutdown partly finished (e.g. one direction)
783 return if ! $shutdown_done;
784 Net::SSLeay::free($ssl);
785 delete ${*$self}{_SSL_object};
788 if ($stop_args->{'SSL_ctx_free'}) {
789 my $ctx = delete ${*$self}{'_SSL_ctx'};
790 $ctx && $ctx->DESTROY();
793 if (my $cert = delete ${*$self}{'_SSL_certificate'}) {
794 Net::SSLeay::X509_free($cert);
797 ${*$self}{'_SSL_opened'} = 0;
799 if ( ! $stop_args->{_SSL_in_DESTROY} ) {
801 my $downgrade = $stop_args->{_SSL_ioclass_downgrade};
802 if ( $downgrade || ! defined $downgrade ) {
803 # rebless to original class from start_SSL
804 if ( my $orig_class = delete ${*$self}{'_SSL_ioclass_upgraded'} ) {
805 bless $self,$orig_class;
807 # FIXME: if original class was tied too we need to restore the tie
809 # remove all _SSL related from *$self
810 my @sslkeys = grep { m{^_?SSL_} } keys %{*$self};
811 delete @{*$self}{@sslkeys} if @sslkeys;
821 $self->close(SSL_no_shutdown => 1) if (${*$self}{'_SSL_opened'} == 1);
822 delete(${*$self}{'_SSL_ctx'});
828 my $fn = ${*$self}{'_SSL_fileno'};
829 return defined($fn) ? $fn : $self->SUPER::fileno();
833 ####### IO::Socket::SSL specific functions #######
834 # _get_ssl_object is for internal use ONLY!
835 sub _get_ssl_object {
837 my $ssl = ${*$self}{'_SSL_object'};
838 return IO::Socket::SSL->error("Undefined SSL object") unless($ssl);
842 # default error for undefined arguments
843 sub _invalid_object {
844 return IO::Socket::SSL->error("Undefined IO::Socket::SSL object");
849 my $ssl = shift()->_get_ssl_object || return;
850 return Net::SSLeay::pending($ssl);
854 my ($class,$socket) = (shift,shift);
855 return $class->error("Not a socket") unless(ref($socket));
856 my $arg_hash = (ref($_[0]) eq 'HASH') ? $_[0] : {@_};
857 my %to = exists $arg_hash->{Timeout} ? ( Timeout => delete $arg_hash->{Timeout} ) :();
858 my $original_class = ref($socket);
859 my $original_fileno = (UNIVERSAL::can($socket, "fileno"))
860 ? $socket->fileno : CORE::fileno($socket);
861 return $class->error("Socket has no fileno") unless defined $original_fileno;
863 bless $socket, $class;
864 $socket->configure_SSL($arg_hash) or bless($socket, $original_class) && return;
866 ${*$socket}{'_SSL_fileno'} = $original_fileno;
867 ${*$socket}{'_SSL_ioclass_upgraded'} = $original_class;
869 my $start_handshake = $arg_hash->{SSL_startHandshake};
870 if ( ! defined($start_handshake) || $start_handshake ) {
871 # if we have no callback force blocking mode
872 DEBUG(2, "start handshake" );
873 my $blocking = $socket->blocking(1);
874 my $result = ${*$socket}{'_SSL_arguments'}{SSL_server}
875 ? $socket->accept_SSL(%to)
876 : $socket->connect_SSL(%to);
877 $socket->blocking(0) if !$blocking;
878 return $result ? $socket : (bless($socket, $original_class) && ());
880 DEBUG(2, "dont start handshake: $socket" );
881 return $socket; # just return upgraded socket
887 my ($class, $fd) = (shift,shift);
888 # Check for accidental inclusion of MODE in the argument list
889 if (length($_[0]) < 4) {
890 (my $mode = $_[0]) =~ tr/+<>//d;
891 shift unless length($mode);
893 my $handle = IO::Socket::INET->new_from_fd($fd, '+<')
894 || return($class->error("Could not create socket from file descriptor."));
896 # Annoying workaround for Perl 5.6.1 and below:
897 $handle = IO::Socket::INET->new_from_fd($handle, '+<');
899 return $class->start_SSL($handle, @_);
903 sub dump_peer_certificate {
904 my $ssl = shift()->_get_ssl_object || return;
905 return Net::SSLeay::dump_peer_certificate($ssl);
910 issuer => sub { Net::SSLeay::X509_NAME_oneline( Net::SSLeay::X509_get_issuer_name( shift )) },
911 subject => sub { Net::SSLeay::X509_NAME_oneline( Net::SSLeay::X509_get_subject_name( shift )) },
913 if ( $Net::SSLeay::VERSION >= 1.30 ) {
914 # I think X509_NAME_get_text_by_NID got added in 1.30
915 $dispatcher{commonName} = sub {
916 my $cn = Net::SSLeay::X509_NAME_get_text_by_NID(
917 Net::SSLeay::X509_get_subject_name( shift ), NID_CommonName);
918 $cn =~s{\0$}{}; # work around Bug in Net::SSLeay <1.33
922 $dispatcher{commonName} = sub {
923 croak "you need at least Net::SSLeay version 1.30 for getting commonName"
927 if ( $Net::SSLeay::VERSION >= 1.33 ) {
928 # X509_get_subjectAltNames did not really work before
929 $dispatcher{subjectAltNames} = sub { Net::SSLeay::X509_get_subjectAltNames( shift ) };
931 $dispatcher{subjectAltNames} = sub {
932 croak "you need at least Net::SSLeay version 1.33 for getting subjectAltNames"
937 $dispatcher{authority} = $dispatcher{issuer};
938 $dispatcher{owner} = $dispatcher{subject};
939 $dispatcher{cn} = $dispatcher{commonName};
941 sub peer_certificate {
942 my ($self, $field) = @_;
943 my $ssl = $self->_get_ssl_object or return;
945 my $cert = ${*$self}{_SSL_certificate}
946 ||= Net::SSLeay::get_peer_certificate($ssl)
947 or return $self->error("Could not retrieve peer certificate");
950 my $sub = $dispatcher{$field} or croak
951 "invalid argument for peer_certificate, valid are: ".join( " ",keys %dispatcher ).
952 "\nMaybe you need to upgrade your Net::SSLeay";
953 return $sub->($cert);
959 # known schemes, possible attributes are:
960 # - wildcards_in_alt (0, 'leftmost', 'anywhere')
961 # - wildcards_in_cn (0, 'leftmost', 'anywhere')
962 # - check_cn (0, 'always', 'when_only')
967 wildcards_in_cn => 0,
968 wildcards_in_alt => 'leftmost',
969 check_cn => 'always',
973 wildcards_in_cn => 0,
974 wildcards_in_alt => 'anywhere',
975 check_cn => 'when_only',
978 # This is just a dumb guess
979 # RFC3207 itself just says, that the client should expect the
980 # domain name of the server in the certificate. It doesn't say
981 # anything about wildcards, so I forbid them. It doesn't say
982 # anything about alt names, but other documents show, that alt
983 # names should be possible. The check_cn value again is a guess.
986 wildcards_in_cn => 0,
987 wildcards_in_alt => 0,
990 none => {}, # do not check
993 $scheme{www} = $scheme{http}; # alias
994 $scheme{xmpp} = $scheme{http}; # rfc 3920
995 $scheme{pop3} = $scheme{ldap}; # rfc 2595
996 $scheme{imap} = $scheme{ldap}; # rfc 2595
997 $scheme{acap} = $scheme{ldap}; # rfc 2595
998 $scheme{nntp} = $scheme{ldap}; # rfc 4642
1000 # function to verify the hostname
1002 # as every application protocol has its own rules to do this
1003 # we provide some default rules as well as a user-defined
1006 sub verify_hostname_of_cert {
1007 my $identity = shift;
1009 my $scheme = shift || 'none';
1010 if ( ! ref($scheme) ) {
1011 DEBUG(3, "scheme=$scheme cert=$cert" );
1012 $scheme = $scheme{$scheme} or croak "scheme $scheme not defined";
1015 # get data from certificate
1016 my $commonName = $dispatcher{cn}->($cert);
1017 my @altNames = $dispatcher{subjectAltNames}->($cert);
1018 DEBUG(3,"identity=$identity cn=$commonName alt=@altNames" );
1020 if ( my $sub = $scheme->{callback} ) {
1021 # use custom callback
1022 return $sub->($identity,$commonName,@altNames);
1025 # is the given hostname an IP address? Then we have to convert to network byte order [RFC791][RFC2460]
1028 if ( $identity =~m{:} ) {
1029 # no IPv4 or hostname have ':' in it, try IPv6.
1030 # make sure that Socket6 was loaded properly
1031 UNIVERSAL::can( __PACKAGE__, 'inet_pton' ) or croak
1032 q[Looks like IPv6 address, make sure that Socket6 is loaded or make "use IO::Socket::SSL 'inet6'];
1033 $ip6 = inet_pton( $identity ) or croak "'$identity' is not IPv6, but neither IPv4 nor hostname";
1034 } elsif ( $identity =~m{^\d+\.\d+\.\d+\.\d+$} ) {
1035 # definitly no hostname, try IPv4
1036 $ip4 = inet_aton( $identity ) or croak "'$identity' is not IPv4, but neither IPv6 nor hostname";
1039 if ( $identity !~m{^[a-zA-Z0-9-_\.]+$} ) {
1040 $identity = idn_to_ascii($identity) or
1041 croak "Warning: Given name '$identity' could not be converted to IDNA!";
1045 # do the actual verification
1046 my $check_name = sub {
1047 my ($name,$identity,$wtyp) = @_;
1051 # we accept only a single wildcard and only for a single part of the FQDN
1052 # e.g *.example.org does match www.example.org but not bla.www.example.org
1053 # The RFCs are in this regard unspecific but we don't want to have to
1054 # deal with certificates like *.com, *.co.uk or even *
1055 # see also http://nils.toedtmann.net/pub/subjectAltName.txt
1056 if ( $wtyp eq 'anywhere' and $name =~m{^([\w\-]*)\*(.+)} ) {
1057 $pattern = qr{^\Q$1\E[\w\-]*\Q$2\E$}i;
1058 } elsif ( $wtyp eq 'leftmost' and $name =~m{^\*(\..+)$} ) {
1059 $pattern = qr{^[\w\-]*\Q$1\E$}i;
1061 $pattern = qr{^\Q$name}i;
1063 return $identity =~ $pattern;
1066 my $alt_dnsNames = 0;
1068 my ($type, $name) = splice (@altNames, 0, 2);
1069 if ( $type == GEN_IPADD ) {
1070 # exakt match needed for IP
1071 # $name is already packed format (inet_xton)
1073 $ip6 ? $ip6 eq $name :
1074 $ip4 ? $ip4 eq $name :
1077 } elsif ( $type == GEN_DNS ) {
1078 $name =~s/\s+$//; $name =~s/^\s+//;
1080 $check_name->($name,$identity,$scheme->{wildcards_in_alt})
1085 if ( $scheme->{check_cn} eq 'always' or
1086 $scheme->{check_cn} eq 'when_only' and !$alt_dnsNames) {
1087 $check_name->($commonName,$identity,$scheme->{wildcars_in_cn})
1091 return 0; # no match
1095 sub verify_hostname {
1098 my $cert = $self->peer_certificate;
1099 return verify_hostname_of_cert( $host,$cert,@_ );
1104 my $ssl = shift()->_get_ssl_object || return;
1105 return Net::SSLeay::get_cipher($ssl);
1110 return ((ref($self) ? ${*$self}{'_SSL_last_err'} : $SSL_ERROR) or '');
1113 sub fatal_ssl_error {
1115 my $error_trap = ${*$self}{'_SSL_arguments'}->{'SSL_error_trap'};
1117 if (defined $error_trap and ref($error_trap) eq 'CODE') {
1118 $error_trap->($self, $self->errstr()."\n".$self->get_ssleay_error());
1125 sub get_ssleay_error {
1126 #Net::SSLeay will print out the errors itself unless we explicitly
1127 #undefine $Net::SSLeay::trace while running print_errs()
1128 local $Net::SSLeay::trace;
1129 return Net::SSLeay::print_errs('SSL error: ') || '';
1133 my ($self, $error, $destroy_socket) = @_;
1134 $error .= Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
1135 DEBUG(2, $error."\n".$self->get_ssleay_error());
1136 $SSL_ERROR = dualvar( -1, $error );
1137 ${*$self}{'_SSL_last_err'} = $SSL_ERROR if (ref($self));
1143 my $self = shift || return;
1144 $self->close(_SSL_in_DESTROY => 1, SSL_no_shutdown => 1)
1145 if (${*$self}{'_SSL_opened'} == 1);
1146 delete(${*$self}{'_SSL_ctx'});
1150 #######Extra Backwards Compatibility Functionality#######
1151 sub socket_to_SSL { IO::Socket::SSL->start_SSL(@_); }
1152 sub socketToSSL { IO::Socket::SSL->start_SSL(@_); }
1154 sub issuer_name { return(shift()->peer_certificate("issuer")) }
1155 sub subject_name { return(shift()->peer_certificate("subject")) }
1156 sub get_peer_certificate { return shift() }
1159 return($GLOBAL_CONTEXT_ARGS = (ref($_[0]) eq 'HASH') ? $_[0] : {@_});
1162 sub set_default_context {
1163 $GLOBAL_CONTEXT_ARGS->{'SSL_reuse_ctx'} = shift;
1166 sub set_default_session_cache {
1167 $GLOBAL_CONTEXT_ARGS->{SSL_session_cache} = shift;
1170 sub set_ctx_defaults {
1172 while ( my ($k,$v) = each %args ) {
1173 $k =~s{^(SSL_)?}{SSL_};
1174 $GLOBAL_CONTEXT_ARGS->{$k} = $v;
1181 return IO::Handle::opened($self) && ${*$self}{'_SSL_opened'};
1186 return ${*$self}{'_SSL_opening'};
1189 sub want_read { shift->errstr == SSL_WANT_READ }
1190 sub want_write { shift->errstr == SSL_WANT_WRITE }
1193 #Redundant IO::Handle functionality
1194 sub getline { return(scalar shift->readline()) }
1196 return(shift->readline()) if wantarray();
1197 croak("Use of getlines() not allowed in scalar context");
1200 #Useless IO::Handle functionality
1201 sub truncate { croak("Use of truncate() not allowed with SSL") }
1202 sub stat { croak("Use of stat() not allowed with SSL" ) }
1203 sub setbuf { croak("Use of setbuf() not allowed with SSL" ) }
1204 sub setvbuf { croak("Use of setvbuf() not allowed with SSL" ) }
1205 sub fdopen { croak("Use of fdopen() not allowed with SSL" ) }
1207 #Unsupported socket functionality
1208 sub ungetc { croak("Use of ungetc() not implemented in IO::Socket::SSL") }
1209 sub send { croak("Use of send() not implemented in IO::Socket::SSL; use print/printf/syswrite instead") }
1210 sub recv { croak("Use of recv() not implemented in IO::Socket::SSL; use read/sysread instead") }
1212 package IO::Socket::SSL::SSL_HANDLE;
1214 use vars qw($HAVE_WEAKREF);
1218 local ($@, $SIG{__DIE__});
1220 #Use Scalar::Util or WeakRef if possible:
1221 eval "use Scalar::Util qw(weaken isweak); 1" or
1223 $HAVE_WEAKREF = $@ ? 0 : 1;
1228 my ($class, $handle) = @_;
1229 weaken($handle) if $HAVE_WEAKREF;
1230 bless \$handle, $class;
1233 sub READ { ${shift()}->sysread(@_) }
1234 sub READLINE { ${shift()}->readline(@_) }
1235 sub GETC { ${shift()}->getc(@_) }
1237 sub PRINT { ${shift()}->print(@_) }
1238 sub PRINTF { ${shift()}->printf(@_) }
1239 sub WRITE { ${shift()}->syswrite(@_) }
1241 sub FILENO { ${shift()}->fileno(@_) }
1243 sub TELL { $! = EBADF; return -1 }
1244 sub BINMODE { return 0 } # not perfect, but better than not implementing the method
1246 sub CLOSE { #<---- Do not change this function!
1253 package IO::Socket::SSL::SSL_Context;
1256 my %CTX_CREATED_IN_THIS_THREAD;
1257 *DEBUG = *IO::Socket::SSL::DEBUG;
1259 # should be better taken from Net::SSLeay, but they are not (yet) defined there
1260 use constant SSL_MODE_ENABLE_PARTIAL_WRITE => 1;
1261 use constant SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER => 2;
1264 # Note that the final object will actually be a reference to the scalar
1265 # (C-style pointer) returned by Net::SSLeay::CTX_*_new() so that
1266 # it can be blessed.
1269 #DEBUG( "$class @_" );
1270 my $arg_hash = (ref($_[0]) eq 'HASH') ? $_[0] : {@_};
1272 my $ctx_object = $arg_hash->{'SSL_reuse_ctx'};
1274 return $ctx_object if ($ctx_object->isa('IO::Socket::SSL::SSL_Context') and
1275 $ctx_object->{context});
1277 # The following "double entendre" applies only if someone passed
1278 # in an IO::Socket::SSL object instead of an actual context.
1279 return $ctx_object if ($ctx_object = ${*$ctx_object}{'_SSL_ctx'});
1283 foreach ($arg_hash->{'SSL_version'}) {
1284 $ctx = /^sslv2$/i ? Net::SSLeay::CTX_v2_new() :
1285 /^sslv3$/i ? Net::SSLeay::CTX_v3_new() :
1286 /^tlsv1$/i ? Net::SSLeay::CTX_tlsv1_new() :
1287 Net::SSLeay::CTX_new();
1290 $ctx || return IO::Socket::SSL->error("SSL Context init failed");
1292 Net::SSLeay::CTX_set_options($ctx, Net::SSLeay::OP_ALL());
1294 # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER makes syswrite return if at least one
1295 # buffer was written and not block for the rest
1296 # SSL_MODE_ENABLE_PARTIAL_WRITE can be necessary for non-blocking because we
1297 # cannot guarantee, that the location of the buffer stays constant
1298 Net::SSLeay::CTX_set_mode( $ctx,
1299 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|SSL_MODE_ENABLE_PARTIAL_WRITE);
1302 my $verify_mode = $arg_hash->{SSL_verify_mode};
1303 unless ($verify_mode == Net::SSLeay::VERIFY_NONE()) {
1304 Net::SSLeay::CTX_load_verify_locations(
1305 $ctx, $arg_hash->{SSL_ca_file},$arg_hash->{SSL_ca_path}
1306 ) || return IO::Socket::SSL->error("Invalid certificate authority locations");
1309 if ($arg_hash->{'SSL_check_crl'}) {
1310 if (Net::SSLeay::OPENSSL_VERSION_NUMBER() >= 0x0090702f) {
1311 Net::SSLeay::X509_STORE_set_flags(
1312 Net::SSLeay::CTX_get_cert_store($ctx),
1313 Net::SSLeay::X509_V_FLAG_CRL_CHECK()
1316 return IO::Socket::SSL->error("CRL not supported for OpenSSL < v0.9.7b");
1320 if ($arg_hash->{'SSL_server'} || $arg_hash->{'SSL_use_cert'}) {
1321 my $filetype = Net::SSLeay::FILETYPE_PEM();
1323 if ($arg_hash->{'SSL_passwd_cb'}) {
1324 Net::SSLeay::CTX_set_default_passwd_cb($ctx, $arg_hash->{'SSL_passwd_cb'});
1327 if ( my $pkey= $arg_hash->{SSL_key} ) {
1328 # binary, e.g. EVP_PKEY*
1329 Net::SSLeay::CTX_use_PrivateKey($ctx, $pkey)
1330 || return IO::Socket::SSL->error("Failed to use Private Key");
1331 } elsif ( my $f = $arg_hash->{SSL_key_file} ) {
1332 Net::SSLeay::CTX_use_PrivateKey_file($ctx, $f, $filetype)
1333 || return IO::Socket::SSL->error("Failed to open Private Key");
1336 if ( my $x509 = $arg_hash->{SSL_cert} ) {
1337 # binary, e.g. X509*
1338 # we habe either a single certificate or a list with
1339 # a chain of certificates
1340 my @x509 = ref($x509) eq 'ARRAY' ? @$x509: ($x509);
1341 my $cert = shift @x509;
1342 Net::SSLeay::CTX_use_certificate( $ctx,$cert )
1343 || return IO::Socket::SSL->error("Failed to use Certificate");
1344 foreach my $ca (@x509) {
1345 Net::SSLeay::CTX_add_extra_chain_cert( $ctx,$ca )
1346 || return IO::Socket::SSL->error("Failed to use Certificate");
1348 } elsif ( my $f = $arg_hash->{SSL_cert_file} ) {
1349 Net::SSLeay::CTX_use_certificate_chain_file($ctx, $f)
1350 || return IO::Socket::SSL->error("Failed to open Certificate");
1353 if ( my $dh = $arg_hash->{SSL_dh} ) {
1355 Net::SSLeay::CTX_set_tmp_dh( $ctx,$dh )
1356 || return IO::Socket::SSL->error( "Failed to set DH from SSL_dh" );
1357 } elsif ( my $f = $arg_hash->{SSL_dh_file} ) {
1358 my $bio = Net::SSLeay::BIO_new_file( $f,'r' )
1359 || return IO::Socket::SSL->error( "Failed to open DH file $f" );
1360 my $dh = Net::SSLeay::PEM_read_bio_DHparams($bio);
1361 Net::SSLeay::BIO_free($bio);
1362 $dh || return IO::Socket::SSL->error( "Failed to read PEM for DH from $f - wrong format?" );
1363 my $rv = Net::SSLeay::CTX_set_tmp_dh( $ctx,$dh );
1364 Net::SSLeay::DH_free( $dh );
1365 $rv || return IO::Socket::SSL->error( "Failed to set DH from $f" );
1369 my $verify_cb = $arg_hash->{SSL_verify_callback};
1370 my $verify_callback = $verify_cb && sub {
1371 my ($ok, $ctx_store) = @_;
1374 $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($ctx_store);
1375 $error = Net::SSLeay::X509_STORE_CTX_get_error($ctx_store);
1376 $cert &&= Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_issuer_name($cert)).
1377 Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_subject_name($cert));
1378 $error &&= Net::SSLeay::ERR_error_string($error);
1380 DEBUG(3, "ok=$ok cert=$cert" );
1381 return $verify_cb->($ok, $ctx_store, $cert, $error);
1384 Net::SSLeay::CTX_set_verify($ctx, $verify_mode, $verify_callback);
1386 $ctx_object = { context => $ctx };
1387 DEBUG(3, "new ctx $ctx" );
1388 $CTX_CREATED_IN_THIS_THREAD{$ctx} = 1;
1390 if ( my $cache = $arg_hash->{SSL_session_cache} ) {
1391 # use predefined cache
1392 $ctx_object->{session_cache} = $cache
1393 } elsif ( my $size = $arg_hash->{SSL_session_cache_size}) {
1394 return IO::Socket::SSL->error("Session caches not supported for Net::SSLeay < v1.26")
1395 if $Net::SSLeay::VERSION < 1.26;
1396 $ctx_object->{session_cache} = IO::Socket::SSL::Session_Cache->new( $size );
1399 return bless $ctx_object, $class;
1405 my $cache = $ctx->{'session_cache'} || return;
1406 my ($addr,$port,$session) = @_;
1407 my $key = "$addr:$port";
1408 return defined($session)
1409 ? $cache->add_session($key, $session)
1410 : $cache->get_session($key);
1413 sub has_session_cache {
1414 return defined shift->{session_cache};
1418 sub CLONE { %CTX_CREATED_IN_THIS_THREAD = (); }
1421 if ( my $ctx = $self->{context} ) {
1422 DEBUG( 3,"free ctx $ctx open=".join( " ",keys %CTX_CREATED_IN_THIS_THREAD ));
1423 if ( %CTX_CREATED_IN_THIS_THREAD and
1424 delete $CTX_CREATED_IN_THIS_THREAD{$ctx} ) {
1425 DEBUG( 3,"OK free ctx $ctx" );
1426 Net::SSLeay::CTX_free($ctx);
1429 delete(@{$self}{'context','session_cache'});
1432 package IO::Socket::SSL::Session_Cache;
1436 my ($class, $size) = @_;
1438 return bless { _maxsize => $size }, $class;
1443 my ($self, $key) = @_;
1444 my $session = $self->{$key} || return;
1445 return $session->{session} if ($self->{'_head'} eq $session);
1446 $session->{prev}->{next} = $session->{next};
1447 $session->{next}->{prev} = $session->{prev};
1448 $session->{next} = $self->{'_head'};
1449 $session->{prev} = $self->{'_head'}->{prev};
1450 $self->{'_head'}->{prev} = $self->{'_head'}->{prev}->{next} = $session;
1451 $self->{'_head'} = $session;
1452 return $session->{session};
1456 my ($self, $key, $val) = @_;
1457 return if ($key eq '_maxsize' or $key eq '_head');
1459 if ((keys %$self) > $self->{'_maxsize'} + 1) {
1460 my $last = $self->{'_head'}->{prev};
1461 Net::SSLeay::SESSION_free($last->{session});
1462 delete($self->{$last->{key}});
1463 $self->{'_head'}->{prev} = $self->{'_head'}->{prev}->{prev};
1464 delete($self->{'_head'}) if ($self->{'_maxsize'} == 1);
1467 my $session = $self->{$key} = { session => $val, key => $key };
1469 if ($self->{'_head'}) {
1470 $session->{next} = $self->{'_head'};
1471 $session->{prev} = $self->{'_head'}->{prev};
1472 $self->{'_head'}->{prev}->{next} = $session;
1473 $self->{'_head'}->{prev} = $session;
1475 $session->{next} = $session->{prev} = $session;
1477 $self->{'_head'} = $session;
1483 delete(@{$self}{'_head','_maxsize'});
1484 foreach my $key (keys %$self) {
1485 Net::SSLeay::SESSION_free($self->{$key}->{session});
1495 IO::Socket::SSL -- Nearly transparent SSL encapsulation for IO::Socket::INET.
1500 use IO::Socket::SSL;
1502 my $client = IO::Socket::SSL->new("www.example.com:https")
1503 || warn "I encountered a problem: ".IO::Socket::SSL::errstr();
1504 $client->verify_hostname( 'www.example.com','http' )
1505 || die "hostname verification failed";
1507 print $client "GET / HTTP/1.0\r\n\r\n";
1513 This module is a true drop-in replacement for IO::Socket::INET that uses
1514 SSL to encrypt data before it is transferred to a remote server or
1515 client. IO::Socket::SSL supports all the extra features that one needs
1516 to write a full-featured SSL client or server application: multiple SSL contexts,
1517 cipher selection, certificate verification, and SSL version selection. As an
1518 extra bonus, it works perfectly with mod_perl.
1520 If you have never used SSL before, you should read the appendix labelled 'Using SSL'
1521 before attempting to use this module.
1523 If you have used this module before, read on, as versions 0.93 and above
1524 have several changes from the previous IO::Socket::SSL versions (especially
1525 see the note about return values).
1527 If you are using non-blocking sockets read on, as version 0.98 added better
1528 support for non-blocking.
1530 If you are trying to use it with threads see the BUGS section.
1534 IO::Socket::SSL inherits its methods from IO::Socket::INET, overriding them
1535 as necessary. If there is an SSL error, the method or operation will return an
1536 empty list (false in all contexts). The methods that have changed from the
1537 perspective of the user are re-documented here:
1543 Creates a new IO::Socket::SSL object. You may use all the friendly options
1544 that came bundled with IO::Socket::INET, plus (optionally) the ones that follow:
1550 Sets the version of the SSL protocol used to transmit data. The default is SSLv2/3,
1551 which auto-negotiates between SSLv2 and SSLv3. You may specify 'SSLv2', 'SSLv3', or
1552 'TLSv1' (case-insensitive) if you do not want this behavior.
1554 =item SSL_cipher_list
1556 If this option is set the cipher list for the connection will be set to the
1557 given value, e.g. something like 'ALL:!LOW:!EXP:!ADH'. Look into the OpenSSL
1558 documentation (L<http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS>)
1560 If this option is not used the openssl builtin default is used which is suitable
1565 If this is set, it forces IO::Socket::SSL to use a certificate and key, even if
1566 you are setting up an SSL client. If this is set to 0 (the default), then you will
1567 only need a certificate and key if you are setting up a server.
1571 If your RSA private key is not in default place (F<certs/server-key.pem> for servers,
1572 F<certs/client-key.pem> for clients), then this is the option that you would use to
1573 specify a different location. Keys should be PEM formatted, and if they are
1574 encrypted, you will be prompted to enter a password before the socket is formed
1575 (unless you specified the SSL_passwd_cb option).
1579 This is an EVP_PKEY* and can be used instead of SSL_key_file.
1580 Useful if you don't have your key in a file but create it dynamically or get it from
1581 a string (see openssl PEM_read_bio_PrivateKey etc for getting a EVP_PKEY* from
1586 If your SSL certificate is not in the default place (F<certs/server-cert.pem> for servers,
1587 F<certs/client-cert.pem> for clients), then you should use this option to specify the
1588 location of your certificate. Note that a key and certificate are only required for an
1589 SSL server, so you do not need to bother with these trifling options should you be
1590 setting up an unauthenticated client.
1594 This is an X509* or an array of X509*.
1595 The first X509* is the internal representation of the certificate while the following
1596 ones are extra certificates. Useful if you create your certificate dynamically (like
1597 in a SSL intercepting proxy) or get it from a string (see openssl PEM_read_bio_X509 etc
1598 for getting a X509* from a string).
1602 If you want Diffie-Hellman key exchange you need to supply a suitable file here
1603 or use the SSL_dh parameter. See dhparam command in openssl for more information.
1607 Like SSL_dh_file, but instead of giving a file you use a preloaded or generated DH*.
1611 If your private key is encrypted, you might not want the default password prompt from
1612 Net::SSLeay. This option takes a reference to a subroutine that should return the
1613 password required to decrypt your private key.
1617 If you want to verify that the peer certificate has been signed by a reputable
1618 certificate authority, then you should use this option to locate the file
1619 containing the certificateZ<>(s) of the reputable certificate authorities if it is
1620 not already in the file F<certs/my-ca.pem>.
1624 If you are unusually friendly with the OpenSSL documentation, you might have set
1625 yourself up a directory containing several trusted certificates as separate files
1626 as well as an index of the certificates. If you want to use that directory for
1627 validation purposes, and that directory is not F<ca/>, then use this option to
1628 point IO::Socket::SSL to the right place to look.
1630 =item SSL_verify_mode
1632 This option sets the verification mode for the peer certificate. The default
1633 (0x00) does no authentication. You may combine 0x01 (verify peer), 0x02 (fail
1634 verification if no peer certificate exists; ignored for clients), and 0x04
1635 (verify client once) to change the default.
1636 See OpenSSL man page for SSL_CTX_set_verify for more information.
1638 =item SSL_verify_callback
1640 If you want to verify certificates yourself, you can pass a sub reference along
1641 with this parameter to do so. When the callback is called, it will be passed:
1642 1) a true/false value that indicates what OpenSSL thinks of the certificate,
1643 2) a C-style memory address of the certificate store,
1644 3) a string containing the certificate's issuer attributes and owner attributes, and
1645 4) a string containing any errors encountered (0 if no errors).
1646 The function should return 1 or 0, depending on whether it thinks the certificate
1647 is valid or invalid. The default is to let OpenSSL do all of the busy work.
1649 =item SSL_verifycn_scheme
1651 Set the scheme used to automatically verify the hostname of the peer.
1652 See the information about the verification schemes in B<verify_hostname>.
1653 The default is undef, e.g. to not automatically verify the hostname.
1655 =item SSL_verifycn_name
1657 Set the name which is used in verification of hostname. If SSL_verifycn_scheme
1658 is set and no SSL_verifycn_name is given it will try to use the PeerHost and
1659 PeerAddr settings and fail if no name caan be determined.
1661 Using PeerHost or PeerAddr works only if you create the connection directly
1662 with C<< IO::Socket::SSL->new >>, if an IO::Socket::INET object is upgraded
1663 with B<start_SSL> the name has to be given in B<SSL_verifycn_name>.
1667 If you want to verify that the peer certificate has not been revoked by the
1668 signing authority, set this value to true. OpenSSL will search for the CRL
1669 in your SSL_ca_path. See the Net::SSLeay documentation for more details.
1670 Note that this functionality appears to be broken with OpenSSL < v0.9.7b,
1671 so its use with lower versions will result in an error.
1675 If you have already set the above options (SSL_version through SSL_check_crl;
1676 this does not include SSL_cipher_list yet) for a previous instance of
1677 IO::Socket::SSL, then you can reuse the SSL context of that instance by passing
1678 it as the value for the SSL_reuse_ctx parameter. You may also create a
1679 new instance of the IO::Socket::SSL::SSL_Context class, using any context options
1680 that you desire without specifying connection options, and pass that here instead.
1682 If you use this option, all other context-related options that you pass
1683 in the same call to new() will be ignored unless the context supplied was invalid.
1684 Note that, contrary to versions of IO::Socket::SSL below v0.90, a global SSL context
1685 will not be implicitly used unless you use the set_default_context() function.
1687 =item SSL_session_cache_size
1689 If you make repeated connections to the same host/port and the SSL renegotiation time
1690 is an issue, you can turn on client-side session caching with this option by specifying a
1691 positive cache size. For successive connections, pass the SSL_reuse_ctx option to
1692 the new() calls (or use set_default_context()) to make use of the cached sessions.
1693 The session cache size refers to the number of unique host/port pairs that can be
1694 stored at one time; the oldest sessions in the cache will be removed if new ones are
1697 =item SSL_session_cache
1699 Specifies session cache object which should be used instead of creating a new.
1700 Overrules SSL_session_cache_size.
1701 This option is useful if you wan't to reuse the cache, but not the rest of
1704 A session cache object can be created using
1705 C<< IO::Socket::SSL::Session_Cache->new( cachesize ) >>.
1707 Use set_default_session_cache() to set a global cache object.
1709 =item SSL_error_trap
1711 When using the accept() or connect() methods, it may be the case that the
1712 actual socket connection works but the SSL negotiation fails, as in the case of
1713 an HTTP client connecting to an HTTPS server. Passing a subroutine ref attached
1714 to this parameter allows you to gain control of the orphaned socket instead of having it
1715 be closed forcibly. The subroutine, if called, will be passed two parameters:
1716 a reference to the socket on which the SSL negotiation failed and and the full
1717 text of the error message.
1723 There are a number of nasty traps that lie in wait if you are not careful about using
1724 close(). The first of these will bite you if you have been using shutdown() on your
1725 sockets. Since the SSL protocol mandates that a SSL "close notify" message be
1726 sent before the socket is closed, a shutdown() that closes the socket's write channel
1727 will cause the close() call to hang. For a similar reason, if you try to close a
1728 copy of a socket (as in a forking server) you will affect the original socket as well.
1729 To get around these problems, call close with an object-oriented syntax
1730 (e.g. $socket->close(SSL_no_shutdown => 1))
1731 and one or more of the following parameters:
1735 =item SSL_no_shutdown
1737 If set to a true value, this option will make close() not use the SSL_shutdown() call
1738 on the socket in question so that the close operation can complete without problems
1739 if you have used shutdown() or are working on a copy of a socket.
1741 =item SSL_fast_shutdown
1743 If set to true only a unidirectional shutdown will be done, e.g. only the
1744 close_notify (see SSL_shutdown(3)) will be called. Otherwise a bidrectional
1745 shutdown will be done. If used within close() it defaults to true, if used
1746 within stop_SSL() it defaults to false.
1750 If you want to make sure that the SSL context of the socket is destroyed when
1751 you close it, set this option to a true value.
1757 This function has exactly the same syntax as sysread(), and performs nearly the same
1758 task (reading data from the socket) but will not advance the read position so
1759 that successive calls to peek() with the same arguments will return the same results.
1760 This function requires OpenSSL 0.9.6a or later to work.
1765 This function will let you know how many bytes of data are immediately ready for reading
1766 from the socket. This is especially handy if you are doing reads on a blocking socket
1767 or just want to know if new data has been sent over the socket.
1770 =item B<get_cipher()>
1772 Returns the string form of the cipher that the IO::Socket::SSL object is using.
1774 =item B<dump_peer_certificate()>
1776 Returns a parsable string with select fields from the peer SSL certificate. This
1777 method directly returns the result of the dump_peer_certificate() method of Net::SSLeay.
1779 =item B<peer_certificate($field)>
1781 If a peer certificate exists, this function can retrieve values from it.
1782 If no field is given the internal representation of certificate from Net::SSLeay is
1784 The following fields can be queried:
1788 =item authority (alias issuer)
1790 The certificate authority which signed the certificate.
1792 =item owner (alias subject)
1794 The owner of the certificate.
1796 =item commonName (alias cn) - only for Net::SSLeay version >=1.30
1798 The common name, usually the server name for SSL certificates.
1800 =item subjectAltNames - only for Net::SSLeay version >=1.33
1802 Alternative names for the subject, usually different names for the same
1803 server, like example.org, example.com, *.example.com.
1805 It returns a list of (typ,value) with typ GEN_DNS, GEN_IPADD etc (these
1806 constants are exported from IO::Socket::SSL).
1807 See Net::SSLeay::X509_get_subjectAltNames.
1811 =item B<verify_hostname($hostname,$scheme)>
1813 This verifies the given hostname against the peer certificate using the
1814 given scheme. Hostname is usually what you specify within the PeerAddr.
1816 Verification of hostname against a certificate is different between various
1817 applications and RFCs. Some scheme allow wildcards for hostnames, some only
1818 in subjectAltNames, and even their different wildcard schemes are possible.
1820 To ease the verification the following schemes are predefined:
1824 =item ldap (rfc4513), pop3,imap,acap (rfc2995), nntp (rfc4642)
1826 Simple wildcards in subjectAltNames are possible, e.g. *.example.org matches
1827 www.example.org but not lala.www.example.org. If nothing from subjectAltNames
1828 match it checks against the common name, but there are no wildcards allowed.
1830 =item http (rfc2818), alias is www
1832 Extended wildcards in subjectAltNames are possible, e.g. *.example.org or
1833 even www*.example.org. Wildcards in the common name are not allowed. The common
1834 name will be only checked if no names are given in subjectAltNames.
1836 =item smtp (rfc3207)
1838 This RFC doesn't say much useful about the verification so it just assumes
1839 that subjectAltNames are possible, but no wildcards are possible anywhere.
1843 The scheme can be given either by specifying the name for one of the above predefined
1844 schemes, by using a callback (see below) or by using a hash which can have the
1845 following keys and values:
1849 =item check_cn: 0|'always'|'when_only'
1851 Determines if the common name gets checked. If 'always' it will always be checked
1852 (like in ldap), if 'when_only' it will only be checked if no names are given in
1853 subjectAltNames (like in http), for any other values the common name will not be checked.
1855 =item wildcards_in_alt: 0|'leftmost'|'anywhere'
1857 Determines if and where wildcards in subjectAltNames are possible. If 'leftmost'
1858 only cases like *.example.org will be possible (like in ldap), for 'anywhere'
1859 www*.example.org is possible too (like http), dangerous things like but www.*.org
1860 or even '*' will not be allowed.
1862 =item wildcards_in_cn: 0|'leftmost'|'anywhere'
1864 Similar to wildcards_in_alt, but checks the common name. There is no predefined
1865 scheme which allows wildcards in common names.
1869 If you give a subroutine for verification it will be called with the arguments
1870 ($hostname,$commonName,@subjectAltNames), where hostname is the name given for
1871 verification, commonName is the result from peer_certificate('cn') and
1872 subjectAltNames is the result from peer_certificate('subjectAltNames').
1876 Returns the last error (in string form) that occurred. If you do not have a real
1877 object to perform this method on, call IO::Socket::SSL::errstr() instead.
1879 For read and write errors on non-blocking sockets, this method may include the string
1880 C<SSL wants a read first!> or C<SSL wants a write first!> meaning that the other side
1881 is expecting to read from or write to the socket and wants to be satisfied before you
1882 get to do anything. But with version 0.98 you are better comparing the global exported
1883 variable $SSL_ERROR against the exported symbols SSL_WANT_READ and SSL_WANT_WRITE.
1887 This returns false if the socket could not be opened, 1 if the socket could be opened
1888 and the SSL handshake was successful done and -1 if the underlying IO::Handle is open,
1889 but the SSL handshake failed.
1891 =item B<< IO::Socket::SSL->start_SSL($socket, ... ) >>
1893 This will convert a glob reference or a socket that you provide to an IO::Socket::SSL
1894 object. You may also pass parameters to specify context or connection options as with
1895 a call to new(). If you are using this function on an accept()ed socket, you must
1896 set the parameter "SSL_server" to 1, i.e. IO::Socket::SSL->start_SSL($socket, SSL_server => 1).
1897 If you have a class that inherits from IO::Socket::SSL and you want the $socket to be blessed
1898 into your own class instead, use MyClass->start_SSL($socket) to achieve the desired effect.
1900 Note that if start_SSL() fails in SSL negotiation, $socket will remain blessed in its
1901 original class. For non-blocking sockets you better just upgrade the socket to
1902 IO::Socket::SSL and call accept_SSL or connect_SSL and the upgraded object. To
1903 just upgrade the socket set B<SSL_startHandshake> explicitly to 0. If you call start_SSL
1904 w/o this parameter it will revert to blocking behavior for accept_SSL and connect_SSL.
1906 If given the parameter "Timeout" it will stop if after the timeout no SSL connection
1907 was established. This parameter is only used for blocking sockets, if it is not given the
1908 default Timeout from the underlying IO::Socket will be used.
1910 =item B<stop_SSL(...)>
1912 This is the opposite of start_SSL(), e.g. it will shutdown the SSL connection
1913 and return to the class before start_SSL(). It gets the same arguments as close(),
1914 in fact close() calls stop_SSL() (but without downgrading the class).
1916 Will return true if it suceeded and undef if failed. This might be the case for
1917 non-blocking sockets. In this case $! is set to EAGAIN and the ssl error to
1918 SSL_WANT_READ or SSL_WANT_WRITE. In this case the call should be retried again with
1919 the same arguments once the socket is ready is until it succeeds.
1921 =item B<< IO::Socket::SSL->new_from_fd($fd, ...) >>
1923 This will convert a socket identified via a file descriptor into an SSL socket.
1924 Note that the argument list does not include a "MODE" argument; if you supply one,
1925 it will be thoughtfully ignored (for compatibility with IO::Socket::INET). Instead,
1926 a mode of '+<' is assumed, and the file descriptor passed must be able to handle such
1927 I/O because the initial SSL handshake requires bidirectional communication.
1929 =item B<IO::Socket::SSL::set_default_context(...)>
1931 You may use this to make IO::Socket::SSL automatically re-use a given context (unless
1932 specifically overridden in a call to new()). It accepts one argument, which should
1933 be either an IO::Socket::SSL object or an IO::Socket::SSL::SSL_Context object. See
1934 the SSL_reuse_ctx option of new() for more details. Note that this sets the default
1935 context globally, so use with caution (esp. in mod_perl scripts).
1937 =item B<IO::Socket::SSL::set_default_session_cache(...)>
1939 You may use this to make IO::Socket::SSL automatically re-use a given session cache
1940 (unless specifically overridden in a call to new()). It accepts one argument, which should
1941 be an IO::Socket::SSL::Session_Cache object or similar (e.g something which implements
1942 get_session and add_session like IO::Socket::SSL::Session_Cache does).
1943 See the SSL_session_cache option of new() for more details. Note that this sets the default
1944 cache globally, so use with caution.
1946 =item B<IO::Socket::SSL::set_ctx_defaults(%args)>
1948 With this function one can set defaults for all SSL_* parameter used for creation of
1949 the context, like the SSL_verify* parameter.
1953 =item mode - set default SSL_verify_mode
1955 =item callback - set default SSL_verify_callback
1957 =item scheme - set default SSL_verifycn_scheme
1959 =item name - set default SSL_verifycn_name
1961 If not given and scheme is hash reference with key callback it will be set to 'unknown'
1967 The following methods are unsupported (not to mention futile!) and IO::Socket::SSL
1968 will emit a large CROAK() if you are silly enough to use them:
1986 Note that send() and recv() cannot be reliably trapped by a tied filehandle (such as
1987 that used by IO::Socket::SSL) and so may send unencrypted data over the socket. Object-oriented
1988 calls to these functions will fail, telling you to use the print/printf/syswrite
1989 and read/sysread families instead.
1994 =head1 RETURN VALUES
1996 A few changes have gone into IO::Socket::SSL v0.93 and later with respect to
1997 return values. The behavior on success remains unchanged, but for I<all> functions,
1998 the return value on error is now an empty list. Therefore, the return value will be
1999 false in all contexts, but those who have been using the return values as arguments
2000 to subroutines (like C<mysub(IO::Socket::SSL(...)->new, ...)>) may run into problems.
2001 The moral of the story: I<always> check the return values of these functions before
2002 using them in any way that you consider meaningful.
2007 Support for IPv6 with IO::Socket::SSL is expected to work, but is experimental, as
2008 none of the author's machines use IPv6 and hence he cannot test IO::Socket::SSL with
2009 them. However, a few brave people have used it without incident, so if you wish to
2010 make IO::Socket::SSL IPv6 aware, pass the 'inet6' option to IO::Socket::SSL when
2011 calling it (i.e. C<use IO::Socket::SSL qw(inet6);>). You will need IO::Socket::INET6
2012 and Socket6 to use this option, and you will also need to write C<use Socket6;> before
2013 using IO::Socket::SSL. If you absolutely do not want to use this (or want a quick
2014 change back to IPv4), pass the 'inet4' option instead.
2016 Currently, there is no support for using IPv4 and IPv6 simultaneously in a single program,
2017 but it is planned for a future release.
2022 If you are having problems using IO::Socket::SSL despite the fact that can recite backwards
2023 the section of this documentation labelled 'Using SSL', you should try enabling debugging. To
2024 specify the debug level, pass 'debug#' (where # is a number from 0 to 3) to IO::Socket::SSL
2026 The debug level will also be propagated to Net::SSLeay::trace, see also L<Net::SSLeay>:
2030 =item use IO::Socket::SSL qw(debug0);
2032 No debugging (default).
2034 =item use IO::Socket::SSL qw(debug1);
2036 Print out errors from IO::Socket::SSL and ciphers from Net::SSLeay.
2038 =item use IO::Socket::SSL qw(debug2);
2040 Print also information about call flow from IO::Socket::SSL and progress
2041 information from Net::SSLeay.
2043 =item use IO::Socket::SSL qw(debug3);
2045 Print also some data dumps from IO::Socket::SSL and from Net::SSLeay.
2051 See the 'example' directory.
2055 IO::Socket::SSL is not threadsafe.
2056 This is because IO::Socket::SSL is based on Net::SSLeay which
2057 uses a global object to access some of the API of openssl
2058 and is therefore not threadsafe.
2059 It might probably work if you don't use SSL_verify_callback and
2062 IO::Socket::SSL does not work together with Storable::fd_retrieve/fd_store.
2063 See BUGS file for more information and how to work around the problem.
2067 IO::Socket::SSL uses Net::SSLeay as the shiny interface to OpenSSL, which is
2068 the shiny interface to the ugliness of SSL. As a result, you will need both Net::SSLeay
2069 and OpenSSL on your computer before using this module.
2071 If you have Scalar::Util (standard with Perl 5.8.0 and above) or WeakRef, IO::Socket::SSL
2072 sockets will auto-close when they go out of scope, just like IO::Socket::INET sockets. If
2073 you do not have one of these modules, then IO::Socket::SSL sockets will stay open until the
2074 program ends or you explicitly close them. This is due to the fact that a circular reference
2075 is required to make IO::Socket::SSL sockets act simultaneously like objects and glob references.
2079 The following functions are deprecated and are only retained for compatibility:
2083 =item context_init()
2085 use the SSL_reuse_ctx option if you want to re-use a context
2088 =item socketToSSL() and socket_to_SSL()
2090 use IO::Socket::SSL->start_SSL() instead
2093 =item get_peer_certificate()
2095 use the peer_certificate() function instead.
2096 Used to return X509_Certificate with methods subject_name and issuer_name.
2097 Now simply returns $self which has these methods (although depreceated).
2101 use peer_certificate( 'issuer' ) instead
2103 =item subject_name()
2105 use peer_certificate( 'subject' ) instead
2109 The following classes have been removed:
2115 (not that you should have been directly accessing this anyway):
2117 =item X509_Certificate
2119 (but get_peer_certificate() will still Do The Right Thing)
2125 IO::Socket::INET, IO::Socket::INET6, Net::SSLeay.
2129 Steffen Ullrich, <steffen at genua.de> is the current maintainer.
2131 Peter Behroozi, <behrooz at fas.harvard.edu> (Note the lack of an "i" at the end of "behrooz")
2133 Marko Asplund, <marko.asplund at kronodoc.fi>, was the original author of IO::Socket::SSL.
2135 Patches incorporated from various people, see file Changes.
2139 Working support for non-blocking was added by Steffen Ullrich.
2141 The rewrite of this module is Copyright (C) 2002-2005 Peter Behroozi.
2143 The original versions of this module are Copyright (C) 1999-2002 Marko Asplund.
2145 This module is free software; you can redistribute it and/or
2146 modify it under the same terms as Perl itself.
2149 =head1 Appendix: Using SSL
2151 If you are unfamiliar with the way OpenSSL works, good references may be found in
2152 both the book "Network Security with OpenSSL" (Oreilly & Assoc.) and the web site
2153 L<http://www.tldp.org/HOWTO/SSL-Certificates-HOWTO/>. Read on for a quick overview.
2155 =head2 The Long of It (Detail)
2157 The usual reason for using SSL is to keep your data safe. This means that not only
2158 do you have to encrypt the data while it is being transported over a network, but
2159 you also have to make sure that the right person gets the data. To accomplish this
2160 with SSL, you have to use certificates. A certificate closely resembles a
2161 Government-issued ID (at least in places where you can trust them). The ID contains some sort of
2162 identifying information such as a name and address, and is usually stamped with a seal
2163 of Government Approval. Theoretically, this means that you may trust the information on
2164 the card and do business with the owner of the card. The same ideas apply to SSL certificates,
2165 which have some identifying information and are "stamped" [most people refer to this as
2166 I<signing> instead] by someone (a Certificate Authority) who you trust will adequately
2167 verify the identifying information. In this case, because of some clever number theory,
2168 it is extremely difficult to falsify the stamping process. Another useful consequence
2169 of number theory is that the certificate is linked to the encryption process, so you may
2170 encrypt data (using information on the certificate) that only the certificate owner can
2173 What does this mean for you? It means that at least one person in the party has to
2174 have an ID to get drinks :-). Seriously, it means that one of the people communicating
2175 has to have a certificate to ensure that your data is safe. For client/server
2176 interactions, the server must B<always> have a certificate. If the server wants to
2177 verify that the client is safe, then the client must also have a personal certificate.
2178 To verify that a certificate is safe, one compares the stamped "seal" [commonly called
2179 an I<encrypted digest/hash/signature>] on the certificate with the official "seal" of
2180 the Certificate Authority to make sure that they are the same. To do this, you will
2181 need the [unfortunately named] certificate of the Certificate Authority. With all these
2182 in hand, you can set up a SSL connection and be reasonably confident that no-one is
2185 =head2 The Short of It (Summary)
2187 For servers, you will need to generate a cryptographic private key and a certificate
2188 request. You will need to send the certificate request to a Certificate Authority to
2189 get a real certificate back, after which you can start serving people. For clients,
2190 you will not need anything unless the server wants validation, in which case you will
2191 also need a private key and a real certificate. For more information about how to
2192 get these, see L<http://www.modssl.org/docs/2.8/ssl_faq.html#ToC24>.