�ɲɾ�����ӯ�����һ��ˣ��������С���˴��ͣ�������P���ҹ��ñ˽��ά�Բ��������˸߸ԣ�������ơ��ҹ��ñ�����ά�Բ���ˡ���˳^�ӣ������ӡ� ���ͯj�ӣ��ƺ���ӣ� ? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!PK81]"00INET.pmnu[# IO::Socket::INET.pm # # Copyright (c) 1997-8 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package IO::Socket::INET; use strict; our(@ISA, $VERSION); use IO::Socket; use Socket; use Carp; use Exporter; use Errno; @ISA = qw(IO::Socket); $VERSION = "1.35"; my $EINVAL = exists(&Errno::EINVAL) ? Errno::EINVAL() : 1; IO::Socket::INET->register_domain( AF_INET ); my %socket_type = ( tcp => SOCK_STREAM, udp => SOCK_DGRAM, icmp => SOCK_RAW ); my %proto_number; $proto_number{tcp} = Socket::IPPROTO_TCP() if defined &Socket::IPPROTO_TCP; $proto_number{udp} = Socket::IPPROTO_UDP() if defined &Socket::IPPROTO_UDP; $proto_number{icmp} = Socket::IPPROTO_ICMP() if defined &Socket::IPPROTO_ICMP; my %proto_name = reverse %proto_number; sub new { my $class = shift; unshift(@_, "PeerAddr") if @_ == 1; return $class->SUPER::new(@_); } sub _cache_proto { my @proto = @_; for (map lc($_), $proto[0], split(' ', $proto[1])) { $proto_number{$_} = $proto[2]; } $proto_name{$proto[2]} = $proto[0]; } sub _get_proto_number { my $name = lc(shift); return undef unless defined $name; return $proto_number{$name} if exists $proto_number{$name}; my @proto = eval { getprotobyname($name) }; return undef unless @proto; _cache_proto(@proto); return $proto[2]; } sub _get_proto_name { my $num = shift; return undef unless defined $num; return $proto_name{$num} if exists $proto_name{$num}; my @proto = eval { getprotobynumber($num) }; return undef unless @proto; _cache_proto(@proto); return $proto[0]; } sub _sock_info { my($addr,$port,$proto) = @_; my $origport = $port; my @serv = (); $port = $1 if(defined $addr && $addr =~ s,:([\w\(\)/]+)$,,); if(defined $proto && $proto =~ /\D/) { my $num = _get_proto_number($proto); unless (defined $num) { $@ = "Bad protocol '$proto'"; return; } $proto = $num; } if(defined $port) { my $defport = ($port =~ s,\((\d+)\)$,,) ? $1 : undef; my $pnum = ($port =~ m,^(\d+)$,)[0]; @serv = getservbyname($port, _get_proto_name($proto) || "") if ($port =~ m,\D,); $port = $serv[2] || $defport || $pnum; unless (defined $port) { $@ = "Bad service '$origport'"; return; } $proto = _get_proto_number($serv[3]) if @serv && !$proto; } return ($addr || undef, $port || undef, $proto || undef ); } sub _error { my $sock = shift; my $err = shift; { local($!); my $title = ref($sock).": "; $@ = join("", $_[0] =~ /^$title/ ? "" : $title, @_); $sock->close() if(defined fileno($sock)); } $! = $err; return undef; } sub _get_addr { my($sock,$addr_str, $multi) = @_; my @addr; if ($multi && $addr_str !~ /^\d+(?:\.\d+){3}$/) { (undef, undef, undef, undef, @addr) = gethostbyname($addr_str); } else { my $h = inet_aton($addr_str); push(@addr, $h) if defined $h; } @addr; } sub configure { my($sock,$arg) = @_; my($lport,$rport,$laddr,$raddr,$proto,$type); $arg->{LocalAddr} = $arg->{LocalHost} if exists $arg->{LocalHost} && !exists $arg->{LocalAddr}; ($laddr,$lport,$proto) = _sock_info($arg->{LocalAddr}, $arg->{LocalPort}, $arg->{Proto}) or return _error($sock, $!, $@); $laddr = defined $laddr ? inet_aton($laddr) : INADDR_ANY; return _error($sock, $EINVAL, "Bad hostname '",$arg->{LocalAddr},"'") unless(defined $laddr); $arg->{PeerAddr} = $arg->{PeerHost} if exists $arg->{PeerHost} && !exists $arg->{PeerAddr}; unless(exists $arg->{Listen}) { ($raddr,$rport,$proto) = _sock_info($arg->{PeerAddr}, $arg->{PeerPort}, $proto) or return _error($sock, $!, $@); } $proto ||= _get_proto_number('tcp'); $type = $arg->{Type} || $socket_type{lc _get_proto_name($proto)}; my @raddr = (); if(defined $raddr) { @raddr = $sock->_get_addr($raddr, $arg->{MultiHomed}); return _error($sock, $EINVAL, "Bad hostname '",$arg->{PeerAddr},"'") unless @raddr; } while(1) { $sock->socket(AF_INET, $type, $proto) or return _error($sock, $!, "$!"); if (defined $arg->{Blocking}) { defined $sock->blocking($arg->{Blocking}) or return _error($sock, $!, "$!"); } if ($arg->{Reuse} || $arg->{ReuseAddr}) { $sock->sockopt(SO_REUSEADDR,1) or return _error($sock, $!, "$!"); } if ($arg->{ReusePort}) { $sock->sockopt(SO_REUSEPORT,1) or return _error($sock, $!, "$!"); } if ($arg->{Broadcast}) { $sock->sockopt(SO_BROADCAST,1) or return _error($sock, $!, "$!"); } if($lport || ($laddr ne INADDR_ANY) || exists $arg->{Listen}) { $sock->bind($lport || 0, $laddr) or return _error($sock, $!, "$!"); } if(exists $arg->{Listen}) { $sock->listen($arg->{Listen} || 5) or return _error($sock, $!, "$!"); last; } # don't try to connect unless we're given a PeerAddr last unless exists($arg->{PeerAddr}); $raddr = shift @raddr; return _error($sock, $EINVAL, 'Cannot determine remote port') unless($rport || $type == SOCK_DGRAM || $type == SOCK_RAW); last unless($type == SOCK_STREAM || defined $raddr); return _error($sock, $EINVAL, "Bad hostname '",$arg->{PeerAddr},"'") unless defined $raddr; # my $timeout = ${*$sock}{'io_socket_timeout'}; # my $before = time() if $timeout; undef $@; if ($sock->connect(pack_sockaddr_in($rport, $raddr))) { # ${*$sock}{'io_socket_timeout'} = $timeout; return $sock; } return _error($sock, $!, $@ || "Timeout") unless @raddr; # if ($timeout) { # my $new_timeout = $timeout - (time() - $before); # return _error($sock, # (exists(&Errno::ETIMEDOUT) ? Errno::ETIMEDOUT() : $EINVAL), # "Timeout") if $new_timeout <= 0; # ${*$sock}{'io_socket_timeout'} = $new_timeout; # } } $sock; } sub connect { @_ == 2 || @_ == 3 or croak 'usage: $sock->connect(NAME) or $sock->connect(PORT, ADDR)'; my $sock = shift; return $sock->SUPER::connect(@_ == 1 ? shift : pack_sockaddr_in(@_)); } sub bind { @_ == 2 || @_ == 3 or croak 'usage: $sock->bind(NAME) or $sock->bind(PORT, ADDR)'; my $sock = shift; return $sock->SUPER::bind(@_ == 1 ? shift : pack_sockaddr_in(@_)) } sub sockaddr { @_ == 1 or croak 'usage: $sock->sockaddr()'; my($sock) = @_; my $name = $sock->sockname; $name ? (sockaddr_in($name))[1] : undef; } sub sockport { @_ == 1 or croak 'usage: $sock->sockport()'; my($sock) = @_; my $name = $sock->sockname; $name ? (sockaddr_in($name))[0] : undef; } sub sockhost { @_ == 1 or croak 'usage: $sock->sockhost()'; my($sock) = @_; my $addr = $sock->sockaddr; $addr ? inet_ntoa($addr) : undef; } sub peeraddr { @_ == 1 or croak 'usage: $sock->peeraddr()'; my($sock) = @_; my $name = $sock->peername; $name ? (sockaddr_in($name))[1] : undef; } sub peerport { @_ == 1 or croak 'usage: $sock->peerport()'; my($sock) = @_; my $name = $sock->peername; $name ? (sockaddr_in($name))[0] : undef; } sub peerhost { @_ == 1 or croak 'usage: $sock->peerhost()'; my($sock) = @_; my $addr = $sock->peeraddr; $addr ? inet_ntoa($addr) : undef; } 1; __END__ =head1 NAME IO::Socket::INET - Object interface for AF_INET domain sockets =head1 SYNOPSIS use IO::Socket::INET; =head1 DESCRIPTION C provides an object interface to creating and using sockets in the AF_INET domain. It is built upon the L interface and inherits all the methods defined by L. =head1 CONSTRUCTOR =over 4 =item new ( [ARGS] ) Creates an C object, which is a reference to a newly created symbol (see the C package). C optionally takes arguments, these arguments are in key-value pairs. In addition to the key-value pairs accepted by L, C provides. PeerAddr Remote host address [:] PeerHost Synonym for PeerAddr PeerPort Remote port or service [()] | LocalAddr Local host bind address hostname[:port] LocalHost Synonym for LocalAddr LocalPort Local host bind port [()] | Proto Protocol name (or number) "tcp" | "udp" | ... Type Socket type SOCK_STREAM | SOCK_DGRAM | ... Listen Queue size for listen ReuseAddr Set SO_REUSEADDR before binding Reuse Set SO_REUSEADDR before binding (deprecated, prefer ReuseAddr) ReusePort Set SO_REUSEPORT before binding Broadcast Set SO_BROADCAST before binding Timeout Timeout value for various operations MultiHomed Try all addresses for multi-homed hosts Blocking Determine if connection will be blocking mode If C is defined then a listen socket is created, else if the socket type, which is derived from the protocol, is SOCK_STREAM then connect() is called. If the C argument is given, but false, the queue size will be set to 5. Although it is not illegal, the use of C on a socket which is in non-blocking mode is of little use. This is because the first connect will never fail with a timeout as the connect call will not block. The C can be a hostname or the IP-address on the "xx.xx.xx.xx" form. The C can be a number or a symbolic service name. The service name might be followed by a number in parenthesis which is used if the service is not known by the system. The C specification can also be embedded in the C by preceding it with a ":". If C is not given and you specify a symbolic C port, then the constructor will try to derive C from the service name. As a last resort C "tcp" is assumed. The C parameter will be deduced from C if not specified. If the constructor is only passed a single argument, it is assumed to be a C specification. If C is set to 0, the connection will be in nonblocking mode. If not specified it defaults to 1 (blocking mode). Examples: $sock = IO::Socket::INET->new(PeerAddr => 'www.perl.org', PeerPort => 'http(80)', Proto => 'tcp'); $sock = IO::Socket::INET->new(PeerAddr => 'localhost:smtp(25)'); $sock = IO::Socket::INET->new(Listen => 5, LocalAddr => 'localhost', LocalPort => 9000, Proto => 'tcp'); $sock = IO::Socket::INET->new('127.0.0.1:25'); $sock = IO::Socket::INET->new( PeerPort => 9999, PeerAddr => inet_ntoa(INADDR_BROADCAST), Proto => udp, LocalAddr => 'localhost', Broadcast => 1 ) or die "Can't bind : $@\n"; NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE As of VERSION 1.18 all IO::Socket objects have autoflush turned on by default. This was not the case with earlier releases. NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE =back =head2 METHODS =over 4 =item sockaddr () Return the address part of the sockaddr structure for the socket =item sockport () Return the port number that the socket is using on the local host =item sockhost () Return the address part of the sockaddr structure for the socket in a text form xx.xx.xx.xx =item peeraddr () Return the address part of the sockaddr structure for the socket on the peer host =item peerport () Return the port number for the socket on the peer host. =item peerhost () Return the address part of the sockaddr structure for the socket on the peer host in a text form xx.xx.xx.xx =back =head1 SEE ALSO L, L =head1 AUTHOR Graham Barr. Currently maintained by the Perl Porters. Please report all bugs to . =head1 COPYRIGHT Copyright (c) 1996-8 Graham Barr . All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK81]XpJ_ _ UNIX.pmnu[# IO::Socket::UNIX.pm # # Copyright (c) 1997-8 Graham Barr . All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package IO::Socket::UNIX; use strict; our(@ISA, $VERSION); use IO::Socket; use Carp; @ISA = qw(IO::Socket); $VERSION = "1.26"; $VERSION = eval $VERSION; IO::Socket::UNIX->register_domain( AF_UNIX ); sub new { my $class = shift; unshift(@_, "Peer") if @_ == 1; return $class->SUPER::new(@_); } sub configure { my($sock,$arg) = @_; my($bport,$cport); my $type = $arg->{Type} || SOCK_STREAM; $sock->socket(AF_UNIX, $type, 0) or return undef; if(exists $arg->{Local}) { my $addr = sockaddr_un($arg->{Local}); $sock->bind($addr) or return undef; } if(exists $arg->{Listen} && $type != SOCK_DGRAM) { $sock->listen($arg->{Listen} || 5) or return undef; } elsif(exists $arg->{Peer}) { my $addr = sockaddr_un($arg->{Peer}); $sock->connect($addr) or return undef; } $sock; } sub hostpath { @_ == 1 or croak 'usage: $sock->hostpath()'; my $n = $_[0]->sockname || return undef; (sockaddr_un($n))[0]; } sub peerpath { @_ == 1 or croak 'usage: $sock->peerpath()'; my $n = $_[0]->peername || return undef; (sockaddr_un($n))[0]; } 1; # Keep require happy __END__ =head1 NAME IO::Socket::UNIX - Object interface for AF_UNIX domain sockets =head1 SYNOPSIS use IO::Socket::UNIX; my $SOCK_PATH = "$ENV{HOME}/unix-domain-socket-test.sock"; # Server: my $server = IO::Socket::UNIX->new( Type => SOCK_STREAM(), Local => $SOCK_PATH, Listen => 1, ); my $count = 1; while (my $conn = $server->accept()) { $conn->print("Hello " . ($count++) . "\n"); } # Client: my $client = IO::Socket::UNIX->new( Type => SOCK_STREAM(), Peer => $SOCK_PATH, ); # Now read and write from $client =head1 DESCRIPTION C provides an object interface to creating and using sockets in the AF_UNIX domain. It is built upon the L interface and inherits all the methods defined by L. =head1 CONSTRUCTOR =over 4 =item new ( [ARGS] ) Creates an C object, which is a reference to a newly created symbol (see the C package). C optionally takes arguments, these arguments are in key-value pairs. In addition to the key-value pairs accepted by L, C provides. Type Type of socket (eg SOCK_STREAM or SOCK_DGRAM) Local Path to local fifo Peer Path to peer fifo Listen Queue size for listen If the constructor is only passed a single argument, it is assumed to be a C specification. If the C argument is given, but false, the queue size will be set to 5. =back =head1 METHODS =over 4 =item hostpath() Returns the pathname to the fifo at the local end =item peerpath() Returns the pathanme to the fifo at the peer end =back =head1 SEE ALSO L, L =head1 AUTHOR Graham Barr. Currently maintained by the Perl Porters. Please report all bugs to . =head1 COPYRIGHT Copyright (c) 1996-8 Graham Barr . All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PKj4][pp Socket.sonuȯELF>p2@p@8@pp ДД Д 8   $$PPP Ptd`~`~`~QtdRtdДД Д 0GNUq'aA4; R8` 8:;BE|qXaϣb Y K|~3`  20>i{ =Me<lR, $}F"    @d__gmon_start___ITM_deregisterTMCloneTable_ITM_registerTMCloneTable__cxa_finalizelibpthread.so.0Perl_hv_common_key_lenPerl_newCONSTSUBPerl_sv_upgradePerl_croakPerl_sv_newmortalgai_strerrorPerl_sv_setpvPerl_safesysmallocmemcpygetnameinfoPerl_safesysfreePerl_sv_2iv_flagsPerl_sv_2pv_flagsPerl_newSVpvPerl_sv_2mortalPerl_mg_getPerl_stack_growPerl_croak_nocontext__stack_chk_failPerl_get_hvPerl_newSV_typegetaddrinfoPerl_newSVpvnfreeaddrinfoPerl_croak_xs_usagePerl_newSVpvn_flagsPerl_sv_2pvbyte__memcpy_chkPerl_newSVivPerl_sv_setivinet_ptonPerl_sv_setpvnPerl_sv_utf8_downgradeinet_ntopPerl_block_gimmePerl_newSVpvfPerl_hv_commonPerl_newSVpvf_nocontextPerl_croak_svPerl_newRV_noincPerl_newSVPerl_sv_2uv_flagsPerl_warn_nocontextboot_SocketPerl_xs_handshakePerl_newXS_deffilePL_thr_keypthread_getspecificPerl_sv_free2Perl_mro_method_changed_inPerl_newXSPerl_xs_boot_epiloglibperl.so.5.26libc.so.6_edata__bss_start_endGLIBC_2.2.5GLIBC_2.14GLIBC_2.3.4GLIBC_2.4U ui ti ii ui Д  3ؔ 2  q r0  rH r` rx #r *r 3r :rؕ Br Lr Sr ar8 hrP trh r r r rȖ r r r r( s@  sX sp  s +s 6s AsЗ Ms Zs es ms0 sH s` sx s s s sؘ t t 't 8t8 ?tP Oth [t ft qt }tș t t t t( t@ tX tp t t u uК )u 7u Ku `u0 puH u` ux u u u u؛ u u v v8  vP (vh 5v Bv Jv WvȜ _v gv qv }v( v@ vX vp v v v vН v w  w w0 wH $w` +wx 4w ;w Cw Mw؞ Tw dw rw }w8 wP wh w w w wȟ w w w w(  x@ xX #xp 0x 9x Jx TxР ax jx wx x0 xH x` xx x x x xء x x x y8 yP yh ,y 8y 8n XnȢ Sy ]y ly xy( y@ yX yp y y y yУ y y y y0  zH z` !zx -z :z Ez Vzؤ gz rz }z z8 zP zh z z z zȥ z z z {( {@ {X !{p ,{ :{ B{ K{Ц U{ #q `{ g{0 p{@ y{P {` {p { { { { { {Ч { { { { { {0 {@ {P |`  |p | | +| 9| C| L|Ш Y| g| o| x| | |0 |@ |P |` |p | | | | | |Щ | | } } } }0 }@ %}P ,}` 2}p 9} C} J} R} Y} e}Ъ o} z} } } } }0 }@ }P }` }p } } ~ ~ $~ .~Ы 8~ C~ S~ ȯ  Я د . 4( 0 8 @ H P X `  h  p  x          Ȯ Ю خ         ! " #( $0 %8 &@ 'H (P )X *` +h ,p -x / 0 1 2 3 4 5 6 7HH HtH5 % hhhhhhhhqhah Qh Ah 1h !h hhhhhhhhhhqhahQhAh1h!hhhh h!h"h#h$h%h&h'qh(ah)Qh*Ah+1h,!h-h.h/h0h1h2%~ D%~ D%~ D%~ D%~ D%~ D%~ D%~ D%~ D%~ D%~ D%~ D%}~ D%u~ D%m~ D%e~ D%]~ D%U~ D%M~ D%E~ D%=~ D%5~ D%-~ D%%~ D%~ D%~ D% ~ D%~ D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%} D%}} D%u} D%m} D%e} D%]} D%U} D%M} DH=} H} H9tH6} Ht H=Y} H5R} H)HHH?HHtH } HtfD=} u+UH=| Ht H=a )d| ]wAVE1MAAUATIUHSHHj(ZYHtwLhAE uЍJv uLHLH[]A\A]A^tMuAE [AN ]A\A]A^úLHAE HH5X6HATIUHcSAx HvPt4HLHHHh H؁K []A\fH<HL@HLxfDAWAVAUATUSH(HHOdH%(H$1HGxHHPHWxHcPHH)HEPHcIHH)HcL4H<H<$AF IGH $HtF % =H@ D$ IGH$HtF % =HHh D$AF @ILhLIAF % =JIvLL#E1E1|$H$HDLD$PpYL^AcIG H)HDLHCE IG HH)HT$I8HCIG LcL)HI8ID$H $IGHDIH$dH3%(H([]A\A]A^A_LD$ kf11ALD$L1L>HfD1D$D$ NfL4$MwM7HLljŃ|$H$L1nLHfDHt$L1ILHfLLFHH޹LH2D1D$LLLIYDHH޹LmHH=>21H=P61@UH5K2HSHHE1HjA0HH6ZYHtiHH@ t H@H[]f HH3~ tHFHJ H[]DHHD$H3HD$@1ff.ATUSHHPHdH%(HD$H1HGxHPHWxHWHchHH)HHHcH4L$F % =ukH~fHL$HT$1)D$)D$ )D$0D$StOHCH8HHCLHHD$HdH3%(u{HP[]A\D1LHHD$HHpHHkHHLHEH|$&HCLHHH55;fDATUHHSH H]HMdH%(HD$1HExHHPHUxHcPHH)HH$HcHH4ыF % =HHPHFH$H HHT$ @D$HE H)HLd$ HLHuIt$HHCZIt$HHC?HH]HD$dH3%(uCH []A\HHH$G@HH޹HHR H52H=.1&H52f.ATUHHSH H]HMdH%(HD$1HExHHPHUxHcPHH)HHHcHH4ыF % =HHPHFHT$HHHD$HE H)H~}Ld$HLHIt$HHCHH]HD$dH3%(uHH []A\@HT$H3HT$mfHH޹HmHhH51H=-1H5[1:f.ATUSHHHHKH3dH%(H$1HCxHPHSxHcPHH)HHQHcH4H,F -% =UHL`HFLd$ImWo)D$oH)L$ oP )T$0oX0)\$@o`@)d$PohP)l$`HP`HT$pPhT$x@lfD$|D$f|$uaD$LD$PHcIpHLcHHII$HkH+H$dH3%(|HĐ[]A\fDLD$IxkLD)@H9HxuHcxf< H5/H=/1HT$HLd$ImLD$nLHLInL)Ms1uoA1fATf.IxIIDHI)A1ADHplAADHH5.{йH5.1H=*fATUSHHHHKH3dH%(HD$1HCxHPHSxHcPHH)HHHcH4H,F % =u`HHPHFH$Hvm0H LcHHQII$HkH+HD$dH3%(u0H[]A\f.HHH$H5-cH5-H=)1@ATUSHHH0H+HKdH%(HD$(1HCxHHPHSxHcPHH)HHHcHH4ыF % =HHPHFHT$Ho)D$@D$ HC H)H~vHt$HHHHEDd$ *LHHEHH+HD$(dH3%(u@H0[]A\@HT$HHT$dHHH HoPH5,H=-(1VH5+f.AWAVAUATUSHH(HdH%(HD$1HGxHPHWxHWHcD`HH)HH8McJ4J,F % =HDh Ht*F % =HFAtWA 8AuMLcHII$HkH+HD$dH3%(H([]A\A]A^A_D8AtIHDLtLkHlIcLHIIEHCJ4D1H)?@6HSA DH5'+H=1'1HH5+3~@f.AUATUSHHHhHKH3dH%(HD$X1HCxHPHSxHcPHH)HHHcH4H,F % =jHDh Ld)AT$ t*H@8uLHAT$  5I$H@HD$ID$AA 7Ht$HoHt$)D$Ld$ .DLL H!%tLDHJHDщ@HHL)WLcHHHII$HkH+HD$XdH3%(Hh[]A\A]Ht$HHt$HD$F D$7fHHKAHT$LHH=%1hDH5(H=$1PH5(H5(H=(1*H=$1ff.AUATUSHHH8H+HKdH%(HD$(1HCxHHPHSxHcPHH)HHHcH4ыF % =HHPHFHT$HHH@HT$HD$f<Ht$HIHC@"<HC LmL)HHl$\HIEfHImLHIEH+HD$(dH3%(H8[]A\A]Ð< H5V'H=&1HT$HHT$H(<-LHHEdLLHI ҹH5&1H="H5&H5&H=!1f.ATUSHHHHKH3dH%(HD$1HCxHPHSxHcPHH)HH!HcL$H,AD$ % =I$HPID$H$HHȉADH5%1(LcHH)II$HkH+HD$dH3%(H[]A\fDHB8XLHGtWAD$ % =?HLHH$9H5?%H=4 1]H5$,H5%H=$17ATUSHHHCxH HPHSxHcHCHH)HHt H5:&~N HHHvHP lHLH 1E1E1RHHHjjjH AL$$HIT$0Ht$H= 1IHHHHH=!1%AUATUSHHHHH+HKdH%(HD$81HCxHHPHSxHcPHH)HHHcH4ыF >% =fHHPHFHT$Ho)D$HPHT$ @D$(D$f Ht$HIHC@"<&HC LeL)H,Hl$HID$fH8LHMHID$l$(\HHIl$ ID$HHDl$7HID$ AHDH+HD$8dH3%(HH[]A\A]< H5"H=!1wHT$HHT$fH<LH`HEVLLHIй H5!1H=H5!lH5!H=1f.AWAVAUATUSHhL/dH%(HD$X1HGxLHPHWxHWHchHH)HHcL8HHMI)ŅoHcH4L$ƒNLt2IL|2AD$ d< oE1AF $< E1f)D$ )D$0)D$@Mt-AG < @LHL$HT$ LKAHC L)H`DH-IEHcHD$EHl$HIL==|D1HHIA$LjH! HXXHC ZL)HLHMeHHIEHm(AFHAM H$HcuHIUHLLjIA$HY^HHcu%HLHjIA$HNHcu _HAXHLHjA$IH"jUHuHAYAZHLHjIA$H1Hu A[XH1HWfMA HE1A LjH~HAZA[Ht1H0F j<b NfDHE1A LjH(HrAXAYHt1H0F < nfDHLHE1jA H^_Ht+H0F L<D 0HE1LjH{A HZYHH0F u<t @% =H@ D$,yL8fE1% =xH@ D$ % =IMvH@HD$Hf% =I$Md$H@HD$Hfd% =(H@ D$$y% =H@ D$(AHl$McHLHCLt$JDHHD$XdH3%(fHh[]A\A]A^A_LLH-IDLHT$1HIHD$LHT$1HIHD$HCHL$HH`H|fDHsfDH[fDHCfDLLHUIDLHAF @LHAD$ AH=1oH=@1aLD$LD$IH5!H=A 1*HH5 H5H= 1H5H= 11DAUATUSHHH8HKH3dH%(HD$(1HCxHPHSxHcPHH)HHHcH4H,Ll)V  E1%= AU ut%= ` t)H@8uLHAU  IEHPIEHT$HfAHHt$fT$fDd$HD$D$LcHHII$HkH+HD$(dH3%(uyH8[]A\A]f uHD` DHAHT$LHHHT$4H5 H=1H5 sH5 H=r 1H5 H= 1fAWL HH AVH AUATUSHHXH|$ dH%(HD$H1HH*H5 D$jHHPH5 THHZH5 >HHTH5: (HHH5 HHHH5 HHH5 HHH5n HHH5 HH@H5 HHH5 HH$H5 xHHH5 bHH(H5 LHHH5 6HHlH5 HHH5X H3H5! HHI H. 8H5, HHIHsHHxKHSLIHH;uHHs@ LhH It HHxtLHLLHHHr(HtVVHb\HHB0HH@(IGH1LHLc@HHFLPAUj H HHHHKHE1ALjHIXZMyIwF #Ѓ 1H~ HEf.HHD$HD$HfDH\$,HHD$,~IHt@ HC LHHHD$,>IHt@H LHHHD$,IHt@ HLH{HHD$,IHt@LH\$0HH6fHH)D$0xIHt@ HuLHfHH)D$0D$?2IHt@H;LHLHdH\$H *HH5&HRH HHH55t$HiHD$HdH3%(u5HX[]A\A]A^A_HH58H1HH5HHHCouldn't add key '%s' to %%Socket::Usage: Socket::getnameinfo(addr, flags=0, xflags=0)ExtUtils::Constant::ProxySubs::MissingBad arg length for %s, length is %lu, should be %luBad address family for %s, got %d, should be %dBad arg length for %s, length is %lu, should be at least %luBad address family for %s, got %d, should be either AF_INET or AF_INET6Bad address length for Socket::inet_ntop on AF_INET; got %lu, should be 4Bad address length for Socket::inet_ntop on AF_INET6; got %lu, should be 16Your vendor has not defined Socket macro %-p, used at %s line %lu %-p is not a valid Socket macro at %s line %lu Usage: Socket::getaddrinfo(host, service, hints)Bad arg length %s, length is %lu, should be %lumultiaddr, source, interface=&PL_sv_undefmultiaddr, interface=&PL_sv_undefPath length (%lu) is longer than maximum supported length (%lu) and will be truncatedport_sv, sin6_addr, scope_id=0, flowinfo=0Couldn't add key '%s' to missing_hashSO_SECURITY_ENCRYPTION_NETWORKSO_SECURITY_ENCRYPTION_TRANSPORTaddr is not a stringSocketmreq_svSocket::unpack_ip_mreq_sourceSocket::unpack_ip_mreqsun_svSocket::unpack_sockaddr_unUndefined address for %ssockaddrSocket::sockaddr_familySocket::unpack_ipv6_mreqaf, hostSocket::inet_ptonaf, ip_address_svSocket::inet_ntopWide character in %ssin_svSocket::unpack_sockaddr_inSocket::inet_ntoa%d.%d.%d.%dsin6_svSocket::unpack_sockaddr_in6hints is not a HASH referenceflagssocktypeprotocolcanonnamemultiaddr, ifindexSocket::pack_ipv6_mreqSocket::pack_ip_mreq_sourceSocket::pack_ip_mreqpathnameSocket::pack_sockaddr_unUndefined path for %sSocket::pack_sockaddr_in6port_sv, ip_address_svSocket::pack_sockaddr_inAF_8022.027v5.26.0Socket.cSocket::AUTOLOADSocket::inet_atonSocket::INADDR_ANYINADDR_LOOPBACKINADDR_NONEINADDR_BROADCASTIN6ADDR_ANYIN6ADDR_LOOPBACKSocket.xsSocket::getaddrinfoSocket::getnameinfoAF_APPLETALKAF_DECnetAF_INETAF_INET6AF_KEYAF_MAXAF_ROUTEAF_SNAAF_UNIXAF_UNSPECAF_X25AI_ADDRCONFIGAI_ALLAI_CANONIDNAI_CANONNAMEAI_IDNAI_IDN_ALLOW_UNASSIGNEDAI_IDN_USE_STD3_ASCII_RULESAI_NUMERICHOSTAI_NUMERICSERVAI_PASSIVEAI_V4MAPPEDEAI_ADDRFAMILYEAI_AGAINEAI_BADFLAGSEAI_FAILEAI_FAMILYEAI_NODATAEAI_NONAMEEAI_SERVICEEAI_SOCKTYPEEAI_SYSTEMIOV_MAXIP_ADD_MEMBERSHIPIP_ADD_SOURCE_MEMBERSHIPIP_BIND_ADDRESS_NO_PORTIP_DROP_MEMBERSHIPIP_DROP_SOURCE_MEMBERSHIPIP_FREEBINDIP_HDRINCLIP_MULTICAST_ALLIP_MULTICAST_IFIP_MULTICAST_LOOPIP_MULTICAST_TTLIP_MTUIP_MTU_DISCOVERIP_NODEFRAGIP_OPTIONSIP_RECVERRIP_RECVOPTSIP_RECVRETOPTSIP_RETOPTSIP_TOSIP_TRANSPARENTIP_TTLIP_PMTUDISC_DOIP_PMTUDISC_DONTIP_PMTUDISC_PROBEIP_PMTUDISC_WANTIPTOS_LOWDELAYIPTOS_THROUGHPUTIPTOS_RELIABILITYIPTOS_MINCOSTIPV6_ADD_MEMBERSHIPIPV6_DROP_MEMBERSHIPIPV6_JOIN_GROUPIPV6_LEAVE_GROUPIPV6_MTUIPV6_MTU_DISCOVERIPV6_MULTICAST_HOPSIPV6_MULTICAST_IFIPV6_MULTICAST_LOOPIPV6_RECVERRIPV6_ROUTER_ALERTIPV6_UNICAST_HOPSIPV6_V6ONLYMSG_DONTWAITMSG_EORMSG_ERRQUEUEMSG_FASTOPENMSG_FINMSG_NOSIGNALMSG_RSTMSG_SYNMSG_TRUNCMSG_WAITALLNI_DGRAMNI_IDNNI_IDN_ALLOW_UNASSIGNEDNI_IDN_USE_STD3_ASCII_RULESNI_NAMEREQDNI_NOFQDNNI_NUMERICHOSTNI_NUMERICSERVPF_APPLETALKPF_DECnetPF_INETPF_INET6PF_KEYPF_MAXPF_ROUTEPF_SNAPF_UNIXPF_UNSPECPF_X25SCM_CREDENTIALSSCM_TIMESTAMPSOCK_DGRAMSOCK_RAWSOCK_RDMSOCK_SEQPACKETSOCK_STREAMSOCK_NONBLOCKSOCK_CLOEXECSOL_SOCKETSOMAXCONNSO_ACCEPTCONNSO_ATTACH_FILTERSO_BINDTODEVICESO_BROADCASTSO_BSDCOMPATSO_BUSY_POLLSO_DEBUGSO_DETACH_FILTERSO_DOMAINSO_DONTROUTESO_ERRORSO_KEEPALIVESO_LINGERSO_LOCK_FILTERSO_MARKSO_OOBINLINESO_PASSCREDSO_PEEK_OFFSO_PEERCREDSO_PRIORITYSO_PROTOCOLSO_RCVBUFSO_RCVBUFFORCESO_RCVLOWATSO_RCVTIMEOSO_REUSEADDRSO_REUSEPORTSO_RXQ_OVFLSO_SECURITY_AUTHENTICATIONSO_SNDBUFSO_SNDBUFFORCESO_SNDLOWATSO_SNDTIMEOSO_TIMESTAMPSO_TYPETCP_CONGESTIONTCP_CORKTCP_DEFER_ACCEPTTCP_FASTOPENTCP_INFOTCP_KEEPCNTTCP_KEEPIDLETCP_KEEPINTVLTCP_LINGER2TCP_MAXSEGTCP_MD5SIGTCP_NODELAYTCP_QUICKACKTCP_SYNCNTTCP_USER_TIMEOUTTCP_WINDOW_CLAMPUIO_MAXIOVIPPROTO_IPIPPROTO_IPV6IPPROTO_RAWIPPROTO_ICMPIPPROTO_IGMPIPPROTO_TCPIPPROTO_UDPIPPROTO_GREIPPROTO_ESPIPPROTO_AHIPPROTO_ICMPV6IPPROTO_SCTPSHUT_RDSHUT_WRSHUT_RDWRMSG_CTRUNCMSG_DONTROUTEMSG_OOBMSG_PEEKMSG_PROXYSCM_RIGHTSAF_AALAF_CCITTAF_CHAOSAF_CTFAF_DATAKITAF_DLIAF_ECMAAF_GOSIPAF_HYLINKAF_IMPLINKAF_ISOAF_LASTAF_LATAF_LINKAF_NBSAF_NITAF_NSAF_OSIAF_OSINETAF_PUPAF_USERAF_WANEAI_BADHINTSEAI_PROTOCOLIPV6_ADDRFROMMSG_BCASTMSG_BTAGMSG_CTLFLAGSMSG_CTLIGNOREMSG_EOFMSG_ETAGMSG_MAXIOVLENMSG_MCASTMSG_URGMSG_WIREPF_802PF_AALPF_CCITTPF_CHAOSPF_CTFPF_DATAKITPF_DLIPF_ECMAPF_GOSIPPF_HYLINKPF_IMPLINKPF_ISOPF_LASTPF_LATPF_LINKPF_NBSPF_NITPF_NSPF_OSIPF_OSINETPF_PUPPF_USERPF_WANSCM_CONNECTSCM_CREDSSO_BACKLOGSO_CHAMELEONSO_DGRAM_ERRINDSO_DONTLINGERSO_FAMILYSO_PASSIFNAMESO_PROTOTYPESO_STATESO_USELOOPBACKSO_XOPENSO_XSETCP_CONNECTIONTIMEOUTTCP_INIT_CWNDTCP_KEEPALIVETCP_MAXRTTCP_NOOPTTCP_NOPUSHTCP_SACK_ENABLETCP_STDURG; д8 d8lP,h`@@0$0h<xzRx $@FJ w?:*3$"D0X\BNB D(D0G8B@F8A0z (A BBBE P (I BBBA (zBDD y ABJ \HFBB B(A0A8G K K F D  8A0A(B BBBH @DAPD0I8H@[8A0Y AAC h AAF 04JFAA Gp  AABF 0PFAG D@   AABH 0fFAG D@  AABE 4$FAA MH  AABG 0\ FAA J0  AABK 0lfFAA JP  AABE HFBB B(A0A8G` 8A0A(B BBBF < tFBA A(J (A ABBD 8PL3FBA A(J`4 (A ABBB 0PFAA J0  AABG ,FAA w(K0B8B@I 8lFBA A(Jp (A ABBH ,TFBB B(A0A8DNUEaHWAPH_EIHfBIH`AvNVBzNVBzKXAtMVAe 8A0A(B BBBI 8 PFBA A(J` (A ABBC @HFBB A(A0JP 0A(A BBBE 8BFBA A(JP (A ABBD D%FBB A(A0M. 0A(A BBBA LFBB B(A0A8G 8A0A(B BBBH 8`l'FBA A(J`c (A ABBC p`FSI B(A0A8GYBBI`NLAw 8A0A(B BBBA GNU 32 q r rr r#r-*r3r:rBr Lr Sr arhr tr r@rrrrr r rs s s s +s 6s As Ms Zs esms#s'ss$s(s s s1t t"'t!8t?t Ot [t ft qt }tt ttttttttuu)u 7uKu`upuuuuuuu uuv v @ v(v 5v BvJv @Wv_vgv qv }vv v@vv v vvv w ww w$w-+w4w;wCw Mw Twdw rw }wwww w w w w w ww x x #x .0x9xJx 'Tx axjx wx x,x$x x x *x x x &x x!x y y y ,y (8y8nXn Sy ]y ly xy y yy yy y y y y y y  z z !z -z :z EzVz gz rz }z )z z z z z z /z 2z 3z:z {{{ !{ ,{ :{B{K{ U{ #q`{g{p{y{{ {{{{ { {{{{{{{{{ {| || | +| 9| C|L| Y| g|o|x| | |||||||| |||| | }}}}}%},}2}9} C}J}R}Y} e} o} z} }} } } } }}}}}~ ~ $~ .~ 8~ C~S~ U + $jД ؔ o(`   ' ( oox oo o , ,0,@,P,`,p,,,,,,,,,-- -0-@-P-`-p---------.. .0.@.P.`.p.........// /0/GA$3a1p2p2GA$3a1++GA$3a1$j,jGA$3a1p2)3 GA$3p86403!jGA$gcc 8.3.1 20190507 GA*GOWDGA*GA!stack_clashGA*cf_protectionGA+GLIBCXX_ASSERTIONS GA*FORTIFYGA*GA! GA* GA!stack_realign GA$3h864p2p2 GA$3h864p2p2GA$3a1!j!jGA$3a1!j!jGA$3a1++GA$3a1,j1jSocket.so-2.027-3.el8.x86_64.debugE 7zXZִF!t/5]?Eh=ڊ2N$)+MմBME4:"#я컁*ͦ[4:Cc&(SVVnC,U_:9A=:DxRu:pO&ۭTw$QA=38l>Ne 9k&< g){g 8O`qa2ҫDҏD)H-CE&S/}g$,V>?Jz.>)amW!Q7w6]F:Ee͂+ߕX猞؁6_˳xTMl0h;Bu)}E[%@U`^q aoK~ICB /U c& )BzF$1 +:׎c}u1-(bs;Tۺ I 9 B}neRK77m&Ra)>>f=׿,Y!9N Trvu?T|/ $ԛ &PyF EWPD5[^{ ू"#>ZS8zSof$cn_b8oC Xںq -S5?xE\便tiu=1+䎗Eݺaj/~,G@5|wv0=0 :W6XdZڱkZ~._t IOA-%WrM=eWYHcŠI=Cnhí뿩-~Ysf(04mh P,[;=*_j82!CP4i(›XiF_.sBJ6bf>s3tyK3ZMZƂqofGBß@-w\rIV&> ]ADT&fGFaeNNnew('www.google.com:443'); print $cl "GET / HTTP/1.0\r\n\r\n"; print <$cl>; # simple server my $srv = IO::Socket::SSL->new( LocalAddr => '0.0.0.0:1234', Listen => 10, SSL_cert_file => 'server-cert.pem', SSL_key_file => 'server-key.pem', ); $srv->accept; =head1 DESCRIPTION IO::Socket::SSL makes using SSL/TLS much easier by wrapping the necessary functionality into the familiar L interface and providing secure defaults whenever possible. This way, existing applications can be made SSL-aware without much effort, at least if you do blocking I/O and don't use select or poll. But, under the hood, SSL is a complex beast. So there are lots of methods to make it do what you need if the default behavior is not adequate. Because it is easy to inadvertently introduce critical security bugs or just hard to debug problems, I would recommend studying the following documentation carefully. The documentation consists of the following parts: =over 4 =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =item * L =back Additional documentation can be found in =over 4 =item * L - Doing Man-In-The-Middle with SSL =item * L - Useful functions for certificates etc =back =head1 Essential Information About SSL/TLS SSL (Secure Socket Layer) or its successor TLS (Transport Layer Security) are protocols to facilitate end-to-end security. These protocols are used when accessing web sites (https), delivering or retrieving email, and in lots of other use cases. In the following documentation we will refer to both SSL and TLS as simply 'SSL'. SSL enables end-to-end security by providing two essential functions: =over 4 =item Encryption This part encrypts the data for transit between the communicating parties, so that nobody in between can read them. It also provides tamper resistance so that nobody in between can manipulate the data. =item Identification This part makes sure that you talk to the right peer. If the identification is done incorrectly it is easy to mount man-in-the-middle attacks, e.g. if Alice wants to talk to Bob it would be possible for Mallory to put itself in the middle, so that Alice talks to Mallory and Mallory to Bob. All the data would still be encrypted, but not end-to-end between Alice and Bob, but only between Alice and Mallory and then between Mallory and Bob. Thus Mallory would be able to read and modify all traffic between Alice and Bob. =back Identification is the part which is the hardest to understand and the easiest to get wrong. With SSL, the Identification is usually done with B inside a B (Public Key Infrastructure). These Certificates are comparable to an identity card, which contains information about the owner of the card. The card then is somehow B by the B of the card, the B (Certificate Agency). To verify the identity of the peer the following must be done inside SSL: =over 4 =item * Get the certificate from the peer. If the peer does not present a certificate we cannot verify it. =item * Check if we trust the certificate, e.g. make sure it's not a forgery. We believe that a certificate is not a fake if we either know the certificate already or if we B the issuer (the CA) and can verify the issuers signature on the certificate. In reality there is often a hierarchy of certificate agencies and we only directly trust the root of this hierarchy. In this case the peer not only sends his own certificate, but also all B. Verification will be done by building a B from the trusted root up to the peers certificate and checking in each step if the we can verify the issuer's signature. This step often causes problems because the client does not know the necessary trusted root certificates. These are usually stored in a system dependent CA store, but often the browsers have their own CA store. =item * Check if the certificate is still valid. Each certificate has a lifetime and should not be used after that time because it might be compromised or the underlying cryptography got broken in the mean time. =item * Check if the subject of the certificate matches the peer. This is like comparing the picture on the identity card against the person representing the identity card. When connecting to a server this is usually done by comparing the hostname used for connecting against the names represented in the certificate. A certificate might contain multiple names or wildcards, so that it can be used for multiple hosts (e.g. *.example.com and *.example.org). Although nobody sane would accept an identity card where the picture does not match the person we see, it is a common implementation error with SSL to omit this check or get it wrong. =item * Check if the certificate was revoked by the issuer. This might be the case if the certificate was compromised somehow and now somebody else might use it to claim the wrong identity. Such revocations happened a lot after the heartbleed attack. For SSL there are two ways to verify a revocation, CRL and OCSP. With CRLs (Certificate Revocation List) the CA provides a list of serial numbers for revoked certificates. The client somehow has to download the list (which can be huge) and keep it up to date. With OCSP (Online Certificate Status Protocol) the client can check a single certificate directly by asking the issuer. Revocation is the hardest part of the verification and none of today's browsers get it fully correct. But, they are still better than most other implementations which don't implement revocation checks or leave the hard parts to the developer. =back When accessing a web site with SSL or delivering mail in a secure way the identity is usually only checked one way, e.g. the client wants to make sure it talks to the right server, but the server usually does not care which client it talks to. But, sometimes the server wants to identify the client too and will request a certificate from the client which the server must verify in a similar way. =head1 Basic SSL Client A basic SSL client is simple: my $client = IO::Socket::SSL->new('www.example.com:443') or die "error=$!, ssl_error=$SSL_ERROR"; This will take the OpenSSL default CA store as the store for the trusted CA. This usually works on UNIX systems. If there are no certificates in the store it will try use L which provides the default CAs of Firefox. In the default settings, L will use a safer cipher set and SSL version, do a proper hostname check against the certificate, and use SNI (server name indication) to send the hostname inside the SSL handshake. This is necessary to work with servers which have different certificates behind the same IP address. It will also check the revocation of the certificate with OCSP, but currently only if the server provides OCSP stapling (for deeper checks see C method). Lots of options can be used to change ciphers, SSL version, location of CA and much more. See documentation of methods for details. With protocols like SMTP it is necessary to upgrade an existing socket to SSL. This can be done like this: my $client = IO::Socket::INET->new('mx.example.com:25') or die $!; # .. read greeting from server # .. send EHLO and read response # .. send STARTTLS command and read response # .. if response was successful we can upgrade the socket to SSL now: IO::Socket::SSL->start_SSL($client, # explicitly set hostname we should use for SNI SSL_hostname => 'mx.example.com' ) or die $SSL_ERROR; A more complete example for a simple HTTP client: my $client = IO::Socket::SSL->new( # where to connect PeerHost => "www.example.com", PeerPort => "https", # certificate verification - VERIFY_PEER is default SSL_verify_mode => SSL_VERIFY_PEER, # location of CA store # need only be given if default store should not be used SSL_ca_path => '/etc/ssl/certs', # typical CA path on Linux SSL_ca_file => '/etc/ssl/cert.pem', # typical CA file on BSD # or just use default path on system: IO::Socket::SSL::default_ca(), # either explicitly # or implicitly by not giving SSL_ca_* # easy hostname verification # It will use PeerHost as default name a verification # scheme as default, which is safe enough for most purposes. SSL_verifycn_name => 'foo.bar', SSL_verifycn_scheme => 'http', # SNI support - defaults to PeerHost SSL_hostname => 'foo.bar', ) or die "failed connect or ssl handshake: $!,$SSL_ERROR"; # send and receive over SSL connection print $client "GET / HTTP/1.0\r\n\r\n"; print <$client>; And to do revocation checks with OCSP (only available with OpenSSL 1.0.0 or higher and L 1.59 or higher): # default will try OCSP stapling and check only leaf certificate my $client = IO::Socket::SSL->new($dst); # better yet: require checking of full chain my $client = IO::Socket::SSL->new( PeerAddr => $dst, SSL_ocsp_mode => SSL_OCSP_FULL_CHAIN, ); # even better: make OCSP errors fatal # (this will probably fail with lots of sites because of bad OCSP setups) # also use common OCSP response cache my $ocsp_cache = IO::Socket::SSL::OCSP_Cache->new; my $client = IO::Socket::SSL->new( PeerAddr => $dst, SSL_ocsp_mode => SSL_OCSP_FULL_CHAIN|SSL_OCSP_FAIL_HARD, SSL_ocsp_cache => $ocsp_cache, ); # disable OCSP stapling in case server has problems with it my $client = IO::Socket::SSL->new( PeerAddr => $dst, SSL_ocsp_mode => SSL_OCSP_NO_STAPLE, ); # check any certificates which are not yet checked by OCSP stapling or # where we have already cached results. For your own resolving combine # $ocsp->requests with $ocsp->add_response(uri,response). my $ocsp = $client->ocsp_resolver(); my $errors = $ocsp->resolve_blocking(); if ($errors) { warn "OCSP verification failed: $errors"; close($client); } =head1 Basic SSL Server A basic SSL server looks similar to other L servers, only that it also contains settings for certificate and key: # simple server my $server = IO::Socket::SSL->new( # where to listen LocalAddr => '127.0.0.1', LocalPort => 8080, Listen => 10, # which certificate to offer # with SNI support there can be different certificates per hostname SSL_cert_file => 'cert.pem', SSL_key_file => 'key.pem', ) or die "failed to listen: $!"; # accept client my $client = $server->accept or die "failed to accept or ssl handshake: $!,$SSL_ERROR"; This will automatically use a secure set of ciphers and SSL version and also supports Forward Secrecy with (Elliptic-Curve) Diffie-Hellmann Key Exchange. If you are doing a forking or threading server, we recommend that you do the SSL handshake inside the new process/thread so that the master is free for new connections. We recommend this because a client with improper or slow SSL handshake could make the server block in the handshake which would be bad to do on the listening socket: # inet server my $server = IO::Socket::INET->new( # where to listen LocalAddr => '127.0.0.1', LocalPort => 8080, Listen => 10, ); # accept client my $client = $server->accept or die; # SSL upgrade client (in new process/thread) IO::Socket::SSL->start_SSL($client, SSL_server => 1, SSL_cert_file => 'cert.pem', SSL_key_file => 'key.pem', ) or die "failed to ssl handshake: $SSL_ERROR"; Like with normal sockets, neither forking nor threading servers scale well. It is recommended to use non-blocking sockets instead, see L =head1 Common Usage Errors This is a list of typical errors seen with the use of L: =over 4 =item * Disabling verification with C. As described in L, a proper identification of the peer is essential and failing to verify makes Man-In-The-Middle attacks possible. Nevertheless, lots of scripts and even public modules or applications disable verification, because it is probably the easiest way to make the thing work and usually nobody notices any security problems anyway. If the verification does not succeed with the default settings, one can do the following: =over 8 =item * Make sure the needed CAs are in the store, maybe use C or C to specify a different CA store. =item * If the validation fails because the certificate is self-signed and that's what you expect, you can use the C option to accept specific leaf certificates by their certificate or pubkey fingerprint. =item * If the validation failed because the hostname does not match and you cannot access the host with the name given in the certificate, you can use C to specify the hostname you expect in the certificate. =back A common error pattern is also to disable verification if they found no CA store (different modules look at different "default" places). Because L is now able to provide a usable CA store on most platforms (UNIX, Mac OSX and Windows) it is better to use the defaults provided by L. If necessary these can be checked with the C method. =item * Polling of SSL sockets (e.g. select, poll and other event loops). If you sysread one byte on a normal socket it will result in a syscall to read one byte. Thus, if more than one byte is available on the socket it will be kept in the network stack of your OS and the next select or poll call will return the socket as readable. But, with SSL you don't deliver single bytes. Multiple data bytes are packaged and encrypted together in an SSL frame. Decryption can only be done on the whole frame, so a sysread for one byte actually reads the complete SSL frame from the socket, decrypts it and returns the first decrypted byte. Further sysreads will return more bytes from the same frame until all bytes are returned and the next SSL frame will be read from the socket. Thus, in order to decide if you can read more data (e.g. if sysread will block) you must check if there are still data in the current SSL frame by calling C and if there are no data pending you might check the underlying socket with select or poll. Another way might be if you try to sysread at least 16kByte all the time. 16kByte is the maximum size of an SSL frame and because sysread returns data from only a single SSL frame you can guarantee that there are no pending data. See also L. =item * Expecting exactly the same behavior as plain sockets. IO::Socket::SSL tries to emulate the usual socket behavior as good as possible, but full emulation can not be done. Specifically a read on the SSL socket might also result in a write on the TCP socket or a write on the SSL socket might result in a read on the TCP socket. Also C and B on the SSL socket will result in writing and reading data to the TCP socket too. Especially the hidden writes might result in a connection reset if the underlying TCP socket is already closed by the peer. Unless signal PIPE is explicitly handled by the application this will ususally result in the application crashing. It is thus recommended to explicitly IGNORE signal PIPE so that the errors get propagated as EPIPE instead of causing a crash of the application. =item * Set 'SSL_version' or 'SSL_cipher_list' to a "better" value. L tries to set these values to reasonable, secure values which are compatible with the rest of the world. But, there are some scripts or modules out there which tried to be smart and get more secure or compatible settings. Unfortunately, they did this years ago and never updated these values, so they are still forced to do only 'TLSv1' (instead of also using TLSv12 or TLSv11). Or they set 'HIGH' as the cipher list and thought they were secure, but did not notice that 'HIGH' includes anonymous ciphers, e.g. without identification of the peer. So it is recommended to leave the settings at the secure defaults which L sets and which get updated from time to time to better fit the real world. =item * Make SSL settings inaccessible by the user, together with bad builtin settings. Some modules use L, but don't make the SSL settings available to the user. This is often combined with bad builtin settings or defaults (like switching verification off). Thus the user needs to hack around these restrictions by using C or similar. =item * Use of constants as strings. Constants like C or C should be used as constants and not be put inside quotes, because they represent numerical values. =item * Forking and handling the socket in parent and child. A B of the process will duplicate the internal user space SSL state of the socket. If both master and child interact with the socket by using their own SSL state strange error messages will happen. Such interaction includes explicit or implicit B of the SSL socket. To avoid this the socket should be explicitly closed with B. =item * Forking and executing a new process. Since the SSL state is stored in user space it will be duplicated by a B but it will be lost when doing B. This means it is not possible to simply redirect stdin and stdout for the new process to the SSL socket by duplicating the relevant file handles. Instead explicitly exchanging plain data between child-process and SSL socket are needed. =back =head1 Common Problems with SSL SSL is a complex protocol with multiple implementations and each of these has their own quirks. While most of these implementations work together, it often gets problematic with older versions, minimal versions in load balancers, or plain wrong setups. Unfortunately these problems are hard to debug. Helpful for debugging are a knowledge of SSL internals, wireshark and the use of the debug settings of L and L, which can both be set with C<$IO::Socket::SSL::DEBUG>. The following debugs levels are defined, but used not in any consistent way: =over 4 =item * 0 - No debugging (default). =item * 1 - Print out errors from L and ciphers from L. =item * 2 - Print also information about call flow from L and progress information from L. =item * 3 - Print also some data dumps from L and from L. =back Also, C from the ssl-tools repository at L might be a helpful tool when debugging SSL problems, as do the C command line tool and a check with a different SSL implementation (e.g. a web browser). The following problems are not uncommon: =over 4 =item * Bad server setup: missing intermediate certificates. It is a regular problem that administrators fail to include all necessary certificates into their server setup, e.g. everything needed to build the trust chain from the trusted root. If they check the setup with the browser everything looks ok, because browsers work around these problems by caching any intermediate certificates and apply them to new connections if certificates are missing. But, fresh browser profiles which have never seen these intermediates cannot fill in the missing certificates and fail to verify; the same is true with L. =item * Old versions of servers or load balancers which do not understand specific TLS versions or croak on specific data. From time to time one encounters an SSL peer, which just closes the connection inside the SSL handshake. This can usually be worked around by downgrading the SSL version, e.g. by setting C. Modern Browsers usually deal with such servers by automatically downgrading the SSL version and repeat the connection attempt until they succeed. Worse servers do not close the underlying TCP connection but instead just drop the relevant packet. This is harder to detect because it looks like a stalled connection. But downgrading the SSL version often works here too. A cause of such problems are often load balancers or security devices, which have hardware acceleration and only a minimal (and less robust) SSL stack. They can often be detected because they support much fewer ciphers than other implementations. =item * Bad or old OpenSSL versions. L uses OpenSSL with the help of the L library. It is recommend to have a recent version of this library, because it has more features and usually fewer known bugs. =item * Validation of client certificates fail. Make sure that the purpose of the certificate allows use as ssl client (check with C<< openssl x509 -purpose >>, that the necessary root certificate is in the path specified by C (or the default path) and that any intermediate certificates needed to build the trust chain are sent by the client. =item * Validation of self-signed certificate fails even if it is given with C argument. The C arguments do not give a general trust store for arbitrary certificates but only specify a store for CA certificates which then can be used to verify other certificates. This especially means that certificates which are not a CA get simply ignored, notably self-signed certificates which do not also have the CA-flag set. This behavior of OpenSSL differs from the more general trust-store concept which can be found in browsers and where it is possible to simply added arbitrary certificates (CA or not) as trusted. =back =head1 Using Non-Blocking Sockets If you have a non-blocking socket, the expected behavior on read, write, accept or connect is to set C<$!> to EWOULDBLOCK if the operation cannot be completed immediately. Note that EWOULDBLOCK is the same as EAGAIN on UNIX systems, but is different on Windows. With SSL, handshakes might occur at any time, even within an established connection. In these cases it is necessary to finish the handshake before you can read or write data. This might result in situations where you want to read but must first finish the write of a handshake or where you want to write but must first finish a read. In these cases C<$!> is set to EAGAIN like expected, and additionally C<$SSL_ERROR> is set to either SSL_WANT_READ or SSL_WANT_WRITE. Thus if you get EWOULDBLOCK on a SSL socket you must check C<$SSL_ERROR> for SSL_WANT_* and adapt your event mask accordingly. Using readline on non-blocking sockets does not make much sense and I would advise against using it. And, while the behavior is not documented for other L classes, it will try to emulate the behavior seen there, e.g. to return the received data instead of blocking, even if the line is not complete. If an unrecoverable error occurs it will return nothing, even if it already received some data. Also, I would advise against using C with a non-blocking SSL object because it might block and this is not what most would expect. The reason for this is that C on a non-blocking TCP socket (e.g. L, L..) results in a new TCP socket which does not inherit the non-blocking behavior of the master socket. And thus, the initial SSL handshake on the new socket inside C will be done in a blocking way. To work around this you are safer by doing a TCP accept and later upgrade the TCP socket in a non-blocking way with C and C. my $cl = IO::Socket::SSL->new($dst); $cl->blocking(0); my $sel = IO::Select->new($cl); while (1) { # with SSL a call for reading n bytes does not result in reading of n # bytes from the socket, but instead it must read at least one full SSL # frame. If the socket has no new bytes, but there are unprocessed data # from the SSL frame can_read will block! # wait for data on socket $sel->can_read(); # new data on socket or eof READ: # this does not read only 1 byte from socket, but reads the complete SSL # frame and then just returns one byte. On subsequent calls it than # returns more byte of the same SSL frame until it needs to read the # next frame. my $n = sysread( $cl,my $buf,1); if ( ! defined $n ) { die $! if not ${EWOULDBLOCK}; next if $SSL_ERROR == SSL_WANT_READ; if ( $SSL_ERROR == SSL_WANT_WRITE ) { # need to write data on renegotiation $sel->can_write; next; } die "something went wrong: $SSL_ERROR"; } elsif ( ! $n ) { last; # eof } else { # read next bytes # we might have still data within the current SSL frame # thus first process these data instead of waiting on the underlying # socket object goto READ if $cl->pending; # goto sysread next; # goto $sel->can_read } } Additionally there are differences to plain sockets when using select, poll, kqueue or similar technologies to get notified if data are available. Relying only on these calls is not sufficient in all cases since unread data might be internally buffered in the SSL stack. To detect such buffering B need to be used. Alternatively the buffering can be avoided by using B with the maximum size of an SSL frame. See L for details. =head1 Advanced Usage =head2 SNI Support Newer extensions to SSL can distinguish between multiple hostnames on the same IP address using Server Name Indication (SNI). Support for SNI on the client side was added somewhere in the OpenSSL 0.9.8 series, but with 1.0 a bug was fixed when the server could not decide about its hostname. Therefore client side SNI is only supported with OpenSSL 1.0 or higher in L. With a supported version, SNI is used automatically on the client side, if it can determine the hostname from C or C (which are synonyms in the underlying IO::Socket:: classes and thus should never be set both or at least not to different values). On unsupported OpenSSL versions it will silently not use SNI. The hostname can also be given explicitly given with C, but in this case it will throw in error, if SNI is not supported. To check for support you might call C<< IO::Socket::SSL->can_client_sni() >>. On the server side, earlier versions of OpenSSL are supported, but only together with L version >= 1.50. To check for support you might call C<< IO::Socket::SSL->can_server_sni() >>. If server side SNI is supported, you might specify different certificates per host with C and C, and check the requested name using C. =head2 Talk Plain and SSL With The Same Socket It is often required to first exchange some plain data and then upgrade the socket to SSL after some kind of STARTTLS command. Protocols like FTPS even need a way to downgrade the socket again back to plain. The common way to do this would be to create a normal socket and use C to upgrade and stop_SSL to downgrade: my $sock = IO::Socket::INET->new(...) or die $!; ... exchange plain data on $sock until starttls command ... IO::Socket::SSL->start_SSL($sock,%sslargs) or die $SSL_ERROR; ... now $sock is an IO::Socket::SSL object ... ... exchange data with SSL on $sock until stoptls command ... $sock->stop_SSL or die $SSL_ERROR; ... now $sock is again an IO::Socket::INET object ... But, lots of modules just derive directly from L. While this base class can be replaced with L, these modules cannot easily support different base classes for SSL and plain data and switch between these classes on a starttls command. To help in this case, L can be reduced to a plain socket on startup, and connect_SSL/accept_SSL/start_SSL can be used to enable SSL and C to talk plain again: my $sock = IO::Socket::SSL->new( PeerAddr => ... SSL_startHandshake => 0, %sslargs ) or die $!; ... exchange plain data on $sock until starttls command ... $sock->connect_SSL or die $SSL_ERROR; ... now $sock is an IO::Socket::SSL object ... ... exchange data with SSL on $sock until stoptls command ... $sock->stop_SSL or die $SSL_ERROR; ... $sock is still an IO::Socket::SSL object ... ... but data exchanged again in plain ... =head1 Integration Into Own Modules L behaves similarly to other L modules and thus could be integrated in the same way, but you have to take special care when using non-blocking I/O (like for handling timeouts) or using select or poll. Please study the documentation on how to deal with these differences. Also, it is recommended to not set or touch most of the C options, so that they keep their secure defaults. It is also recommended to let the user override these SSL specific settings without the need of global settings or hacks like C. The notable exception is C. This should be set to the hostname verification scheme required by the module or protocol. =head1 Description Of Methods L inherits from another L module. The choice of the super class depends on the installed modules: =over 4 =item * If L with at least version 0.20 is installed it will use this module as super class, transparently providing IPv6 and IPv4 support. =item * If L is installed it will use this module as super class, transparently providing IPv6 and IPv4 support. =item * Otherwise it will fall back to L, which is a perl core module. With L you only get IPv4 support. =back Please be aware that with the IPv6 capable super classes, it will look first for the IPv6 address of a given hostname. If the resolver provides an IPv6 address, but the host cannot be reached by IPv6, there will be no automatic fallback to IPv4. To avoid these problems you can enforce IPv4 for a specific socket by using the C or C option with the value AF_INET as described in L. Alternatively you can enforce IPv4 globally by loading L with the option 'inet4', in which case it will use the IPv4 only class L as the super class. L will provide all of the methods of its super class, but sometimes it will override them to match the behavior expected from SSL or to provide additional arguments. The new or changed methods are described below, but please also read the section about SSL specific error handling. =over 4 =item Error Handling If an SSL specific error occurs, the global variable C<$SSL_ERROR> will be set. If the error occurred on an existing SSL socket, the method C will give access to the latest socket specific error. Both C<$SSL_ERROR> and the C method give a dualvar similar to C<$!>, e.g. providing an error number in numeric context or an error description in string context. =item B Creates a new L object. You may use all the friendly options that came bundled with the super class (e.g. L, L, ...) plus (optionally) the ones described below. If you don't specify any SSL related options it will do its best in using secure defaults, e.g. choosing good ciphers, enabling proper verification, etc. =over 2 =item SSL_server Set this option to a true value if the socket should be used as a server. If this is not explicitly set it is assumed if the C parameter is given when creating the socket. =item SSL_hostname This can be given to specify the hostname used for SNI, which is needed if you have multiple SSL hostnames on the same IP address. If not given it will try to determine the hostname from C, which will fail if only an IP was given or if this argument is used within C. If you want to disable SNI, set this argument to ''. Currently only supported for the client side and will be ignored for the server side. See section "SNI Support" for details of SNI the support. =item SSL_startHandshake If this option is set to false (defaults to true) it will not start the SSL handshake yet. This has to be done later with C or C. Before the handshake is started read/write/etc. can be used to exchange plain data. =item SSL_keepSocketOnError If this option is set to true (defaults to false) it will not close the underlying TCP socket on errors. In most cases there is no real use for this behavior since both sides of the TCP connection will probably have a different idea of the current state of the connection. =item SSL_ca | SSL_ca_file | SSL_ca_path Usually you want to verify that the peer certificate has been signed by a trusted certificate authority. In this case you should use this option to specify the file (C) or directory (C) containing the certificateZ<>(s) of the trusted certificate authorities. C can also be an array or a string containing multiple path, where the path are separated by the platform specific separator. This separator is C<;> on DOS, Windows, Netware, C<,> on VMS and C<:> for all the other systems. If multiple path are given at least one of these must be accessible. You can also give a list of X509* certificate handles (like you get from L or L) with C. These will be added to the CA store before path and file and thus take precedence. If neither SSL_ca, nor SSL_ca_file or SSL_ca_path are set it will use C to determine the user-set or system defaults. If you really don't want to set a CA set SSL_ca_file or SSL_ca_path to C<\undef> or SSL_ca to an empty list. (unfortunately C<''> is used by some modules using L when CA is not explicitly given). =item SSL_client_ca | SSL_client_ca_file If verify_mode is VERIFY_PEER on the server side these options can be used to set the list of acceptable CAs for the client. This way the client can select they required certificate from a list of certificates. The value for these options is similar to C and C. =item SSL_fingerprint Sometimes you have a self-signed certificate or a certificate issued by an unknown CA and you really want to accept it, but don't want to disable verification at all. In this case you can specify the fingerprint of the certificate as C<'algo$hex_fingerprint'>. C is a fingerprint algorithm supported by OpenSSL, e.g. 'sha1','sha256'... and C is the hexadecimal representation of the binary fingerprint. Any colons inside the hex string will be ignored. If you want to use the fingerprint of the pubkey inside the certificate instead of the certificate use the syntax C<'algo$pub$hex_fingerprint'> instead. To get the fingerprint of an established connection you can use C. It is also possible to skip C, i.e. only specifiy the fingerprint. In this case the likely algorithms will be automatically detected based on the length of the digest string. You can specify a list of fingerprints in case you have several acceptable certificates. If a fingerprint matches the topmost (i.e. leaf) certificate no additional validations can make the verification fail. =item SSL_cert_file | SSL_cert | SSL_key_file | SSL_key If you create a server you usually need to specify a server certificate which should be verified by the client. Same is true for client certificates, which should be verified by the server. The certificate can be given as a file with SSL_cert_file or as an internal representation of an X509* object (like you get from L or L) with SSL_cert. If given as a file it will automatically detect the format. Supported file formats are PEM, DER and PKCS#12, where PEM and PKCS#12 can contain the certificate and the chain to use, while DER can only contain a single certificate. If given as a list of X509* please note, that the all the chain certificates (e.g. all except the first) will be "consumed" by openssl and will be freed if the SSL context gets destroyed - so you should never free them yourself. But the servers certificate (e.g. the first) will not be consumed by openssl and thus must be freed by the application. For each certificate a key is need, which can either be given as a file with SSL_key_file or as an internal representation of an EVP_PKEY* object with SSL_key (like you get from L or L). If a key was already given within the PKCS#12 file specified by SSL_cert_file it will ignore any SSL_key or SSL_key_file. If no SSL_key or SSL_key_file was given it will try to use the PEM file given with SSL_cert_file again, maybe it contains the key too. If your SSL server should be able to use different certificates on the same IP address, depending on the name given by SNI, you can use a hash reference instead of a file with C< cert_file>>. If your SSL server should be able to use both RSA and ECDSA certificates for the same domain/IP a similar hash reference like with SNI is given. The domain names used to specify the additional certificates should be C, i.e. C or similar. This needs at least OpenSSL 1.0.2. To let the server pick the certificate based on the clients cipher preference C should be set to false. In case certs and keys are needed but not given it might fall back to builtin defaults, see "Defaults for Cert, Key and CA". Examples: SSL_cert_file => 'mycert.pem', SSL_key_file => 'mykey.pem', SSL_cert_file => { "foo.example.org" => 'foo-cert.pem', "foo.example.org%ecc" => 'foo-ecc-cert.pem', "bar.example.org" => 'bar-cert.pem', # used when nothing matches or client does not support SNI '' => 'default-cert.pem', '%ecc' => 'default-ecc-cert.pem', }, SSL_key_file => { "foo.example.org" => 'foo-key.pem', "foo.example.org%ecc" => 'foo-ecc-key.pem', "bar.example.org" => 'bar-key.pem', # used when nothing matches or client does not support SNI '' => 'default-key.pem', '%ecc' => 'default-ecc-key.pem', } =item SSL_passwd_cb If your private key is encrypted, you might not want the default password prompt from Net::SSLeay. This option takes a reference to a subroutine that should return the password required to decrypt your private key. =item SSL_use_cert If this is true, it forces IO::Socket::SSL to use a certificate and key, even if you are setting up an SSL client. If this is set to 0 (the default), then you will only need a certificate and key if you are setting up a server. SSL_use_cert will implicitly be set if SSL_server is set. For convenience it is also set if it was not given but a cert was given for use (SSL_cert_file or similar). =item SSL_version Sets the version of the SSL protocol used to transmit data. 'SSLv23' uses a handshake compatible with SSL2.0, SSL3.0 and TLS1.x, while 'SSLv2', 'SSLv3', 'TLSv1', 'TLSv1_1', 'TLSv1_2', or 'TLSv1_3' restrict handshake and protocol to the specified version. All values are case-insensitive. Instead of 'TLSv1_1', 'TLSv1_2', and 'TLSv1_3' one can also use 'TLSv11', 'TLSv12', and 'TLSv13'. Support for 'TLSv1_1', 'TLSv1_2', and 'TLSv1_3' requires recent versions of Net::SSLeay and openssl. The default SSL_version is defined by the underlying cryptographic library. Independent from the handshake format you can limit to set of accepted SSL versions by adding !version separated by ':'. For example, 'SSLv23:!SSLv3:!SSLv2' means that the handshake format is compatible to SSL2.0 and higher, but that the successful handshake is limited to TLS1.0 and higher, that is no SSL2.0 or SSL3.0 because both of these versions have serious security issues and should not be used anymore. You can also use !TLSv1_1 and !TLSv1_2 to disable TLS versions 1.1 and 1.2 while still allowing TLS version 1.0. Setting the version instead to 'TLSv1' might break interaction with older clients, which need and SSL2.0 compatible handshake. On the other side some clients just close the connection when they receive a TLS version 1.1 request. In this case setting the version to 'SSLv23:!SSLv2:!SSLv3:!TLSv1_1:!TLSv1_2' might help. =item SSL_cipher_list If this option is set the cipher list for the connection will be set to the given value, e.g. something like 'ALL:!LOW:!EXP:!aNULL'. Look into the OpenSSL documentation (L) for more details. Unless you fail to contact your peer because of no shared ciphers it is recommended to leave this option at the default setting, which honors the system-wide PROFILE=SYSTEM cipher list. In case different cipher lists are needed for different SNI hosts a hash can be given with the host as key and the cipher suite as value, similar to B. =item SSL_honor_cipher_order If this option is true the cipher order the server specified is used instead of the order proposed by the client. This option defaults to true to make use of our secure cipher list setting. =item SSL_dh_file To create a server which provides forward secrecy you need to either give the DH parameters or (better, because faster) the ECDH curve. This setting cares about DH parameters. To support non-elliptic Diffie-Hellman key exchange a suitable file needs to be given here or the SSL_dh should be used with a appropriate value. See dhparam command in openssl for more information. If neither C nor C are set a builtin DH parameter with a length of 2048 bit is used to offer DH key exchange by default. If you don't want this (e.g. disable DH key exchange) explicitly set this or the C parameter to undef. =item SSL_dh Like SSL_dh_file, but instead of giving a file you use a preloaded or generated DH*. =item SSL_ecdh_curve To create a server which provides forward secrecy you need to either give the DH parameters or (better, because faster) the ECDH curve. This setting cares about the ECDH curve(s). To support Elliptic Curve Diffie-Hellmann key exchange the OID or NID of at least one suitable curve needs to be provided here. With OpenSSL 1.1.0+ this parameter defaults to C, which means that it lets OpenSSL pick the best settings. If support for CTX_set_ecdh_auto is implemented in Net::SSLeay (needs at least version 1.86) it will use this to implement the same default. Otherwise it will default to C (builtin of OpenSSL) in order to offer ECDH key exchange by default. If setting groups or curves is supported by Net::SSLeay (needs at least version 1.86) then multiple curves can be given here in the order of the preference, i.e. C. When used at the client side this will include the supported curves as extension in the TLS handshake. If you don't want to have ECDH key exchange this could be set to undef or set C to exclude all of these ciphers. You can check if ECDH support is available by calling C<< IO::Socket::SSL->can_ecdh >>. =item SSL_verify_mode This option sets the verification mode for the peer certificate. You may combine SSL_VERIFY_PEER (verify_peer), SSL_VERIFY_FAIL_IF_NO_PEER_CERT (fail verification if no peer certificate exists; ignored for clients), SSL_VERIFY_CLIENT_ONCE (verify client once; ignored for clients). See OpenSSL man page for SSL_CTX_set_verify for more information. The default is SSL_VERIFY_NONE for server (e.g. no check for client certificate) and SSL_VERIFY_PEER for client (check server certificate). =item SSL_verify_callback If you want to verify certificates yourself, you can pass a sub reference along with this parameter to do so. When the callback is called, it will be passed: =over 4 =item 1. a true/false value that indicates what OpenSSL thinks of the certificate, =item 2. a C-style memory address of the certificate store, =item 3. a string containing the certificate's issuer attributes and owner attributes, and =item 4. a string containing any errors encountered (0 if no errors). =item 5. a C-style memory address of the peer's own certificate (convertible to PEM form with Net::SSLeay::PEM_get_string_X509()). =item 6. The depth of the certificate in the chain. Depth 0 is the leaf certificate. =back The function should return 1 or 0, depending on whether it thinks the certificate is valid or invalid. The default is to let OpenSSL do all of the busy work. The callback will be called for each element in the certificate chain. See the OpenSSL documentation for SSL_CTX_set_verify for more information. =item SSL_verifycn_scheme The scheme is used to correctly verify the identity inside the certificate by using the hostname of the peer. See the information about the verification schemes in B. If you don't specify a scheme it will use 'default', but only complain loudly if the name verification fails instead of letting the whole certificate verification fail. THIS WILL CHANGE, e.g. it will let the certificate verification fail in the future if the hostname does not match the certificate !!!! To override the name used in verification use B. The scheme 'default' is a superset of the usual schemes, which will accept the hostname in common name and subjectAltName and allow wildcards everywhere. While using this scheme is way more secure than no name verification at all you better should use the scheme specific to your application protocol, e.g. 'http', 'ftp'... If you are really sure, that you don't want to verify the identity using the hostname you can use 'none' as a scheme. In this case you'd better have alternative forms of verification, like a certificate fingerprint or do a manual verification later by calling B yourself. =item SSL_verifycn_publicsuffix This option is used to specify the behavior when checking wildcards certificates for public suffixes, e.g. no wildcard certificates for *.com or *.co.uk should be accepted, while *.example.com or *.example.co.uk is ok. If not specified it will simply use the builtin default of L, you can create another object with from_string or from_file of this module. To disable verification of public suffix set this option to C<''>. =item SSL_verifycn_name Set the name which is used in verification of hostname. If SSL_verifycn_scheme is set and no SSL_verifycn_name is given it will try to use SSL_hostname or PeerHost and PeerAddr settings and fail if no name can be determined. If SSL_verifycn_scheme is not set it will use a default scheme and warn if it cannot determine a hostname, but it will not fail. Using PeerHost or PeerAddr works only if you create the connection directly with C<< IO::Socket::SSL->new >>, if an IO::Socket::INET object is upgraded with B the name has to be given in B or B. =item SSL_check_crl If you want to verify that the peer certificate has not been revoked by the signing authority, set this value to true. OpenSSL will search for the CRL in your SSL_ca_path, or use the file specified by SSL_crl_file. See the Net::SSLeay documentation for more details. Note that this functionality appears to be broken with OpenSSL < v0.9.7b, so its use with lower versions will result in an error. =item SSL_crl_file If you want to specify the CRL file to be used, set this value to the pathname to be used. This must be used in addition to setting SSL_check_crl. =item SSL_ocsp_mode Defines how certificate revocation is done using OCSP (Online Status Revocation Protocol). The default is to send a request for OCSP stapling to the server and if the server sends an OCSP response back the result will be used. Any other OCSP checking needs to be done manually with C. The following flags can be combined with C<|>: =over 8 =item SSL_OCSP_NO_STAPLE Don't ask for OCSP stapling. This is the default if SSL_verify_mode is VERIFY_NONE. =item SSL_OCSP_TRY_STAPLE Try OCSP stapling, but don't complain if it gets no stapled response back. This is the default if SSL_verify_mode is VERIFY_PEER (the default). =item SSL_OCSP_MUST_STAPLE Consider it a hard error, if the server does not send a stapled OCSP response back. Most servers currently send no stapled OCSP response back. =item SSL_OCSP_FAIL_HARD Fail hard on response errors, default is to fail soft like the browsers do. Soft errors mean, that the OCSP response is not usable, e.g. no response, error response, no valid signature etc. Certificate revocations inside a verified response are considered hard errors in any case. Soft errors inside a stapled response are never considered hard, e.g. it is expected that in this case an OCSP request will be send to the responsible OCSP responder. =item SSL_OCSP_FULL_CHAIN This will set up the C so that all certificates from the peer chain will be checked, otherwise only the leaf certificate will be checked against revocation. =back =item SSL_ocsp_staple_callback If this callback is defined, it will be called with the SSL object and the OCSP response handle obtained from the peer, e.g. C<<$cb->($ssl,$resp)>>. If the peer did not provide a stapled OCSP response the function will be called with C<$resp=undef>. Because the OCSP response handle is no longer valid after leaving this function it should not by copied or freed. If access to the response is necessary after leaving this function it can be serialized with C. If no such callback is provided, it will use the default one, which verifies the response and uses it to check if the certificate(s) of the connection got revoked. =item SSL_ocsp_cache With this option a cache can be given for caching OCSP responses, which could be shared between different SSL contexts. If not given a cache specific to the SSL context only will be used. You can either create a new cache with C<< IO::Socket::SSL::OCSP_Cache->new([size]) >> or implement your own cache, which needs to have methods C and C (returning C<\%entry>) where entry is the hash representation of the OCSP response with fields like C. The default implementation of the cache will consider responses valid as long as C is less then the current time. =item SSL_reuse_ctx If you have already set the above options for a previous instance of IO::Socket::SSL, then you can reuse the SSL context of that instance by passing it as the value for the SSL_reuse_ctx parameter. You may also create a new instance of the IO::Socket::SSL::SSL_Context class, using any context options that you desire without specifying connection options, and pass that here instead. If you use this option, all other context-related options that you pass in the same call to new() will be ignored unless the context supplied was invalid. Note that, contrary to versions of IO::Socket::SSL below v0.90, a global SSL context will not be implicitly used unless you use the set_default_context() function. =item SSL_create_ctx_callback With this callback you can make individual settings to the context after it got created and the default setup was done. The callback will be called with the CTX object from Net::SSLeay as the single argument. Example for limiting the server session cache size: SSL_create_ctx_callback => sub { my $ctx = shift; Net::SSLeay::CTX_sess_set_cache_size($ctx,128); } =item SSL_session_cache_size If you make repeated connections to the same host/port and the SSL renegotiation time is an issue, you can turn on client-side session caching with this option by specifying a positive cache size. For successive connections, pass the SSL_reuse_ctx option to the new() calls (or use set_default_context()) to make use of the cached sessions. The session cache size refers to the number of unique host/port pairs that can be stored at one time; the oldest sessions in the cache will be removed if new ones are added. This option does not effect the session cache a server has for it's clients, e.g. it does not affect SSL objects with SSL_server set. Note that session caching with TLS 1.3 needs at least Net::SSLeay 1.86. =item SSL_session_cache Specifies session cache object which should be used instead of creating a new. Overrules SSL_session_cache_size. This option is useful if you want to reuse the cache, but not the rest of the context. A session cache object can be created using C<< IO::Socket::SSL::Session_Cache->new( cachesize ) >>. Use set_default_session_cache() to set a global cache object. =item SSL_session_key Specifies a key to use for lookups and inserts into client-side session cache. Per default ip:port of destination will be used, but sometimes you want to share the same session over multiple ports on the same server (like with FTPS). =item SSL_session_id_context This gives an id for the servers session cache. It's necessary if you want clients to connect with a client certificate. If not given but SSL_verify_mode specifies the need for client certificate a context unique id will be picked. =item SSL_error_trap When using the accept() or connect() methods, it may be the case that the actual socket connection works but the SSL negotiation fails, as in the case of an HTTP client connecting to an HTTPS server. Passing a subroutine ref attached to this parameter allows you to gain control of the orphaned socket instead of having it be closed forcibly. The subroutine, if called, will be passed two parameters: a reference to the socket on which the SSL negotiation failed and the full text of the error message. =item SSL_npn_protocols If used on the server side it specifies list of protocols advertised by SSL server as an array ref, e.g. ['spdy/2','http1.1']. On the client side it specifies the protocols offered by the client for NPN as an array ref. See also method C. Next Protocol Negotiation (NPN) is available with Net::SSLeay 1.46+ and openssl-1.0.1+. NPN is unavailable in TLSv1.3 protocol. To check support you might call C<< IO::Socket::SSL->can_npn() >>. If you use this option with an unsupported Net::SSLeay/OpenSSL it will throw an error. =item SSL_alpn_protocols If used on the server side it specifies list of protocols supported by the SSL server as an array ref, e.g. ['http/2.0', 'spdy/3.1','http/1.1']. On the client side it specifies the protocols advertised by the client for ALPN as an array ref. See also method C. Application-Layer Protocol Negotiation (ALPN) is available with Net::SSLeay 1.56+ and openssl-1.0.2+. More details about the extension are in RFC7301. To check support you might call C<< IO::Socket::SSL->can_alpn() >>. If you use this option with an unsupported Net::SSLeay/OpenSSL it will throw an error. Note that some client implementations may encounter problems if both NPN and ALPN are specified. Since ALPN is intended as a replacement for NPN, try providing ALPN protocols then fall back to NPN if that fails. =item SSL_ticket_keycb => [$sub,$data] | $sub This is a callback used for stateless session reuse (Session Tickets, RFC 5077). This callback will be called as C<< $sub->($data,[$key_name]) >> where C<$data> is the argument given to SSL_ticket_keycb (or undef) and C<$key_name> depends on the mode: =over 8 =item encrypt ticket If a ticket needs to be encrypted the callback will be called without C<$key_name>. In this case it should return C<($current_key,$current_key_name>) where C<$current_key> is the current key (32 byte random data) and C<$current_key_name> the name associated with this key (exactly 16 byte). This C<$current_key_name> will be incorporated into the ticket. =item decrypt ticket If a ticket needs to be decrypted the callback will be called with C<$key_name> as found in the ticket. It should return C<($key,$current_key_name>) where C<$key> is the key associated with the given C<$key_name> and C<$current_key_name> the name associated with the currently active key. If C<$current_key_name> is different from the given C<$key_name> the callback will be called again to re-encrypt the ticket with the currently active key. If no key can be found which matches the given C<$key_name> then this function should return nothing (empty list). This mechanism should be used to limit the life time for each key encrypting the ticket. Compromise of a ticket encryption key might lead to decryption of SSL sessions which used session tickets protected by this key. =back Example: Net::SSLeay::RAND_bytes(my $oldkey,32); Net::SSLeay::RAND_bytes(my $newkey,32); my $oldkey_name = pack("a16",'oldsecret'); my $newkey_name = pack("a16",'newsecret'); my @keys = ( [ $newkey_name, $newkey ], # current active key [ $oldkey_name, $oldkey ], # already expired ); my $keycb = [ sub { my ($mykeys,$name) = @_; # return (current_key, current_key_name) if no name given return ($mykeys->[0][1],$mykeys->[0][0]) if ! $name; # return (matching_key, current_key_name) if we find a key matching # the given name for(my $i = 0; $i<@$mykeys; $i++) { next if $name ne $mykeys->[$i][0]; return ($mykeys->[$i][1],$mykeys->[0][0]); } # no matching key found return; },\@keys ]; my $srv = IO::Socket::SSL->new(..., SSL_ticket_keycb => $keycb); =back =item B This behaves similar to the accept function of the underlying socket class, but additionally does the initial SSL handshake. But because the underlying socket class does return a blocking file handle even when accept is called on a non-blocking socket, the SSL handshake on the new file object will be done in a blocking way. Please see the section about non-blocking I/O for details. If you don't like this behavior you should do accept on the TCP socket and then upgrade it with C later. =item B This behaves similar to the connect function but also does an SSL handshake. Because you cannot give SSL specific arguments to this function, you should better either use C to create a connect SSL socket or C to upgrade an established TCP socket to SSL. =item B Contrary to a close for a simple INET socket a close in SSL also mandates a proper shutdown of the SSL part. This is done by sending a close notify message by both peers. A naive implementation would thus wait until it receives the close notify message from the peer - which conflicts with the commonly expected semantic that a close will not block. The default behavior is thus to only send a close notify but not wait for the close notify of the peer. If this is required C need to be explicitly set to false. There are also cases where a SSL shutdown should not be done at all. This is true for example when forking to let a child deal with the socket and closing the socket in the parent process. A naive explicit C or an implicit close when destroying the socket in the parent would send a close notify to the peer which would make the SSL socket in the client process unusable. In this case an explicit C with C set to true should be done in the parent process. For more details and other arguments see C which gets called from C to shutdown the SSL state of the socket. =item B This function behaves from the outside the same as B in other L objects, e.g. it returns at most LEN bytes of data. But in reality it reads not only LEN bytes from the underlying socket, but at a single SSL frame. It then returns up to LEN bytes it decrypted from this SSL frame. If the frame contained more data than requested it will return only LEN data, buffer the rest and return it on further read calls. This means, that it might be possible to read data, even if the underlying socket is not readable, so using poll or select might not be sufficient. sysread will only return data from a single SSL frame, e.g. either the pending data from the already buffered frame or it will read a frame from the underlying socket and return the decrypted data. It will not return data spanning several SSL frames in a single call. Also, calls to sysread might fail, because it must first finish an SSL handshake. To understand these behaviors is essential, if you write applications which use event loops and/or non-blocking sockets. Please read the specific sections in this documentation. =item B This functions behaves from the outside the same as B in other L objects, e.g. it will write at most LEN bytes to the socket, but there is no guarantee, that all LEN bytes are written. It will return the number of bytes written. Because it basically just calls SSL_write from OpenSSL syswrite will write at most a single SSL frame. This means, that no more than 16.384 bytes, which is the maximum size of an SSL frame, will be written at once. For non-blocking sockets SSL specific behavior applies. Pease read the specific section in this documentation. =item B This function has exactly the same syntax as B, and performs nearly the same task but will not advance the read position so that successive calls to peek() with the same arguments will return the same results. This function requires OpenSSL 0.9.6a or later to work. =item B This function gives you the number of bytes available without reading from the underlying socket object. This function is essential if you work with event loops, please see the section about polling SSL sockets. =item B This methods returns the fingerprint of the given certificate in the form C, where C is the used algorithm, default 'sha256'. If no certificate is given the peer certificate of the connection is used. If C is true it will not return the fingerprint of the certificate but instead the fingerprint of the pubkey inside the certificate as C. =item B This methods returns the binary fingerprint of the given certificate by using the algorithm C, default 'sha256'. If no certificate is given the peer certificate of the connection is used. If C is true it will not return the fingerprint of the certificate but instead the fingerprint of the pubkey inside the certificate. =item B Returns the string form of the cipher that the IO::Socket::SSL object is using. =item B Returns the string representation of the SSL version of an established connection. =item B Returns the integer representation of the SSL version of an established connection. =item B This returns true if the session got reused and false otherwise. Note that with a reused session no certificates are send within the handshake and no ciphers are offered and thus functions which rely on this might not work. =item B Returns a parsable string with select fields from the peer SSL certificate. This method directly returns the result of the dump_peer_certificate() method of Net::SSLeay. =item B If a peer certificate exists, this function can retrieve values from it. If no field is given the internal representation of certificate from Net::SSLeay is returned. If refresh is true it will not used a cached version, but check again in case the certificate of the connection has changed due to renegotiation. The following fields can be queried: =over 8 =item authority (alias issuer) The certificate authority which signed the certificate. =item owner (alias subject) The owner of the certificate. =item commonName (alias cn) - only for Net::SSLeay version >=1.30 The common name, usually the server name for SSL certificates. =item subjectAltNames - only for Net::SSLeay version >=1.33 Alternative names for the subject, usually different names for the same server, like example.org, example.com, *.example.com. It returns a list of (typ,value) with typ GEN_DNS, GEN_IPADD etc (these constants are exported from IO::Socket::SSL). See Net::SSLeay::X509_get_subjectAltNames. =back =item B This is similar to C but will return the sites own certificate. The same arguments for B<$field> can be used. If no B<$field> is given the certificate handle from the underlying OpenSSL will be returned. This handle will only be valid as long as the SSL connection exists and if used afterwards it might result in strange crashes of the application. =item B This returns all the certificates send by the peer, e.g. first the peers own certificate and then the rest of the chain. You might use B from L to inspect each of the certificates. This function depends on a version of Net::SSLeay >= 1.58 . =item B This gives the name requested by the client if Server Name Indication (SNI) was used. =item B This verifies the given hostname against the peer certificate using the given scheme. Hostname is usually what you specify within the PeerAddr. See the C parameter for an explanation of suffix checking and for the possible values. Verification of hostname against a certificate is different between various applications and RFCs. Some scheme allow wildcards for hostnames, some only in subjectAltNames, and even their different wildcard schemes are possible. RFC 6125 provides a good overview. To ease the verification the following schemes are predefined (both protocol name and rfcXXXX name can be used): =over 8 =item rfc2818, xmpp (rfc3920), ftp (rfc4217) Extended wildcards in subjectAltNames and common name are possible, e.g. *.example.org or even www*.example.org. The common name will be only checked if no DNS names are given in subjectAltNames. =item http (alias www) While name checking is defined in rfc2818 the current browsers usually accept also an IP address (w/o wildcards) within the common name as long as no subjectAltNames are defined. Thus this is rfc2818 extended with this feature. =item smtp (rfc2595), imap, pop3, acap (rfc4642), netconf (rfc5538), syslog (rfc5425), snmp (rfc5953) Simple wildcards in subjectAltNames are possible, e.g. *.example.org matches www.example.org but not lala.www.example.org. If nothing from subjectAltNames match it checks against the common name, where wildcards are also allowed to match the full leftmost label. =item ldap (rfc4513) Simple wildcards are allowed in subjectAltNames, but not in common name. Common name will be checked even if subjectAltNames exist. =item sip (rfc5922) No wildcards are allowed and common name is checked even if subjectAltNames exist. =item gist (rfc5971) Simple wildcards are allowed in subjectAltNames and common name, but common name will only be checked if their are no DNS names in subjectAltNames. =item default This is a superset of all the rules and is automatically used if no scheme is given but a hostname (instead of IP) is known. Extended wildcards are allowed in subjectAltNames and common name and common name is checked always. =item none No verification will be done. Actually is does not make any sense to call verify_hostname in this case. =back The scheme can be given either by specifying the name for one of the above predefined schemes, or by using a hash which can have the following keys and values: =over 8 =item check_cn: 0|'always'|'when_only' Determines if the common name gets checked. If 'always' it will always be checked (like in ldap), if 'when_only' it will only be checked if no names are given in subjectAltNames (like in http), for any other values the common name will not be checked. =item wildcards_in_alt: 0|'full_label'|'anywhere' Determines if and where wildcards in subjectAltNames are possible. If 'full_label' only cases like *.example.org will be possible (like in ldap), for 'anywhere' www*.example.org is possible too (like http), dangerous things like but www.*.org or even '*' will not be allowed. For compatibility with older versions 'leftmost' can be given instead of 'full_label'. =item wildcards_in_cn: 0|'full_label'|'anywhere' Similar to wildcards_in_alt, but checks the common name. There is no predefined scheme which allows wildcards in common names. =item ip_in_cn: 0|1|4|6 Determines if an IP address is allowed in the common name (no wildcards are allowed). If set to 4 or 6 it only allows IPv4 or IPv6 addresses, any other true value allows both. =item callback: \&coderef If you give a subroutine for verification it will be called with the arguments ($hostname,$commonName,@subjectAltNames), where hostname is the name given for verification, commonName is the result from peer_certificate('cn') and subjectAltNames is the result from peer_certificate('subjectAltNames'). All other arguments for the verification scheme will be ignored in this case. =back =item B This method returns the name of negotiated protocol - e.g. 'http/1.1'. It works for both client and server side of SSL connection. NPN support is available with Net::SSLeay 1.46+ and openssl-1.0.1+. To check support you might call C<< IO::Socket::SSL->can_npn() >>. =item B Returns the protocol negotiated via ALPN as a string, e.g. 'http/1.1', 'http/2.0' or 'spdy/3.1'. ALPN support is available with Net::SSLeay 1.56+ and openssl-1.0.2+. To check support, use C<< IO::Socket::SSL->can_alpn() >>. =item B Returns the last error (in string form) that occurred. If you do not have a real object to perform this method on, call IO::Socket::SSL::errstr() instead. For read and write errors on non-blocking sockets, this method may include the string C or C meaning that the other side is expecting to read from or write to the socket and wants to be satisfied before you get to do anything. But with version 0.98 you are better comparing the global exported variable $SSL_ERROR against the exported symbols SSL_WANT_READ and SSL_WANT_WRITE. =item B This returns false if the socket could not be opened, 1 if the socket could be opened and the SSL handshake was successful done and -1 if the underlying IO::Handle is open, but the SSL handshake failed. =item B<< IO::Socket::SSL->start_SSL($socket, ... ) >> This will convert a glob reference or a socket that you provide to an IO::Socket::SSL object. You may also pass parameters to specify context or connection options as with a call to new(). If you are using this function on an accept()ed socket, you must set the parameter "SSL_server" to 1, i.e. IO::Socket::SSL->start_SSL($socket, SSL_server => 1). If you have a class that inherits from IO::Socket::SSL and you want the $socket to be blessed into your own class instead, use MyClass->start_SSL($socket) to achieve the desired effect. Note that if start_SSL() fails in SSL negotiation, $socket will remain blessed in its original class. For non-blocking sockets you better just upgrade the socket to IO::Socket::SSL and call accept_SSL or connect_SSL and the upgraded object. To just upgrade the socket set B explicitly to 0. If you call start_SSL w/o this parameter it will revert to blocking behavior for accept_SSL and connect_SSL. If given the parameter "Timeout" it will stop if after the timeout no SSL connection was established. This parameter is only used for blocking sockets, if it is not given the default Timeout from the underlying IO::Socket will be used. =item B This is the opposite of start_SSL(), connect_SSL() and accept_SSL(), e.g. it will shutdown the SSL connection and return to the class before start_SSL(). It gets the same arguments as close(), in fact close() calls stop_SSL() (but without downgrading the class). Will return true if it succeeded and undef if failed. This might be the case for non-blocking sockets. In this case $! is set to EWOULDBLOCK and the ssl error to SSL_WANT_READ or SSL_WANT_WRITE. In this case the call should be retried again with the same arguments once the socket is ready. For calling from C C default to false, e.g. it waits for the close_notify of the peer. This is necessary in case you want to downgrade the socket and continue to use it as a plain socket. After stop_SSL the socket can again be used to exchange plain data. =item B, B These functions should be used to do the relevant handshake, if the socket got created with C or upgraded with C and C was set to false. They will return undef until the handshake succeeded or an error got thrown. As long as the function returns undef and $! is set to EWOULDBLOCK one could retry the call after the socket got readable (SSL_WANT_READ) or writeable (SSL_WANT_WRITE). =item B This will create an OCSP resolver object, which can be used to create OCSP requests for the certificates of the SSL connection. Which certificates are verified depends on the setting of C: by default only the leaf certificate will be checked, but with SSL_OCSP_FULL_CHAIN all chain certificates will be checked. Because to create an OCSP request the certificate and its issuer certificate need to be known it is not possible to check certificates when the trust chain is incomplete or if the certificate is self-signed. The OCSP resolver gets created by calling C<< $ssl->ocsp_resolver >> and provides the following methods: =over 8 =item hard_error This returns the hard error when checking the OCSP response. Hard errors are certificate revocations. With the C of SSL_OCSP_FAIL_HARD any soft error (e.g. failures to get signed information about the certificates) will be considered a hard error too. The OCSP resolving will stop on the first hard error. The method will return undef as long as no hard errors occurred and still requests to be resolved. If all requests got resolved and no hard errors occurred the method will return C<''>. =item soft_error This returns the soft error(s) which occurred when asking the OCSP responders. =item requests This will return a hash consisting of C<(url,request)>-tuples, e.g. which contain the OCSP request string and the URL where it should be sent too. The usual way to send such a request is as HTTP POST request with a content-type of C or as a GET request with the base64 and url-encoded request is added to the path of the URL. After you've handled all these requests and added the response with C you should better call this method again to make sure, that no more requests are outstanding. IO::Socket::SSL will combine multiple OCSP requests for the same server inside a single request, but some server don't give a response to all these requests, so that one has to ask again with the remaining requests. =item add_response($uri,$response) This method takes the HTTP body of the response which got received when sending the OCSP request to C<$uri>. If no response was received or an error occurred one should either retry or consider C<$response> as empty which will trigger a soft error. The method returns the current value of C, e.g. a defined value when no more requests need to be done. =item resolve_blocking(%args) This combines C and C which L to do all necessary requests in a blocking way. C<%args> will be given to L so that you can put proxy settings etc here. L will be called with C of false, because the OCSP responses have their own signatures so no extra SSL verification is needed. If you don't want to use blocking requests you need to roll your own user agent with C and C. =back =item B<< IO::Socket::SSL->new_from_fd($fd, [mode], %sslargs) >> This will convert a socket identified via a file descriptor into an SSL socket. Note that the argument list does not include a "MODE" argument; if you supply one, it will be thoughtfully ignored (for compatibility with IO::Socket::INET). Instead, a mode of '+<' is assumed, and the file descriptor passed must be able to handle such I/O because the initial SSL handshake requires bidirectional communication. Internally the given $fd will be upgraded to a socket object using the C method of the super class (L or similar) and then C will be called using the given C<%sslargs>. If C<$fd> is already an IO::Socket object you should better call C directly. =item B ..., SSL_ca_path => ... ])> Determines or sets the default CA path. If existing path or dir or a hash is given it will set the default CA path to this value and never try to detect it automatically. If C is given it will forget any stored defaults and continue with detection of system defaults. If no arguments are given it will start detection of system defaults, unless it has already stored user-set or previously detected values. The detection of system defaults works similar to OpenSSL, e.g. it will check the directory specified in environment variable SSL_CERT_DIR or the path OPENSSLDIR/certs (SSLCERTS: on VMS) and the file specified in environment variable SSL_CERT_FILE or the path OPENSSLDIR/cert.pem (SSLCERTS:cert.pem on VMS). Contrary to OpenSSL it will check if the SSL_ca_path contains PEM files with the hash as file name and if the SSL_ca_file looks like PEM. If no usable system default can be found it will try to load and use L and if not available give up detection. The result of the detection will be saved to speed up future calls. The function returns the saved default CA as hash with SSL_ca_file and SSL_ca_path. =item B You may use this to make IO::Socket::SSL automatically re-use a given context (unless specifically overridden in a call to new()). It accepts one argument, which should be either an IO::Socket::SSL object or an IO::Socket::SSL::SSL_Context object. See the SSL_reuse_ctx option of new() for more details. Note that this sets the default context globally, so use with caution (esp. in mod_perl scripts). =item B You may use this to make IO::Socket::SSL automatically re-use a given session cache (unless specifically overridden in a call to new()). It accepts one argument, which should be an IO::Socket::SSL::Session_Cache object or similar (e.g. something which implements get_session, add_session and del_session like IO::Socket::SSL::Session_Cache does). See the SSL_session_cache option of new() for more details. Note that this sets the default cache globally, so use with caution. =item B With this function one can set defaults for all SSL_* parameter used for creation of the context, like the SSL_verify* parameter. Any SSL_* parameter can be given or the following short versions: =over 8 =item mode - SSL_verify_mode =item callback - SSL_verify_callback =item scheme - SSL_verifycn_scheme =item name - SSL_verifycn_name =back =item B Similar to C, but only sets the defaults for client mode. =item B Similar to C, but only sets the defaults for server mode. =item B Sometimes one has to use code which uses unwanted or invalid arguments for SSL, typically disabling SSL verification or setting wrong ciphers or SSL versions. With this hack it is possible to override these settings and restore sanity. Example: IO::Socket::SSL::set_args_filter_hack( sub { my ($is_server,$args) = @_; if ( ! $is_server ) { # client settings - enable verification with default CA # and fallback hostname verification etc delete @{$args}{qw( SSL_verify_mode SSL_ca_file SSL_ca_path SSL_verifycn_scheme SSL_version )}; # and add some fingerprints for known certs which are signed by # unknown CAs or are self-signed $args->{SSL_fingerprint} = ... } }); With the short setting C it will prefer the default settings in all cases. These default settings can be modified with C, C and C. =back The following methods are unsupported (not to mention futile!) and IO::Socket::SSL will emit a large CROAK() if you are silly enough to use them: =over 4 =item truncate =item stat =item ungetc =item setbuf =item setvbuf =item fdopen =item send/recv Note that send() and recv() cannot be reliably trapped by a tied filehandle (such as that used by IO::Socket::SSL) and so may send unencrypted data over the socket. Object-oriented calls to these functions will fail, telling you to use the print/printf/syswrite and read/sysread families instead. =back =head1 DEPRECATIONS The following functions are deprecated and are only retained for compatibility: =over 2 =item context_init() use the SSL_reuse_ctx option if you want to re-use a context =item socketToSSL() and socket_to_SSL() use IO::Socket::SSL->start_SSL() instead =item kill_socket() use close() instead =item get_peer_certificate() use the peer_certificate() function instead. Used to return X509_Certificate with methods subject_name and issuer_name. Now simply returns $self which has these methods (although deprecated). =item issuer_name() use peer_certificate( 'issuer' ) instead =item subject_name() use peer_certificate( 'subject' ) instead =back =head1 EXAMPLES See the 'example' directory, the tests in 't' and also the tools in 'util'. =head1 BUGS If you use IO::Socket::SSL together with threads you should load it (e.g. use or require) inside the main thread before creating any other threads which use it. This way it is much faster because it will be initialized only once. Also there are reports that it might crash the other way. Creating an IO::Socket::SSL object in one thread and closing it in another thread will not work. IO::Socket::SSL does not work together with Storable::fd_retrieve/fd_store. See BUGS file for more information and how to work around the problem. Non-blocking and timeouts (which are based on non-blocking) are not supported on Win32, because the underlying IO::Socket::INET does not support non-blocking on this platform. If you have a server and it looks like you have a memory leak you might check the size of your session cache. Default for Net::SSLeay seems to be 20480, see the example for SSL_create_ctx_callback for how to limit it. TLS 1.3 support regarding session reuse is incomplete. =head1 SEE ALSO IO::Socket::INET, IO::Socket::INET6, IO::Socket::IP, Net::SSLeay. =head1 THANKS Many thanks to all who added patches or reported bugs or helped IO::Socket::SSL another way. Please keep reporting bugs and help with patches, even if they just fix the documentation. Special thanks to the team of Net::SSLeay for the good cooperation. =head1 AUTHORS Steffen Ullrich, is the current maintainer. Peter Behroozi, (Note the lack of an "i" at the end of "behrooz") Marko Asplund, , was the original author of IO::Socket::SSL. Patches incorporated from various people, see file Changes. =head1 COPYRIGHT The original versions of this module are Copyright (C) 1999-2002 Marko Asplund. The rewrite of this module is Copyright (C) 2002-2005 Peter Behroozi. Versions 0.98 and newer are Copyright (C) 2006-2014 Steffen Ullrich. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. PKk4]F#SSL.pmnu[#vim: set sts=4 sw=4 ts=8 ai: # # IO::Socket::SSL: # provide an interface to SSL connections similar to IO::Socket modules # # Current Code Shepherd: Steffen Ullrich # Code Shepherd before: Peter Behroozi, # # The original version of this module was written by # Marko Asplund, , who drew from # Crypt::SSLeay (Net::SSL) by Gisle Aas. # package IO::Socket::SSL; our $VERSION = '2.066'; use IO::Socket; use Net::SSLeay 1.46; use IO::Socket::SSL::PublicSuffix; use Exporter (); use Errno qw( EWOULDBLOCK EAGAIN ETIMEDOUT EINTR EPIPE ); use Carp; use strict; my $use_threads; BEGIN { die "no support for weaken - please install Scalar::Util" if ! do { local $SIG{__DIE__}; eval { require Scalar::Util; Scalar::Util->import("weaken"); 1 } || eval { require WeakRef; WeakRef->import("weaken"); 1 } }; require Config; $use_threads = $Config::Config{usethreads}; } # results from commonly used constant functions from Net::SSLeay for fast access my $Net_SSLeay_ERROR_WANT_READ = Net::SSLeay::ERROR_WANT_READ(); my $Net_SSLeay_ERROR_WANT_WRITE = Net::SSLeay::ERROR_WANT_WRITE(); my $Net_SSLeay_ERROR_SYSCALL = Net::SSLeay::ERROR_SYSCALL(); my $Net_SSLeay_VERIFY_NONE = Net::SSLeay::VERIFY_NONE(); my $Net_SSLeay_VERIFY_PEER = Net::SSLeay::VERIFY_PEER(); use constant SSL_VERIFY_NONE => &Net::SSLeay::VERIFY_NONE; use constant SSL_VERIFY_PEER => &Net::SSLeay::VERIFY_PEER; use constant SSL_VERIFY_FAIL_IF_NO_PEER_CERT => Net::SSLeay::VERIFY_FAIL_IF_NO_PEER_CERT(); use constant SSL_VERIFY_CLIENT_ONCE => Net::SSLeay::VERIFY_CLIENT_ONCE(); # from openssl/ssl.h; should be better in Net::SSLeay use constant SSL_SENT_SHUTDOWN => 1; use constant SSL_RECEIVED_SHUTDOWN => 2; use constant SSL_OCSP_NO_STAPLE => 0b00001; use constant SSL_OCSP_MUST_STAPLE => 0b00010; use constant SSL_OCSP_FAIL_HARD => 0b00100; use constant SSL_OCSP_FULL_CHAIN => 0b01000; use constant SSL_OCSP_TRY_STAPLE => 0b10000; # capabilities of underlying Net::SSLeay/openssl my $can_client_sni; # do we support SNI on the client side my $can_server_sni; # do we support SNI on the server side my $can_multi_cert; # RSA and ECC certificate in same context my $can_npn; # do we support NPN (obsolete) my $can_alpn; # do we support ALPN my $can_ecdh; # do we support ECDH key exchange my $set_groups_list; # SSL_CTX_set1_groups_list || SSL_CTX_set1_curves_list || undef my $can_ocsp; # do we support OCSP my $can_ocsp_staple; # do we support OCSP stapling my $can_tckt_keycb; # TLS ticket key callback my $can_pha; # do we support PHA my $session_upref; # SSL_SESSION_up_ref is implemented my %sess_cb; # SSL_CTX_sess_set_(new|remove)_cb my $check_partial_chain; # use X509_V_FLAG_PARTIAL_CHAIN if available my $openssl_version; my $netssleay_version; BEGIN { $openssl_version = Net::SSLeay::OPENSSL_VERSION_NUMBER(); $netssleay_version = do { no warnings; $Net::SSLeay::VERSION + 0.0; }; $can_client_sni = $openssl_version >= 0x10000000; $can_server_sni = defined &Net::SSLeay::get_servername; $can_npn = defined &Net::SSLeay::P_next_proto_negotiated && ! Net::SSLeay::constant("LIBRESSL_VERSION_NUMBER"); # LibreSSL 2.6.1 disabled NPN by keeping the relevant functions # available but removed the actual functionality from these functions. $can_alpn = defined &Net::SSLeay::CTX_set_alpn_protos; $can_ecdh = ($openssl_version >= 0x1010000f) ? 'auto' : defined(&Net::SSLeay::CTX_set_ecdh_auto) ? 'can_auto' : (defined &Net::SSLeay::CTX_set_tmp_ecdh && # There is a regression with elliptic curves on 1.0.1d with 64bit # http://rt.openssl.org/Ticket/Display.html?id=2975 ( $openssl_version != 0x1000104f || length(pack("P",0)) == 4 )) ? 'tmp_ecdh' : ''; $set_groups_list = defined &Net::SSLeay::CTX_set1_groups_list ? \&Net::SSLeay::CTX_set1_groups_list : defined &Net::SSLeay::CTX_set1_curves_list ? \&Net::SSLeay::CTX_set1_curves_list : undef; $can_multi_cert = $can_ecdh && $openssl_version >= 0x10002000; $can_ocsp = defined &Net::SSLeay::OCSP_cert2ids # OCSP got broken in 1.75..1.77 && ($netssleay_version < 1.75 || $netssleay_version > 1.77); $can_ocsp_staple = $can_ocsp && defined &Net::SSLeay::set_tlsext_status_type; $can_tckt_keycb = defined &Net::SSLeay::CTX_set_tlsext_ticket_getkey_cb && $netssleay_version >= 1.80; $can_pha = defined &Net::SSLeay::CTX_set_post_handshake_auth; if (defined &Net::SSLeay::SESSION_up_ref) { $session_upref = 1; } if ($session_upref && defined &Net::SSLeay::CTX_sess_set_new_cb && defined &Net::SSLeay::CTX_sess_set_remove_cb) { %sess_cb = ( new => \&Net::SSLeay::CTX_sess_set_new_cb, remove => \&Net::SSLeay::CTX_sess_set_remove_cb, ); } if (my $c = defined &Net::SSLeay::CTX_get0_param && eval { Net::SSLeay::X509_V_FLAG_PARTIAL_CHAIN() }) { $check_partial_chain = sub { my $ctx = shift; my $param = Net::SSLeay::CTX_get0_param($ctx); Net::SSLeay::X509_VERIFY_PARAM_set_flags($param, $c); }; } } my $algo2digest = do { my %digest; sub { my $digest_name = shift; return $digest{$digest_name} ||= do { Net::SSLeay::SSLeay_add_ssl_algorithms(); Net::SSLeay::EVP_get_digestbyname($digest_name) or die "Digest algorithm $digest_name is not available"; }; } }; my $CTX_tlsv1_3_new; if ( defined &Net::SSLeay::CTX_set_min_proto_version and defined &Net::SSLeay::CTX_set_max_proto_version and my $tls13 = eval { Net::SSLeay::TLS1_3_VERSION() } ) { $CTX_tlsv1_3_new = sub { my $ctx = Net::SSLeay::CTX_new(); return $ctx if Net::SSLeay::CTX_set_min_proto_version($ctx,$tls13) && Net::SSLeay::CTX_set_max_proto_version($ctx,$tls13); Net::SSLeay::CTX_free($ctx); return; }; } # global defaults my %DEFAULT_SSL_ARGS = ( SSL_check_crl => 0, SSL_version => '', SSL_verify_callback => undef, SSL_verifycn_scheme => undef, # fallback cn verification SSL_verifycn_publicsuffix => undef, # fallback default list verification #SSL_verifycn_name => undef, # use from PeerAddr/PeerHost - do not override in set_args_filter_hack 'use_defaults' SSL_npn_protocols => undef, # meaning depends whether on server or client side SSL_alpn_protocols => undef, # list of protocols we'll accept/send, for example ['http/1.1','spdy/3.1'] # Use system-wide default cipher list to support use of system-wide # crypto policy (#1076390, #1127577, CPAN RT#97816) # https://fedoraproject.org/wiki/Changes/CryptoPolicy SSL_cipher_list => 'PROFILE=SYSTEM', ); my %DEFAULT_SSL_CLIENT_ARGS = ( %DEFAULT_SSL_ARGS, SSL_verify_mode => SSL_VERIFY_PEER, SSL_ca_file => undef, SSL_ca_path => undef, ); # set values inside _init to work with perlcc, RT#95452 my %DEFAULT_SSL_SERVER_ARGS; # Initialization of OpenSSL internals # This will be called once during compilation - perlcc users might need to # call it again by hand, see RT#95452 { sub init { # library_init returns false if the library was already initialized. # This way we can find out if the library needs to be re-initialized # inside code compiled with perlcc Net::SSLeay::library_init() or return; Net::SSLeay::load_error_strings(); Net::SSLeay::OpenSSL_add_all_digests(); Net::SSLeay::randomize(); %DEFAULT_SSL_SERVER_ARGS = ( %DEFAULT_SSL_ARGS, SSL_verify_mode => SSL_VERIFY_NONE, SSL_honor_cipher_order => 1, # trust server to know the best cipher SSL_dh => do { my $bio = Net::SSLeay::BIO_new(Net::SSLeay::BIO_s_mem()); # generated with: openssl dhparam 2048 Net::SSLeay::BIO_write($bio,<<'DH'); -----BEGIN DH PARAMETERS----- MIIBCAKCAQEAr8wskArj5+1VCVsnWt/RUR7tXkHJ7mGW7XxrLSPOaFyKyWf8lZht iSY2Lc4oa4Zw8wibGQ3faeQu/s8fvPq/aqTxYmyHPKCMoze77QJHtrYtJAosB9SY CN7s5Hexxb5/vQ4qlQuOkVrZDiZO9GC4KaH9mJYnCoAsXDhDft6JT0oRVSgtZQnU gWFKShIm+JVjN94kGs0TcBEesPTK2g8XVHK9H8AtSUb9BwW2qD/T5RmgNABysApO Ps2vlkxjAHjJcqc3O+OiImKik/X2rtBTZjpKmzN3WWTB0RJZCOWaLlDO81D01o1E aZecz3Np9KIYey900f+X7zC2bJxEHp95ywIBAg== -----END DH PARAMETERS----- DH my $dh = Net::SSLeay::PEM_read_bio_DHparams($bio); Net::SSLeay::BIO_free($bio); $dh or die "no DH"; $dh; }, ( $can_ecdh eq 'auto' ? () : # automatically enabled by openssl $can_ecdh eq 'can_auto' ? (SSL_ecdh_curve => 'auto') : $can_ecdh eq 'tmp_ecdh' ? ( SSL_ecdh_curve => 'prime256v1' ) : (), ) ); } # Call it once at compile time and try it at INIT. # This should catch all cases of including the module, e.g. 'use' (INIT) or # 'require' (compile time) and works also with perlcc { no warnings; INIT { init() } init(); } } # global defaults which can be changed using set_defaults # either key/value can be set or it can just be set to an external hash my $GLOBAL_SSL_ARGS = {}; my $GLOBAL_SSL_CLIENT_ARGS = {}; my $GLOBAL_SSL_SERVER_ARGS = {}; # hack which is used to filter bad settings from used modules my $FILTER_SSL_ARGS = undef; # non-XS Versions of Scalar::Util will fail BEGIN{ die "You need the XS Version of Scalar::Util for dualvar() support" if !do { local $SIG{__DIE__}; local $SIG{__WARN__}; # be silent eval { use Scalar::Util 'dualvar'; dualvar(0,''); 1 }; }; } # get constants for SSL_OP_NO_* now, instead calling the related functions # every time we setup a connection my %SSL_OP_NO; for(qw( SSLv2 SSLv3 TLSv1 TLSv1_1 TLSv11:TLSv1_1 TLSv1_2 TLSv12:TLSv1_2 TLSv1_3 TLSv13:TLSv1_3 )) { my ($k,$op) = m{:} ? split(m{:},$_,2) : ($_,$_); my $sub = "Net::SSLeay::OP_NO_$op"; local $SIG{__DIE__}; $SSL_OP_NO{$k} = eval { no strict 'refs'; &$sub } || 0; } # Make SSL_CTX_clear_options accessible through SSL_CTX_ctrl unless it is # already implemented in Net::SSLeay if (!defined &Net::SSLeay::CTX_clear_options) { *Net::SSLeay::CTX_clear_options = sub { my ($ctx,$opt) = @_; # 77 = SSL_CTRL_CLEAR_OPTIONS Net::SSLeay::CTX_ctrl($ctx,77,$opt,0); }; } # Try to work around problems with alternative trust path by default, RT#104759 my $DEFAULT_X509_STORE_flags = 0; { local $SIG{__DIE__}; eval { $DEFAULT_X509_STORE_flags |= Net::SSLeay::X509_V_FLAG_TRUSTED_FIRST() }; } our $DEBUG; use vars qw(@ISA $SSL_ERROR @EXPORT); { # These constants will be used in $! at return from SSL_connect, # SSL_accept, _generic_(read|write), thus notifying the caller # the usual way of problems. Like with EWOULDBLOCK, EINPROGRESS.. # these are especially important for non-blocking sockets my $x = $Net_SSLeay_ERROR_WANT_READ; use constant SSL_WANT_READ => dualvar( \$x, 'SSL wants a read first' ); my $y = $Net_SSLeay_ERROR_WANT_WRITE; use constant SSL_WANT_WRITE => dualvar( \$y, 'SSL wants a write first' ); @EXPORT = qw( SSL_WANT_READ SSL_WANT_WRITE SSL_VERIFY_NONE SSL_VERIFY_PEER SSL_VERIFY_FAIL_IF_NO_PEER_CERT SSL_VERIFY_CLIENT_ONCE SSL_OCSP_NO_STAPLE SSL_OCSP_TRY_STAPLE SSL_OCSP_MUST_STAPLE SSL_OCSP_FAIL_HARD SSL_OCSP_FULL_CHAIN $SSL_ERROR GEN_DNS GEN_IPADD ); } my @caller_force_inet4; # in case inet4 gets forced we store here who forced it my $IOCLASS; my $family_key; # 'Domain'||'Family' BEGIN { # declare @ISA depending of the installed socket class # try to load inet_pton from Socket or Socket6 and make sure it is usable local $SIG{__DIE__}; local $SIG{__WARN__}; # be silent my $ip6 = eval { require Socket; Socket->VERSION(1.95); Socket::inet_pton( AF_INET6(),'::1') && AF_INET6() or die; Socket->import( qw/inet_pton NI_NUMERICHOST NI_NUMERICSERV/ ); # behavior different to Socket6::getnameinfo - wrap *_getnameinfo = sub { my ($err,$host,$port) = Socket::getnameinfo(@_) or return; return if $err; return ($host,$port); }; 'Socket'; } || eval { require Socket6; Socket6::inet_pton( AF_INET6(),'::1') && AF_INET6() or die; Socket6->import( qw/inet_pton NI_NUMERICHOST NI_NUMERICSERV/ ); # behavior different to Socket::getnameinfo - wrap *_getnameinfo = sub { return Socket6::getnameinfo(@_); }; 'Socket6'; } || undef; # try IO::Socket::IP or IO::Socket::INET6 for IPv6 support $family_key = 'Domain'; # traditional if ($ip6) { # if we have IO::Socket::IP >= 0.31 we will use this in preference # because it can handle both IPv4 and IPv6 if ( eval { require IO::Socket::IP; IO::Socket::IP->VERSION(0.31) }) { @ISA = qw(IO::Socket::IP); constant->import( CAN_IPV6 => "IO::Socket::IP" ); $family_key = 'Family'; $IOCLASS = "IO::Socket::IP"; # if we have IO::Socket::INET6 we will use this not IO::Socket::INET # because it can handle both IPv4 and IPv6 # require at least 2.62 because of several problems before that version } elsif( eval { require IO::Socket::INET6; IO::Socket::INET6->VERSION(2.62) } ) { @ISA = qw(IO::Socket::INET6); constant->import( CAN_IPV6 => "IO::Socket::INET6" ); $IOCLASS = "IO::Socket::INET6"; } else { $ip6 = '' } } # fall back to IO::Socket::INET for IPv4 only if (!$ip6) { @ISA = qw(IO::Socket::INET); $IOCLASS = "IO::Socket::INET"; constant->import(CAN_IPV6 => ''); if (!defined $ip6) { constant->import(NI_NUMERICHOST => 1); constant->import(NI_NUMERICSERV => 2); } } #Make $DEBUG another name for $Net::SSLeay::trace *DEBUG = \$Net::SSLeay::trace; #Compatibility *ERROR = \$SSL_ERROR; } sub DEBUG { $DEBUG or return; my (undef,$file,$line,$sub) = caller(1); if ($sub =~m{^IO::Socket::SSL::(?:error|(_internal_error))$}) { (undef,$file,$line) = caller(2) if $1; } else { (undef,$file,$line) = caller; } my $msg = shift; $file = '...'.substr( $file,-17 ) if length($file)>20; $msg = sprintf $msg,@_ if @_; print STDERR "DEBUG: $file:$line: $msg\n"; } BEGIN { # import some constants from Net::SSLeay or use hard-coded defaults # if Net::SSLeay isn't recent enough to provide the constants my %const = ( NID_CommonName => 13, GEN_DNS => 2, GEN_IPADD => 7, ); while ( my ($name,$value) = each %const ) { no strict 'refs'; *{$name} = UNIVERSAL::can( 'Net::SSLeay', $name ) || sub { $value }; } *idn_to_ascii = \&IO::Socket::SSL::PublicSuffix::idn_to_ascii; *idn_to_unicode = \&IO::Socket::SSL::PublicSuffix::idn_to_unicode; } my $OPENSSL_LIST_SEPARATOR = $^O =~m{^(?:(dos|os2|mswin32|netware)|vms)$}i ? $1 ? ';' : ',' : ':'; my $CHECK_SSL_PATH = sub { my %args = (@_ == 1) ? ('',@_) : @_; for my $type (keys %args) { my $path = $args{$type}; if (!$type) { delete $args{$type}; $type = (ref($path) || -d $path) ? 'SSL_ca_path' : 'SSL_ca_file'; $args{$type} = $path; } next if ref($path) eq 'SCALAR' && ! $$path; if ($type eq 'SSL_ca_file') { die "SSL_ca_file $path can't be used: $!" if ! open(my $fh,'<',$path); } elsif ($type eq 'SSL_ca_path') { $path = [ split($OPENSSL_LIST_SEPARATOR,$path) ] if !ref($path); my @err; for my $d (ref($path) ? @$path : $path) { if (! -d $d) { push @err, "SSL_ca_path $d does not exist"; } elsif (! opendir(my $dh,$d)) { push @err, "SSL_ca_path $d is not accessible: $!" } else { @err = (); last } } die "@err" if @err; } } return %args; }; { my %default_ca; my $ca_detected; # 0: never detect, undef: need to (re)detect my $openssldir; sub default_ca { if (@_) { # user defined default CA or reset if ( @_ > 1 ) { %default_ca = @_; $ca_detected = 0; } elsif ( my $path = shift ) { %default_ca = $CHECK_SSL_PATH->($path); $ca_detected = 0; } else { $ca_detected = undef; } } return %default_ca if defined $ca_detected; # SSLEAY_DIR was 5 up to OpenSSL 1.1, then switched to 4 and got # renamed to OPENSSL_DIR. Unfortunately it is not exported as constant # by Net::SSLeay so we use the fixed number. $openssldir ||= Net::SSLeay::SSLeay_version(5) =~m{^OPENSSLDIR: "(.+)"$} ? $1 : Net::SSLeay::SSLeay_version(4) =~m{^OPENSSLDIR: "(.+)"$} ? $1 : 'cannot-determine-openssldir-from-ssleay-version'; # (re)detect according to openssl crypto/cryptlib.h my $dir = $ENV{SSL_CERT_DIR} || ( $^O =~m{vms}i ? "SSLCERTS:":"$openssldir/certs" ); if ( opendir(my $dh,$dir)) { FILES: for my $f ( grep { m{^[a-f\d]{8}(\.\d+)?$} } readdir($dh) ) { open( my $fh,'<',"$dir/$f") or next; while (my $line = <$fh>) { $line =~m{^-+BEGIN (X509 |TRUSTED |)CERTIFICATE-} or next; $default_ca{SSL_ca_path} = $dir; last FILES; } } } my $file = $ENV{SSL_CERT_FILE} || ( $^O =~m{vms}i ? "SSLCERTS:cert.pem":"$openssldir/cert.pem" ); if ( open(my $fh,'<',$file)) { while (my $line = <$fh>) { $line =~m{^-+BEGIN (X509 |TRUSTED |)CERTIFICATE-} or next; $default_ca{SSL_ca_file} = $file; last; } } $default_ca{SSL_ca_file} = Mozilla::CA::SSL_ca_file() if ! %default_ca && do { local $SIG{__DIE__}; eval { require Mozilla::CA; 1 }; }; $ca_detected = 1; return %default_ca; } } # Export some stuff # inet4|inet6|debug will be handled by myself, everything # else will be handled the Exporter way sub import { my $class = shift; my @export; foreach (@_) { if ( /^inet4$/i ) { # explicitly fall back to inet4 @ISA = 'IO::Socket::INET'; @caller_force_inet4 = caller(); # save for warnings for 'inet6' case } elsif ( /^inet6$/i ) { # check if we have already ipv6 as base if ( ! UNIVERSAL::isa( $class, 'IO::Socket::INET6') and ! UNIVERSAL::isa( $class, 'IO::Socket::IP' )) { # either we don't support it or we disabled it by explicitly # loading it with 'inet4'. In this case re-enable but warn # because this is probably an error if ( CAN_IPV6 ) { @ISA = ( CAN_IPV6 ); warn "IPv6 support re-enabled in __PACKAGE__, got disabled in file $caller_force_inet4[1] line $caller_force_inet4[2]"; } else { die "INET6 is not supported, install IO::Socket::IP"; } } } elsif ( /^:?debug(\d+)/ ) { $DEBUG=$1; } else { push @export,$_ } } @_ = ( $class,@export ); goto &Exporter::import; } my %SSL_OBJECT; my %CREATED_IN_THIS_THREAD; sub CLONE { %CREATED_IN_THIS_THREAD = (); } # all keys used internally, these should be cleaned up at end my @all_my_keys = qw( _SSL_arguments _SSL_certificate _SSL_ctx _SSL_fileno _SSL_in_DESTROY _SSL_ioclass_downgrade _SSL_ioclass_upgraded _SSL_last_err _SSL_object _SSL_ocsp_verify _SSL_opened _SSL_opening _SSL_servername ); # we have callbacks associated with contexts, but have no way to access the # current SSL object from these callbacks. To work around this # CURRENT_SSL_OBJECT will be set before calling Net::SSLeay::{connect,accept} # and reset afterwards, so we have access to it inside _internal_error. my $CURRENT_SSL_OBJECT; # You might be expecting to find a new() subroutine here, but that is # not how IO::Socket::INET works. All configuration gets performed in # the calls to configure() and either connect() or accept(). #Call to configure occurs when a new socket is made using #IO::Socket::INET. Returns false (empty list) on failure. sub configure { my ($self, $arg_hash) = @_; return _invalid_object() unless($self); # force initial blocking # otherwise IO::Socket::SSL->new might return undef if the # socket is nonblocking and it fails to connect immediately # for real nonblocking behavior one should create a nonblocking # socket and later call connect explicitly my $blocking = delete $arg_hash->{Blocking}; # because Net::HTTPS simple redefines blocking() to {} (e.g. # return undef) and IO::Socket::INET does not like this we # set Blocking only explicitly if it was set $arg_hash->{Blocking} = 1 if defined ($blocking); $self->configure_SSL($arg_hash) || return; if ($arg_hash->{$family_key} ||= $arg_hash->{Domain} || $arg_hash->{Family}) { # Hack to work around the problem that IO::Socket::IP defaults to # AI_ADDRCONFIG which creates problems if we have only the loopback # interface. If we already know the family this flag is more harmful # then useful. $arg_hash->{GetAddrInfoFlags} = 0 if $IOCLASS eq 'IO::Socket::IP' && ! defined $arg_hash->{GetAddrInfoFlags}; } return $self->_internal_error("@ISA configuration failed",0) if ! $self->SUPER::configure($arg_hash); $self->blocking(0) if defined $blocking && !$blocking; return $self; } sub configure_SSL { my ($self, $arg_hash) = @_; $arg_hash->{Proto} ||= 'tcp'; my $is_server = $arg_hash->{SSL_server}; if ( ! defined $is_server ) { $is_server = $arg_hash->{SSL_server} = $arg_hash->{Listen} || 0; } # add user defined defaults, maybe after filtering $FILTER_SSL_ARGS->($is_server,$arg_hash) if $FILTER_SSL_ARGS; delete @{*$self}{@all_my_keys}; ${*$self}{_SSL_opened} = $is_server; ${*$self}{_SSL_arguments} = $arg_hash; # this adds defaults to $arg_hash as a side effect! ${*$self}{'_SSL_ctx'} = IO::Socket::SSL::SSL_Context->new($arg_hash) or return; return $self; } sub _skip_rw_error { my ($self,$ssl,$rv) = @_; my $err = Net::SSLeay::get_error($ssl,$rv); if ( $err == $Net_SSLeay_ERROR_WANT_READ) { $SSL_ERROR = SSL_WANT_READ; } elsif ( $err == $Net_SSLeay_ERROR_WANT_WRITE) { $SSL_ERROR = SSL_WANT_WRITE; } else { return $err; } $! ||= EWOULDBLOCK; ${*$self}{_SSL_last_err} = [$SSL_ERROR,4] if ref($self); Net::SSLeay::ERR_clear_error(); return 0; } # Call to connect occurs when a new client socket is made using IO::Socket::* sub connect { my $self = shift || return _invalid_object(); return $self if ${*$self}{'_SSL_opened'}; # already connected if ( ! ${*$self}{'_SSL_opening'} ) { # call SUPER::connect if the underlying socket is not connected # if this fails this might not be an error (e.g. if $! = EINPROGRESS # and socket is nonblocking this is normal), so keep any error # handling to the client $DEBUG>=2 && DEBUG('socket not yet connected' ); $self->SUPER::connect(@_) || return; $DEBUG>=2 && DEBUG('socket connected' ); # IO::Socket works around systems, which return EISCONN or similar # on non-blocking re-connect by returning true, even if $! is set # but it does not clear $!, so do it here $! = undef; # don't continue with connect_SSL if SSL_startHandshake is set to 0 my $sh = ${*$self}{_SSL_arguments}{SSL_startHandshake}; return $self if defined $sh && ! $sh; } return $self->connect_SSL; } sub connect_SSL { my $self = shift; my $args = @_>1 ? {@_}: $_[0]||{}; return $self if ${*$self}{'_SSL_opened'}; # already connected my ($ssl,$ctx); if ( ! ${*$self}{'_SSL_opening'} ) { # start ssl connection $DEBUG>=2 && DEBUG('ssl handshake not started' ); ${*$self}{'_SSL_opening'} = 1; my $arg_hash = ${*$self}{'_SSL_arguments'}; my $fileno = ${*$self}{'_SSL_fileno'} = fileno($self); return $self->_internal_error("Socket has no fileno",9) if ! defined $fileno; $ctx = ${*$self}{'_SSL_ctx'}; # Reference to real context $ssl = ${*$self}{'_SSL_object'} = Net::SSLeay::new($ctx->{context}) || return $self->error("SSL structure creation failed"); $CREATED_IN_THIS_THREAD{$ssl} = 1 if $use_threads; $SSL_OBJECT{$ssl} = [$self,0]; weaken($SSL_OBJECT{$ssl}[0]); if ($ctx->{session_cache}) { $arg_hash->{SSL_session_key} ||= do { my $host = $arg_hash->{PeerAddr} || $arg_hash->{PeerHost} || $self->_update_peer; my $port = $arg_hash->{PeerPort} || $arg_hash->{PeerService}; $port ? "$host:$port" : $host; } } Net::SSLeay::set_fd($ssl, $fileno) || return $self->error("SSL filehandle association failed"); if ( $can_client_sni ) { my $host; if ( exists $arg_hash->{SSL_hostname} ) { # explicitly given # can be set to undef/'' to not use extension $host = $arg_hash->{SSL_hostname} } elsif ( $host = $arg_hash->{PeerAddr} || $arg_hash->{PeerHost} ) { # implicitly given $host =~s{:[a-zA-Z0-9_\-]+$}{}; # should be hostname, not IPv4/6 $host = undef if $host !~m{[a-z_]}i or $host =~m{:}; } # define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 # define TLSEXT_NAMETYPE_host_name 0 if ($host) { $DEBUG>=2 && DEBUG("using SNI with hostname $host"); Net::SSLeay::ctrl($ssl,55,0,$host); } else { $DEBUG>=2 && DEBUG("not using SNI because hostname is unknown"); } } elsif ( $arg_hash->{SSL_hostname} ) { return $self->_internal_error( "Client side SNI not supported for this openssl",9); } else { $DEBUG>=2 && DEBUG("not using SNI because openssl is too old"); } $arg_hash->{PeerAddr} || $arg_hash->{PeerHost} || $self->_update_peer; if ( $ctx->{verify_name_ref} ) { # need target name for update my $host = $arg_hash->{SSL_verifycn_name} || $arg_hash->{SSL_hostname}; if ( ! defined $host ) { if ( $host = $arg_hash->{PeerAddr} || $arg_hash->{PeerHost} ) { $host =~s{:[a-zA-Z0-9_\-]+$}{}; } } ${$ctx->{verify_name_ref}} = $host; } my $ocsp = $ctx->{ocsp_mode}; if ( $ocsp & SSL_OCSP_NO_STAPLE ) { # don't try stapling } elsif ( ! $can_ocsp_staple ) { croak("OCSP stapling not support") if $ocsp & SSL_OCSP_MUST_STAPLE; } elsif ( $ocsp & (SSL_OCSP_TRY_STAPLE|SSL_OCSP_MUST_STAPLE)) { # staple by default if verification enabled ${*$self}{_SSL_ocsp_verify} = undef; Net::SSLeay::set_tlsext_status_type($ssl, Net::SSLeay::TLSEXT_STATUSTYPE_ocsp()); $DEBUG>=2 && DEBUG("request OCSP stapling"); } if ($ctx->{session_cache} and my $session = $ctx->{session_cache}->get_session($arg_hash->{SSL_session_key}) ) { Net::SSLeay::set_session($ssl, $session); } } $ssl ||= ${*$self}{'_SSL_object'}; $SSL_ERROR = $! = undef; my $timeout = exists $args->{Timeout} ? $args->{Timeout} : ${*$self}{io_socket_timeout}; # from IO::Socket if ( defined($timeout) && $timeout>0 && $self->blocking(0) ) { $DEBUG>=2 && DEBUG( "set socket to non-blocking to enforce timeout=$timeout" ); # timeout was given and socket was blocking # enforce timeout with now non-blocking socket } else { # timeout does not apply because invalid or socket non-blocking $timeout = undef; } my $start = defined($timeout) && time(); { $SSL_ERROR = undef; $CURRENT_SSL_OBJECT = $self; $DEBUG>=3 && DEBUG("call Net::SSLeay::connect" ); my $rv = Net::SSLeay::connect($ssl); $CURRENT_SSL_OBJECT = undef; $DEBUG>=3 && DEBUG("done Net::SSLeay::connect -> $rv" ); if ( $rv < 0 ) { if ( my $err = $self->_skip_rw_error( $ssl,$rv )) { $self->error("SSL connect attempt failed"); delete ${*$self}{'_SSL_opening'}; ${*$self}{'_SSL_opened'} = -1; $DEBUG>=1 && DEBUG( "fatal SSL error: $SSL_ERROR" ); return $self->fatal_ssl_error(); } $DEBUG>=2 && DEBUG('ssl handshake in progress' ); # connect failed because handshake needs to be completed # if socket was non-blocking or no timeout was given return with this error return if ! defined($timeout); # wait until socket is readable or writable my $rv; if ( $timeout>0 ) { my $vec = ''; vec($vec,$self->fileno,1) = 1; $DEBUG>=2 && DEBUG( "waiting for fd to become ready: $SSL_ERROR" ); $rv = $SSL_ERROR == SSL_WANT_READ ? select( $vec,undef,undef,$timeout) : $SSL_ERROR == SSL_WANT_WRITE ? select( undef,$vec,undef,$timeout) : undef; } else { $DEBUG>=2 && DEBUG("handshake failed because no more time" ); $! = ETIMEDOUT } if ( ! $rv ) { $DEBUG>=2 && DEBUG("handshake failed because socket did not became ready" ); # failed because of timeout, return $! ||= ETIMEDOUT; delete ${*$self}{'_SSL_opening'}; ${*$self}{'_SSL_opened'} = -1; $self->blocking(1); # was blocking before return } # socket is ready, try non-blocking connect again after recomputing timeout $DEBUG>=2 && DEBUG("socket ready, retrying connect" ); my $now = time(); $timeout -= $now - $start; $start = $now; redo; } elsif ( $rv == 0 ) { delete ${*$self}{'_SSL_opening'}; $DEBUG>=2 && DEBUG("connection failed - connect returned 0" ); $self->error("SSL connect attempt failed because of handshake problems" ); ${*$self}{'_SSL_opened'} = -1; return $self->fatal_ssl_error(); } } $DEBUG>=2 && DEBUG('ssl handshake done' ); # ssl connect successful delete ${*$self}{'_SSL_opening'}; ${*$self}{'_SSL_opened'}=1; if (defined($timeout)) { $self->blocking(1); # reset back to blocking $! = undef; # reset errors from non-blocking } $ctx ||= ${*$self}{'_SSL_ctx'}; if ( my $ocsp_result = ${*$self}{_SSL_ocsp_verify} ) { # got result from OCSP stapling if ( $ocsp_result->[0] > 0 ) { $DEBUG>=3 && DEBUG("got OCSP success with stapling"); # successful validated } elsif ( $ocsp_result->[0] < 0 ) { # Permanent problem with validation because certificate # is either self-signed or the issuer cannot be found. # Ignore here, because this will cause other errors too. $DEBUG>=3 && DEBUG("got OCSP failure with stapling: %s", $ocsp_result->[1]); } else { # definitely revoked $DEBUG>=3 && DEBUG("got OCSP revocation with stapling: %s", $ocsp_result->[1]); $self->_internal_error($ocsp_result->[1],5); return $self->fatal_ssl_error(); } } elsif ( $ctx->{ocsp_mode} & SSL_OCSP_MUST_STAPLE ) { $self->_internal_error("did not receive the required stapled OCSP response",5); return $self->fatal_ssl_error(); } if (!%sess_cb and $ctx->{session_cache} and my $session = Net::SSLeay::get1_session($ssl)) { $ctx->{session_cache}->add_session( ${*$self}{_SSL_arguments}{SSL_session_key}, $session ); } tie *{$self}, "IO::Socket::SSL::SSL_HANDLE", $self; return $self; } # called if PeerAddr is not set in ${*$self}{'_SSL_arguments'} # this can be the case if start_SSL is called with a normal IO::Socket::INET # so that PeerAddr|PeerPort are not set from args # returns PeerAddr sub _update_peer { my $self = shift; my $arg_hash = ${*$self}{'_SSL_arguments'}; eval { my $sockaddr = getpeername( $self ); my $af = sockaddr_family($sockaddr); if( CAN_IPV6 && $af == AF_INET6 ) { my (undef, $host, $port) = _getnameinfo($sockaddr, NI_NUMERICHOST | NI_NUMERICSERV); $arg_hash->{PeerPort} = $port; $arg_hash->{PeerAddr} = $host; } else { my ($port,$addr) = sockaddr_in( $sockaddr); $arg_hash->{PeerPort} = $port; $arg_hash->{PeerAddr} = inet_ntoa( $addr ); } } } #Call to accept occurs when a new client connects to a server using #IO::Socket::SSL sub accept { my $self = shift || return _invalid_object(); my $class = shift || 'IO::Socket::SSL'; my $socket = ${*$self}{'_SSL_opening'}; if ( ! $socket ) { # underlying socket not done $DEBUG>=2 && DEBUG('no socket yet' ); $socket = $self->SUPER::accept($class) || return; $DEBUG>=2 && DEBUG('accept created normal socket '.$socket ); # don't continue with accept_SSL if SSL_startHandshake is set to 0 my $sh = ${*$self}{_SSL_arguments}{SSL_startHandshake}; if (defined $sh && ! $sh) { ${*$socket}{_SSL_ctx} = ${*$self}{_SSL_ctx}; ${*$socket}{_SSL_arguments} = { %{${*$self}{_SSL_arguments}}, SSL_server => 0, }; $DEBUG>=2 && DEBUG('will not start SSL handshake yet'); return wantarray ? ($socket, getpeername($socket) ) : $socket } } $self->accept_SSL($socket) || return; $DEBUG>=2 && DEBUG('accept_SSL ok' ); return wantarray ? ($socket, getpeername($socket) ) : $socket; } sub accept_SSL { my $self = shift; my $socket = ( @_ && UNIVERSAL::isa( $_[0], 'IO::Handle' )) ? shift : $self; my $args = @_>1 ? {@_}: $_[0]||{}; my $ssl; if ( ! ${*$self}{'_SSL_opening'} ) { $DEBUG>=2 && DEBUG('starting sslifying' ); ${*$self}{'_SSL_opening'} = $socket; if ($socket != $self) { ${*$socket}{_SSL_ctx} = ${*$self}{_SSL_ctx}; ${*$socket}{_SSL_arguments} = { %{${*$self}{_SSL_arguments}}, SSL_server => 0 }; } my $fileno = ${*$socket}{'_SSL_fileno'} = fileno($socket); return $socket->_internal_error("Socket has no fileno",9) if ! defined $fileno; $ssl = ${*$socket}{_SSL_object} = Net::SSLeay::new(${*$socket}{_SSL_ctx}{context}) || return $socket->error("SSL structure creation failed"); $CREATED_IN_THIS_THREAD{$ssl} = 1 if $use_threads; $SSL_OBJECT{$ssl} = [$socket,1]; weaken($SSL_OBJECT{$ssl}[0]); Net::SSLeay::set_fd($ssl, $fileno) || return $socket->error("SSL filehandle association failed"); } $ssl ||= ${*$socket}{'_SSL_object'}; $SSL_ERROR = $! = undef; #$DEBUG>=2 && DEBUG('calling ssleay::accept' ); my $timeout = exists $args->{Timeout} ? $args->{Timeout} : ${*$self}{io_socket_timeout}; # from IO::Socket if ( defined($timeout) && $timeout>0 && $socket->blocking(0) ) { # timeout was given and socket was blocking # enforce timeout with now non-blocking socket } else { # timeout does not apply because invalid or socket non-blocking $timeout = undef; } my $start = defined($timeout) && time(); { $SSL_ERROR = undef; $CURRENT_SSL_OBJECT = $self; my $rv = Net::SSLeay::accept($ssl); $CURRENT_SSL_OBJECT = undef; $DEBUG>=3 && DEBUG( "Net::SSLeay::accept -> $rv" ); if ( $rv < 0 ) { if ( my $err = $socket->_skip_rw_error( $ssl,$rv )) { $socket->error("SSL accept attempt failed"); delete ${*$self}{'_SSL_opening'}; ${*$socket}{'_SSL_opened'} = -1; return $socket->fatal_ssl_error(); } # accept failed because handshake needs to be completed # if socket was non-blocking or no timeout was given return with this error return if ! defined($timeout); # wait until socket is readable or writable my $rv; if ( $timeout>0 ) { my $vec = ''; vec($vec,$socket->fileno,1) = 1; $rv = $SSL_ERROR == SSL_WANT_READ ? select( $vec,undef,undef,$timeout) : $SSL_ERROR == SSL_WANT_WRITE ? select( undef,$vec,undef,$timeout) : undef; } else { $! = ETIMEDOUT } if ( ! $rv ) { # failed because of timeout, return $! ||= ETIMEDOUT; delete ${*$self}{'_SSL_opening'}; ${*$socket}{'_SSL_opened'} = -1; $socket->blocking(1); # was blocking before return } # socket is ready, try non-blocking accept again after recomputing timeout my $now = time(); $timeout -= $now - $start; $start = $now; redo; } elsif ( $rv == 0 ) { $socket->error("SSL accept attempt failed because of handshake problems" ); delete ${*$self}{'_SSL_opening'}; ${*$socket}{'_SSL_opened'} = -1; return $socket->fatal_ssl_error(); } } $DEBUG>=2 && DEBUG('handshake done, socket ready' ); # socket opened delete ${*$self}{'_SSL_opening'}; ${*$socket}{'_SSL_opened'} = 1; if (defined($timeout)) { $socket->blocking(1); # reset back to blocking $! = undef; # reset errors from non-blocking } tie *{$socket}, "IO::Socket::SSL::SSL_HANDLE", $socket; return $socket; } ####### I/O subroutines ######################## sub _generic_read { my ($self, $read_func, undef, $length, $offset) = @_; my $ssl = ${*$self}{_SSL_object} || return; my $buffer=\$_[2]; $SSL_ERROR = $! = undef; my ($data,$rwerr) = $read_func->($ssl, $length); while ( ! defined($data)) { if ( my $err = $self->_skip_rw_error( $ssl, defined($rwerr) ? $rwerr:-1 )) { if ($err == $Net_SSLeay_ERROR_SYSCALL) { # OpenSSL 1.1.0c+ : EOF can now result in SSL_read returning -1 if (not $!) { # SSL_ERROR_SYSCALL but not errno -> treat as EOF $data = ''; last; } } $self->error("SSL read error"); } return; } $length = length($data); $$buffer = '' if !defined $$buffer; $offset ||= 0; if ($offset>length($$buffer)) { $$buffer.="\0" x ($offset-length($$buffer)); #mimic behavior of read } substr($$buffer, $offset, length($$buffer), $data); return $length; } sub read { my $self = shift; ${*$self}{_SSL_object} && return _generic_read($self, $self->blocking ? \&Net::SSLeay::ssl_read_all : \&Net::SSLeay::read, @_ ); # fall back to plain read if we are not required to use SSL yet return $self->SUPER::read(@_); } # contrary to the behavior of read sysread can read partial data sub sysread { my $self = shift; ${*$self}{_SSL_object} && return _generic_read( $self, \&Net::SSLeay::read, @_ ); # fall back to plain sysread if we are not required to use SSL yet my $rv = $self->SUPER::sysread(@_); return $rv; } sub peek { my $self = shift; ${*$self}{_SSL_object} && return _generic_read( $self, \&Net::SSLeay::peek, @_ ); # fall back to plain peek if we are not required to use SSL yet # emulate peek with recv(...,MS_PEEK) - peek(buf,len,offset) return if ! defined recv($self,my $buf,$_[1],MSG_PEEK); $_[0] = $_[2] ? substr($_[0],0,$_[2]).$buf : $buf; return length($buf); } sub _generic_write { my ($self, $write_all, undef, $length, $offset) = @_; my $ssl = ${*$self}{_SSL_object} || return; my $buffer = \$_[2]; my $buf_len = length($$buffer); $length ||= $buf_len; $offset ||= 0; return $self->_internal_error("Invalid offset for SSL write",9) if $offset>$buf_len; return 0 if ($offset == $buf_len); $SSL_ERROR = $! = undef; my $written; if ( $write_all ) { my $data = $length < $buf_len-$offset ? substr($$buffer, $offset, $length) : $$buffer; ($written, my $errs) = Net::SSLeay::ssl_write_all($ssl, $data); # ssl_write_all returns number of bytes written $written = undef if ! $written && $errs; } else { $written = Net::SSLeay::write_partial( $ssl,$offset,$length,$$buffer ); # write_partial does SSL_write which returns -1 on error $written = undef if $written < 0; } if ( !defined($written) ) { if ( my $err = $self->_skip_rw_error( $ssl,-1 )) { # if $! is not set with ERROR_SYSCALL then report as EPIPE $! ||= EPIPE if $err == $Net_SSLeay_ERROR_SYSCALL; $self->error("SSL write error ($err)"); } return; } return $written; } # if socket is blocking write() should return only on error or # if all data are written sub write { my $self = shift; ${*$self}{_SSL_object} && return _generic_write( $self, scalar($self->blocking),@_ ); # fall back to plain write if we are not required to use SSL yet return $self->SUPER::write(@_); } # contrary to write syswrite() returns already if only # a part of the data is written sub syswrite { my $self = shift; ${*$self}{_SSL_object} && return _generic_write($self,0,@_); # fall back to plain syswrite if we are not required to use SSL yet return $self->SUPER::syswrite(@_); } sub print { my $self = shift; my $string = join(($, or ''), @_, ($\ or '')); return $self->write( $string ); } sub printf { my ($self,$format) = (shift,shift); return $self->write(sprintf($format, @_)); } sub getc { my ($self, $buffer) = (shift, undef); return $buffer if $self->read($buffer, 1, 0); } sub readline { my $self = shift; ${*$self}{_SSL_object} or return $self->SUPER::getline; if ( not defined $/ or wantarray) { # read all and split my $buf = ''; while (1) { my $rv = $self->sysread($buf,2**16,length($buf)); if ( ! defined $rv ) { next if $! == EINTR; # retry last if $! == EWOULDBLOCK || $! == EAGAIN; # use everything so far return; # return error } elsif ( ! $rv ) { last } } if ( ! defined $/ ) { return $buf } elsif ( ref($/)) { my $size = ${$/}; die "bad value in ref \$/: $size" unless $size>0; return $buf=~m{\G(.{1,$size})}g; } elsif ( $/ eq '' ) { return $buf =~m{\G(.*\n\n+|.+)}g; } else { return $buf =~m{\G(.*$/|.+)}g; } } # read only one line if ( ref($/) ) { my $size = ${$/}; # read record of $size bytes die "bad value in ref \$/: $size" unless $size>0; my $buf = ''; while ( $size>length($buf)) { my $rv = $self->sysread($buf,$size-length($buf),length($buf)); if ( ! defined $rv ) { next if $! == EINTR; # retry last if $! == EWOULDBLOCK || $! == EAGAIN; # use everything so far return; # return error } elsif ( ! $rv ) { last } } return $buf; } my ($delim0,$delim1) = $/ eq '' ? ("\n\n","\n"):($/,''); # find first occurrence of $delim0 followed by as much as possible $delim1 my $buf = ''; my $eod = 0; # pointer into $buf after $delim0 $delim1* my $ssl = $self->_get_ssl_object or return; while (1) { # wait until we have more data or eof my $poke = Net::SSLeay::peek($ssl,1); if ( ! defined $poke or $poke eq '' ) { next if $! == EINTR; } my $skip = 0; # peek into available data w/o reading my $pending = Net::SSLeay::pending($ssl); if ( $pending and ( my $pb = Net::SSLeay::peek( $ssl,$pending )) ne '' ) { $buf .= $pb } else { return $buf eq '' ? ():$buf; } if ( !$eod ) { my $pos = index( $buf,$delim0 ); if ( $pos<0 ) { $skip = $pending } else { $eod = $pos + length($delim0); # pos after delim0 } } if ( $eod ) { if ( $delim1 ne '' ) { # delim0 found, check for as much delim1 as possible while ( index( $buf,$delim1,$eod ) == $eod ) { $eod+= length($delim1); } } $skip = $pending - ( length($buf) - $eod ); } # remove data from $self which I already have in buf while ( $skip>0 ) { if ($self->sysread(my $p,$skip,0)) { $skip -= length($p); next; } $! == EINTR or last; } if ( $eod and ( $delim1 eq '' or $eod < length($buf))) { # delim0 found and there can be no more delim1 pending last } } return substr($buf,0,$eod); } sub close { my $self = shift || return _invalid_object(); my $close_args = (ref($_[0]) eq 'HASH') ? $_[0] : {@_}; return if ! $self->stop_SSL( SSL_fast_shutdown => 1, %$close_args, _SSL_ioclass_downgrade => 0, ); if ( ! $close_args->{_SSL_in_DESTROY} ) { untie( *$self ); undef ${*$self}{_SSL_fileno}; return $self->SUPER::close; } return 1; } sub is_SSL { my $self = pop; return ${*$self}{_SSL_object} && 1 } sub stop_SSL { my $self = shift || return _invalid_object(); my $stop_args = (ref($_[0]) eq 'HASH') ? $_[0] : {@_}; $stop_args->{SSL_no_shutdown} = 1 if ! ${*$self}{_SSL_opened}; if (my $ssl = ${*$self}{'_SSL_object'}) { if ( ! $stop_args->{SSL_no_shutdown} ) { my $status = Net::SSLeay::get_shutdown($ssl); my $timeout = not($self->blocking) ? undef : exists $stop_args->{Timeout} ? $stop_args->{Timeout} : ${*$self}{io_socket_timeout}; # from IO::Socket if ($timeout) { $self->blocking(0); $timeout += time(); } while (1) { if ( $status & SSL_SENT_SHUTDOWN and # don't care for received if fast shutdown $status & SSL_RECEIVED_SHUTDOWN || $stop_args->{SSL_fast_shutdown}) { # shutdown complete last; } if ((${*$self}{'_SSL_opened'}||0) <= 0) { # not really open, thus don't expect shutdown to return # something meaningful last; } # initiate or complete shutdown local $SIG{PIPE} = 'IGNORE'; my $rv = Net::SSLeay::shutdown($ssl); if ( $rv < 0 ) { # non-blocking socket? if ( ! $timeout ) { $self->_skip_rw_error( $ssl,$rv ); # need to try again return; } # don't use _skip_rw_error so that existing error does # not get cleared my $wait = $timeout - time(); last if $wait<=0; vec(my $vec = '',fileno($self),1) = 1; my $err = Net::SSLeay::get_error($ssl,$rv); if ( $err == $Net_SSLeay_ERROR_WANT_READ) { select($vec,undef,undef,$wait) } elsif ( $err == $Net_SSLeay_ERROR_WANT_READ) { select(undef,$vec,undef,$wait) } else { last; } } $status |= SSL_SENT_SHUTDOWN; $status |= SSL_RECEIVED_SHUTDOWN if $rv>0; } $self->blocking(1) if $timeout; } # destroy allocated objects for SSL and untie # do not destroy CTX unless explicitly specified Net::SSLeay::free($ssl); if (my $cert = delete ${*$self}{'_SSL_certificate'}) { Net::SSLeay::X509_free($cert); } delete ${*$self}{_SSL_object}; ${*$self}{'_SSL_opened'} = 0; delete $SSL_OBJECT{$ssl}; delete $CREATED_IN_THIS_THREAD{$ssl}; untie(*$self); } if ($stop_args->{'SSL_ctx_free'}) { my $ctx = delete ${*$self}{'_SSL_ctx'}; $ctx && $ctx->DESTROY(); } if ( ! $stop_args->{_SSL_in_DESTROY} ) { my $downgrade = $stop_args->{_SSL_ioclass_downgrade}; if ( $downgrade || ! defined $downgrade ) { # rebless to original class from start_SSL if ( my $orig_class = delete ${*$self}{'_SSL_ioclass_upgraded'} ) { bless $self,$orig_class; # FIXME: if original class was tied too we need to restore the tie # remove all _SSL related from *$self my @sslkeys = grep { m{^_?SSL_} } keys %{*$self}; delete @{*$self}{@sslkeys} if @sslkeys; } } } return 1; } sub fileno { my $self = shift; my $fn = ${*$self}{'_SSL_fileno'}; return defined($fn) ? $fn : $self->SUPER::fileno(); } ####### IO::Socket::SSL specific functions ####### # _get_ssl_object is for internal use ONLY! sub _get_ssl_object { my $self = shift; return ${*$self}{'_SSL_object'} || IO::Socket::SSL->_internal_error("Undefined SSL object",9); } # _get_ctx_object is for internal use ONLY! sub _get_ctx_object { my $self = shift; my $ctx_object = ${*$self}{_SSL_ctx}; return $ctx_object && $ctx_object->{context}; } # default error for undefined arguments sub _invalid_object { return IO::Socket::SSL->_internal_error("Undefined IO::Socket::SSL object",9); } sub pending { my $ssl = shift()->_get_ssl_object || return; return Net::SSLeay::pending($ssl); } sub start_SSL { my ($class,$socket) = (shift,shift); return $class->_internal_error("Not a socket",9) if ! ref($socket); my $arg_hash = @_ == 1 ? $_[0] : {@_}; my %to = exists $arg_hash->{Timeout} ? ( Timeout => delete $arg_hash->{Timeout} ) :(); my $original_class = ref($socket); if ( ! $original_class ) { $socket = ($original_class = $ISA[0])->new_from_fd($socket,'<+') or return $class->_internal_error( "creating $original_class from file handle failed",9); } my $original_fileno = (UNIVERSAL::can($socket, "fileno")) ? $socket->fileno : CORE::fileno($socket); return $class->_internal_error("Socket has no fileno",9) if ! defined $original_fileno; bless $socket, $class; $socket->configure_SSL($arg_hash) or bless($socket, $original_class) && return; ${*$socket}{'_SSL_fileno'} = $original_fileno; ${*$socket}{'_SSL_ioclass_upgraded'} = $original_class if $class ne $original_class; my $start_handshake = $arg_hash->{SSL_startHandshake}; if ( ! defined($start_handshake) || $start_handshake ) { # if we have no callback force blocking mode $DEBUG>=2 && DEBUG( "start handshake" ); my $was_blocking = $socket->blocking(1); my $result = ${*$socket}{'_SSL_arguments'}{SSL_server} ? $socket->accept_SSL(%to) : $socket->connect_SSL(%to); if ( $result ) { $socket->blocking(0) if ! $was_blocking; return $socket; } else { # upgrade to SSL failed, downgrade socket to original class if ( $original_class ) { bless($socket,$original_class); $socket->blocking(0) if ! $was_blocking && $socket->can('blocking'); } return; } } else { $DEBUG>=2 && DEBUG( "don't start handshake: $socket" ); return $socket; # just return upgraded socket } } sub new_from_fd { my ($class, $fd) = (shift,shift); # Check for accidental inclusion of MODE in the argument list if (length($_[0]) < 4) { (my $mode = $_[0]) =~ tr/+<>//d; shift unless length($mode); } my $handle = $ISA[0]->new_from_fd($fd, '+<') || return($class->error("Could not create socket from file descriptor.")); # Annoying workaround for Perl 5.6.1 and below: $handle = $ISA[0]->new_from_fd($handle, '+<'); return $class->start_SSL($handle, @_); } sub dump_peer_certificate { my $ssl = shift()->_get_ssl_object || return; return Net::SSLeay::dump_peer_certificate($ssl); } if ( defined &Net::SSLeay::get_peer_cert_chain && $netssleay_version >= 1.58 ) { *peer_certificates = sub { my $self = shift; my $ssl = $self->_get_ssl_object || return; my @chain = Net::SSLeay::get_peer_cert_chain($ssl); @chain = () if @chain && !$self->peer_certificate; # work around #96013 if ( ${*$self}{_SSL_arguments}{SSL_server} ) { # in the client case the chain contains the peer certificate, # in the server case not # this one has an increased reference counter, the other not if ( my $peer = Net::SSLeay::get_peer_certificate($ssl)) { Net::SSLeay::X509_free($peer); unshift @chain, $peer; } } return @chain; } } else { *peer_certificates = sub { die "peer_certificates needs Net::SSLeay>=1.58"; } } { my %dispatcher = ( issuer => sub { Net::SSLeay::X509_NAME_oneline( Net::SSLeay::X509_get_issuer_name( shift )) }, subject => sub { Net::SSLeay::X509_NAME_oneline( Net::SSLeay::X509_get_subject_name( shift )) }, commonName => sub { my $cn = Net::SSLeay::X509_NAME_get_text_by_NID( Net::SSLeay::X509_get_subject_name( shift ), NID_CommonName); $cn; }, subjectAltNames => sub { Net::SSLeay::X509_get_subjectAltNames( shift ) }, ); # alternative names $dispatcher{authority} = $dispatcher{issuer}; $dispatcher{owner} = $dispatcher{subject}; $dispatcher{cn} = $dispatcher{commonName}; sub peer_certificate { my ($self,$field,$reload) = @_; my $ssl = $self->_get_ssl_object or return; Net::SSLeay::X509_free(delete ${*$self}{_SSL_certificate}) if $reload && ${*$self}{_SSL_certificate}; my $cert = ${*$self}{_SSL_certificate} ||= Net::SSLeay::get_peer_certificate($ssl) or return $self->error("Could not retrieve peer certificate"); if ($field) { my $sub = $dispatcher{$field} or croak "invalid argument for peer_certificate, valid are: ".join( " ",keys %dispatcher ). "\nMaybe you need to upgrade your Net::SSLeay"; return $sub->($cert); } else { return $cert } } sub sock_certificate { my ($self,$field) = @_; my $ssl = $self->_get_ssl_object || return; my $cert = Net::SSLeay::get_certificate( $ssl ) || return; if ($field) { my $sub = $dispatcher{$field} or croak "invalid argument for sock_certificate, valid are: ".join( " ",keys %dispatcher ). "\nMaybe you need to upgrade your Net::SSLeay"; return $sub->($cert); } else { return $cert } } # known schemes, possible attributes are: # - wildcards_in_alt (0, 'full_label', 'anywhere') # - wildcards_in_cn (0, 'full_label', 'anywhere') # - check_cn (0, 'always', 'when_only') # unfortunately there are a lot of different schemes used, see RFC 6125 for a # summary, which references all of the following except RFC4217/ftp my %scheme = ( none => {}, # do not check # default set is a superset of all the others and thus worse than a more # specific set, but much better than not verifying name at all default => { wildcards_in_cn => 'anywhere', wildcards_in_alt => 'anywhere', check_cn => 'always', ip_in_cn => 1, }, ); for(qw( rfc2818 rfc3920 xmpp rfc4217 ftp )) { $scheme{$_} = { wildcards_in_cn => 'anywhere', wildcards_in_alt => 'anywhere', check_cn => 'when_only', } } for(qw(www http)) { $scheme{$_} = { wildcards_in_cn => 'anywhere', wildcards_in_alt => 'anywhere', check_cn => 'when_only', ip_in_cn => 4, } } for(qw( rfc4513 ldap )) { $scheme{$_} = { wildcards_in_cn => 0, wildcards_in_alt => 'full_label', check_cn => 'always', }; } for(qw( rfc2595 smtp rfc4642 imap pop3 acap rfc5539 nntp rfc5538 netconf rfc5425 syslog rfc5953 snmp )) { $scheme{$_} = { wildcards_in_cn => 'full_label', wildcards_in_alt => 'full_label', check_cn => 'always' }; } for(qw( rfc5971 gist )) { $scheme{$_} = { wildcards_in_cn => 'full_label', wildcards_in_alt => 'full_label', check_cn => 'when_only', }; } for(qw( rfc5922 sip )) { $scheme{$_} = { wildcards_in_cn => 0, wildcards_in_alt => 0, check_cn => 'always', }; } # function to verify the hostname # # as every application protocol has its own rules to do this # we provide some default rules as well as a user-defined # callback sub verify_hostname_of_cert { my $identity = shift; my $cert = shift; my $scheme = shift || 'default'; my $publicsuffix = shift; if ( ! ref($scheme) ) { $DEBUG>=3 && DEBUG( "scheme=$scheme cert=$cert" ); $scheme = $scheme{$scheme} || croak("scheme $scheme not defined"); } return 1 if ! %$scheme; # 'none' $identity =~s{\.+$}{}; # ignore absolutism # get data from certificate my $commonName = $dispatcher{cn}->($cert); my @altNames = $dispatcher{subjectAltNames}->($cert); $DEBUG>=3 && DEBUG("identity=$identity cn=$commonName alt=@altNames" ); if ( my $sub = $scheme->{callback} ) { # use custom callback return $sub->($identity,$commonName,@altNames); } # is the given hostname an IP address? Then we have to convert to network byte order [RFC791][RFC2460] my $ipn; if ( CAN_IPV6 and $identity =~m{:} ) { # no IPv4 or hostname have ':' in it, try IPv6. $identity =~m{[^\da-fA-F:\.]} and return; # invalid characters in name $ipn = inet_pton(AF_INET6,$identity) or return; # invalid name } elsif ( my @ip = $identity =~m{^(\d+)(?:\.(\d+)\.(\d+)\.(\d+)|[\d\.]*)$} ) { # check for invalid IP/hostname return if 4 != @ip or 4 != grep { defined($_) && $_<256 } @ip; $ipn = pack("CCCC",@ip); } else { # assume hostname, check for umlauts etc if ( $identity =~m{[^a-zA-Z0-9_.\-]} ) { $identity =~m{\0} and return; # $identity has \\0 byte $identity = idn_to_ascii($identity) or return; # conversation to IDNA failed $identity =~m{[^a-zA-Z0-9_.\-]} and return; # still junk inside } } # do the actual verification my $check_name = sub { my ($name,$identity,$wtyp,$publicsuffix) = @_; $name =~s{\.+$}{}; # ignore absolutism $name eq '' and return; $wtyp ||= ''; my $pattern; ### IMPORTANT! # We accept only a single wildcard and only for a single part of the FQDN # e.g. *.example.org does match www.example.org but not bla.www.example.org # The RFCs are in this regard unspecific but we don't want to have to # deal with certificates like *.com, *.co.uk or even * # see also http://nils.toedtmann.net/pub/subjectAltName.txt . # Also, we fall back to full_label matches if the identity is an IDNA # name, see RFC6125 and the discussion at # http://bugs.python.org/issue17997#msg194950 if ( $wtyp eq 'anywhere' and $name =~m{^([a-zA-Z0-9_\-]*)\*(.+)} ) { return if $1 ne '' and substr($identity,0,4) eq 'xn--'; # IDNA $pattern = qr{^\Q$1\E[a-zA-Z0-9_\-]+\Q$2\E$}i; } elsif ( $wtyp =~ m{^(?:full_label|leftmost)$} and $name =~m{^\*(\..+)$} ) { $pattern = qr{^[a-zA-Z0-9_\-]+\Q$1\E$}i; } else { return lc($identity) eq lc($name); } if ( $identity =~ $pattern ) { $publicsuffix = IO::Socket::SSL::PublicSuffix->default if ! defined $publicsuffix; return 1 if $publicsuffix eq ''; my @labels = split( m{\.+}, $identity ); my $tld = $publicsuffix->public_suffix(\@labels,+1); return 1 if @labels > ( $tld ? 0+@$tld : 1 ); } return; }; my $alt_dnsNames = 0; while (@altNames) { my ($type, $name) = splice (@altNames, 0, 2); if ( $ipn and $type == GEN_IPADD ) { # exact match needed for IP # $name is already packed format (inet_xton) return 1 if $ipn eq $name; } elsif ( ! $ipn and $type == GEN_DNS ) { $name =~s/\s+$//; $name =~s/^\s+//; $alt_dnsNames++; $check_name->($name,$identity,$scheme->{wildcards_in_alt},$publicsuffix) and return 1; } } if ( $scheme->{check_cn} eq 'always' or $scheme->{check_cn} eq 'when_only' and !$alt_dnsNames ) { if ( ! $ipn ) { $check_name->($commonName,$identity,$scheme->{wildcards_in_cn},$publicsuffix) and return 1; } elsif ( $scheme->{ip_in_cn} ) { if ( $identity eq $commonName ) { return 1 if $scheme->{ip_in_cn} == 4 ? length($ipn) == 4 : $scheme->{ip_in_cn} == 6 ? length($ipn) == 8 : 1; } } } return 0; # no match } } sub verify_hostname { my $self = shift; my $host = shift; my $cert = $self->peer_certificate; return verify_hostname_of_cert( $host,$cert,@_ ); } sub get_servername { my $self = shift; return ${*$self}{_SSL_servername} ||= do { my $ssl = $self->_get_ssl_object or return; Net::SSLeay::get_servername($ssl); }; } sub get_fingerprint_bin { my ($self,$algo,$cert,$key_only) = @_; $cert ||= $self->peer_certificate; return $key_only ? Net::SSLeay::X509_pubkey_digest($cert, $algo2digest->($algo || 'sha256')) : Net::SSLeay::X509_digest($cert, $algo2digest->($algo || 'sha256')); } sub get_fingerprint { my ($self,$algo,$cert,$key_only) = @_; $algo ||= 'sha256'; my $fp = get_fingerprint_bin($self,$algo,$cert,$key_only) or return; return $algo.'$'.($key_only ? 'pub$':'').unpack('H*',$fp); } sub get_cipher { my $ssl = shift()->_get_ssl_object || return; return Net::SSLeay::get_cipher($ssl); } sub get_sslversion { my $ssl = shift()->_get_ssl_object || return; my $version = Net::SSLeay::version($ssl) or return; return $version == 0x0304 ? 'TLSv1_3' : $version == 0x0303 ? 'TLSv1_2' : $version == 0x0302 ? 'TLSv1_1' : $version == 0x0301 ? 'TLSv1' : $version == 0x0300 ? 'SSLv3' : $version == 0x0002 ? 'SSLv2' : $version == 0xfeff ? 'DTLS1' : undef; } sub get_sslversion_int { my $ssl = shift()->_get_ssl_object || return; return Net::SSLeay::version($ssl); } sub get_session_reused { return Net::SSLeay::session_reused( shift()->_get_ssl_object || return); } if ($can_ocsp) { no warnings 'once'; *ocsp_resolver = sub { my $self = shift; my $ssl = $self->_get_ssl_object || return; my $ctx = ${*$self}{_SSL_ctx}; return IO::Socket::SSL::OCSP_Resolver->new( $ssl, $ctx->{ocsp_cache} ||= IO::Socket::SSL::OCSP_Cache->new, $ctx->{ocsp_mode} & SSL_OCSP_FAIL_HARD, @_ ? \@_ : $ctx->{ocsp_mode} & SSL_OCSP_FULL_CHAIN ? [ $self->peer_certificates ]: [ $self->peer_certificate ] ); }; } sub errstr { my $self = shift; my $oe = ref($self) && ${*$self}{_SSL_last_err}; return $oe ? $oe->[0] : $SSL_ERROR || ''; } sub fatal_ssl_error { my $self = shift; my $error_trap = ${*$self}{'_SSL_arguments'}->{'SSL_error_trap'}; $@ = $self->errstr; if (defined $error_trap and ref($error_trap) eq 'CODE') { $error_trap->($self, $self->errstr()."\n".$self->get_ssleay_error()); } elsif ( ${*$self}{'_SSL_ioclass_upgraded'} || ${*$self}{_SSL_arguments}{SSL_keepSocketOnError}) { # downgrade only $DEBUG>=3 && DEBUG('downgrading SSL only, not closing socket' ); $self->stop_SSL; } else { # kill socket $self->close } return; } sub get_ssleay_error { #Net::SSLeay will print out the errors itself unless we explicitly #undefine $Net::SSLeay::trace while running print_errs() local $Net::SSLeay::trace; return Net::SSLeay::print_errs('SSL error: ') || ''; } # internal errors, e.g. unsupported features, hostname check failed etc # _SSL_last_err contains severity so that on error chains we can decide if one # error should replace the previous one or if this is just a less specific # follow-up error, e.g. configuration failed because certificate failed because # hostname check went wrong: # 0 - fallback errors # 4 - errors bubbled up from OpenSSL (sub error, r/w error) # 5 - hostname or OCSP verification failed # 9 - fatal problems, e.g. missing feature, no fileno... # _SSL_last_err and SSL_ERROR are only replaced if the error has a higher # severity than the previous one sub _internal_error { my ($self, $error, $severity) = @_; $error = dualvar( -1, $error ); $self = $CURRENT_SSL_OBJECT if !ref($self) && $CURRENT_SSL_OBJECT; if (ref($self)) { my $oe = ${*$self}{_SSL_last_err}; if (!$oe || $oe->[1] <= $severity) { ${*$self}{_SSL_last_err} = [$error,$severity]; $SSL_ERROR = $error; $DEBUG && DEBUG("local error: $error"); } else { $DEBUG && DEBUG("ignoring less severe local error '$error', keep '$oe->[0]'"); } } else { $SSL_ERROR = $error; $DEBUG && DEBUG("global error: $error"); } return; } # OpenSSL errors sub error { my ($self, $error) = @_; my @err; while ( my $err = Net::SSLeay::ERR_get_error()) { push @err, Net::SSLeay::ERR_error_string($err); $DEBUG>=2 && DEBUG( $error."\n".$self->get_ssleay_error()); } $error .= ' '.join(' ',@err) if @err; return $self->_internal_error($error,4) if $error; return; } sub can_client_sni { return $can_client_sni } sub can_server_sni { return $can_server_sni } sub can_multi_cert { return $can_multi_cert } sub can_npn { return $can_npn } sub can_alpn { return $can_alpn } sub can_ecdh { return $can_ecdh } sub can_ipv6 { return CAN_IPV6 } sub can_ocsp { return $can_ocsp } sub can_ticket_keycb { return $can_tckt_keycb } sub can_pha { return $can_pha } sub can_partial_chain { return $check_partial_chain && 1 } sub DESTROY { my $self = shift or return; if (my $ssl = ${*$self}{_SSL_object}) { delete $SSL_OBJECT{$ssl}; if (!$use_threads or delete $CREATED_IN_THIS_THREAD{$ssl}) { $self->close(_SSL_in_DESTROY => 1, SSL_no_shutdown => 1) if ${*$self}{'_SSL_opened'}; } } delete @{*$self}{@all_my_keys}; } #######Extra Backwards Compatibility Functionality####### sub socket_to_SSL { IO::Socket::SSL->start_SSL(@_); } sub socketToSSL { IO::Socket::SSL->start_SSL(@_); } sub kill_socket { shift->close } sub issuer_name { return(shift()->peer_certificate("issuer")) } sub subject_name { return(shift()->peer_certificate("subject")) } sub get_peer_certificate { return shift() } sub context_init { return($GLOBAL_SSL_ARGS = (ref($_[0]) eq 'HASH') ? $_[0] : {@_}); } sub set_default_context { $GLOBAL_SSL_ARGS->{'SSL_reuse_ctx'} = shift; } sub set_default_session_cache { $GLOBAL_SSL_ARGS->{SSL_session_cache} = shift; } { my $set_defaults = sub { my $args = shift; for(my $i=0;$i<@$args;$i+=2 ) { my ($k,$v) = @{$args}[$i,$i+1]; if ( $k =~m{^SSL_} ) { $_->{$k} = $v for(@_); } elsif ( $k =~m{^(name|scheme)$} ) { $_->{"SSL_verifycn_$k"} = $v for (@_); } elsif ( $k =~m{^(callback|mode)$} ) { $_->{"SSL_verify_$k"} = $v for(@_); } else { $_->{"SSL_$k"} = $v for(@_); } } }; sub set_defaults { my %args = @_; $set_defaults->(\@_, $GLOBAL_SSL_ARGS, $GLOBAL_SSL_CLIENT_ARGS, $GLOBAL_SSL_SERVER_ARGS ); } { # deprecated API no warnings; *set_ctx_defaults = \&set_defaults; } sub set_client_defaults { my %args = @_; $set_defaults->(\@_, $GLOBAL_SSL_CLIENT_ARGS ); } sub set_server_defaults { my %args = @_; $set_defaults->(\@_, $GLOBAL_SSL_SERVER_ARGS ); } } sub set_args_filter_hack { my $sub = shift; if ( ref $sub ) { $FILTER_SSL_ARGS = $sub; } elsif ( $sub eq 'use_defaults' ) { # override args with defaults $FILTER_SSL_ARGS = sub { my ($is_server,$args) = @_; %$args = ( %$args, $is_server ? ( %DEFAULT_SSL_SERVER_ARGS, %$GLOBAL_SSL_SERVER_ARGS ) : ( %DEFAULT_SSL_CLIENT_ARGS, %$GLOBAL_SSL_CLIENT_ARGS ) ); } } } sub next_proto_negotiated { my $self = shift; return $self->_internal_error("NPN not supported in Net::SSLeay",9) if ! $can_npn; my $ssl = $self->_get_ssl_object || return; return Net::SSLeay::P_next_proto_negotiated($ssl); } sub alpn_selected { my $self = shift; return $self->_internal_error("ALPN not supported in Net::SSLeay",9) if ! $can_alpn; my $ssl = $self->_get_ssl_object || return; return Net::SSLeay::P_alpn_selected($ssl); } sub opened { my $self = shift; return IO::Handle::opened($self) && ${*$self}{'_SSL_opened'}; } sub opening { my $self = shift; return ${*$self}{'_SSL_opening'}; } sub want_read { shift->errstr == SSL_WANT_READ } sub want_write { shift->errstr == SSL_WANT_WRITE } #Redundant IO::Handle functionality sub getline { return(scalar shift->readline()) } sub getlines { return(shift->readline()) if wantarray(); croak("Use of getlines() not allowed in scalar context"); } #Useless IO::Handle functionality sub truncate { croak("Use of truncate() not allowed with SSL") } sub stat { croak("Use of stat() not allowed with SSL" ) } sub setbuf { croak("Use of setbuf() not allowed with SSL" ) } sub setvbuf { croak("Use of setvbuf() not allowed with SSL" ) } sub fdopen { croak("Use of fdopen() not allowed with SSL" ) } #Unsupported socket functionality sub ungetc { croak("Use of ungetc() not implemented in IO::Socket::SSL") } sub send { croak("Use of send() not implemented in IO::Socket::SSL; use print/printf/syswrite instead") } sub recv { croak("Use of recv() not implemented in IO::Socket::SSL; use read/sysread instead") } package IO::Socket::SSL::SSL_HANDLE; use strict; use Errno 'EBADF'; *weaken = *IO::Socket::SSL::weaken; sub TIEHANDLE { my ($class, $handle) = @_; weaken($handle); bless \$handle, $class; } sub READ { ${shift()}->sysread(@_) } sub READLINE { ${shift()}->readline(@_) } sub GETC { ${shift()}->getc(@_) } sub PRINT { ${shift()}->print(@_) } sub PRINTF { ${shift()}->printf(@_) } sub WRITE { ${shift()}->syswrite(@_) } sub FILENO { ${shift()}->fileno(@_) } sub TELL { $! = EBADF; return -1 } sub BINMODE { return 0 } # not perfect, but better than not implementing the method sub CLOSE { #<---- Do not change this function! my $ssl = ${$_[0]}; local @_; $ssl->close(); } package IO::Socket::SSL::SSL_Context; use Carp; use strict; my %CTX_CREATED_IN_THIS_THREAD; *DEBUG = *IO::Socket::SSL::DEBUG; use constant SSL_MODE_ENABLE_PARTIAL_WRITE => 1; use constant SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER => 2; use constant FILETYPE_PEM => Net::SSLeay::FILETYPE_PEM(); use constant FILETYPE_ASN1 => Net::SSLeay::FILETYPE_ASN1(); my $DEFAULT_SSL_OP = &Net::SSLeay::OP_ALL | &Net::SSLeay::OP_SINGLE_DH_USE | ($can_ecdh && &Net::SSLeay::OP_SINGLE_ECDH_USE); # Note that the final object will actually be a reference to the scalar # (C-style pointer) returned by Net::SSLeay::CTX_*_new() so that # it can be blessed. sub new { my $class = shift; #DEBUG( "$class @_" ); my $arg_hash = (ref($_[0]) eq 'HASH') ? $_[0] : {@_}; my $is_server = $arg_hash->{SSL_server}; my %defaults = $is_server ? (%DEFAULT_SSL_SERVER_ARGS, %$GLOBAL_SSL_ARGS, %$GLOBAL_SSL_SERVER_ARGS) : (%DEFAULT_SSL_CLIENT_ARGS, %$GLOBAL_SSL_ARGS, %$GLOBAL_SSL_CLIENT_ARGS); if ( $defaults{SSL_reuse_ctx} ) { # ignore default context if there are args to override it delete $defaults{SSL_reuse_ctx} if grep { m{^SSL_(?!verifycn_name|hostname)$} } keys %$arg_hash; } %$arg_hash = ( %defaults, %$arg_hash ) if %defaults; if (my $ctx = $arg_hash->{'SSL_reuse_ctx'}) { if ($ctx->isa('IO::Socket::SSL::SSL_Context') and $ctx->{context}) { # valid context } elsif ( $ctx = ${*$ctx}{_SSL_ctx} ) { # reuse context from existing SSL object } return $ctx } # common problem forgetting to set SSL_use_cert # if client cert is given by user but SSL_use_cert is undef, assume that it # should be set if ( ! $is_server && ! defined $arg_hash->{SSL_use_cert} && ( grep { $arg_hash->{$_} } qw(SSL_cert SSL_cert_file)) && ( grep { $arg_hash->{$_} } qw(SSL_key SSL_key_file)) ) { $arg_hash->{SSL_use_cert} = 1 } # if any of SSL_ca* is set don't set the other SSL_ca* # from defaults if ( $arg_hash->{SSL_ca} ) { $arg_hash->{SSL_ca_file} ||= undef $arg_hash->{SSL_ca_path} ||= undef } elsif ( $arg_hash->{SSL_ca_path} ) { $arg_hash->{SSL_ca_file} ||= undef } elsif ( $arg_hash->{SSL_ca_file} ) { $arg_hash->{SSL_ca_path} ||= undef; } # add library defaults $arg_hash->{SSL_use_cert} = $is_server if ! defined $arg_hash->{SSL_use_cert}; # Avoid passing undef arguments to Net::SSLeay defined($arg_hash->{$_}) or delete($arg_hash->{$_}) for(keys %$arg_hash); # check SSL CA, cert etc arguments # some apps set keys '' to signal that it is not set, replace with undef for (qw( SSL_cert SSL_cert_file SSL_key SSL_key_file SSL_ca SSL_ca_file SSL_ca_path SSL_fingerprint )) { $arg_hash->{$_} = undef if defined $arg_hash->{$_} and $arg_hash->{$_} eq ''; } for(qw(SSL_cert_file SSL_key_file)) { defined( my $file = $arg_hash->{$_} ) or next; for my $f (ref($file) eq 'HASH' ? values(%$file):$file ) { die "$_ $f can't be used: $!" if ! open(my $fh,'<',$f) } } my $verify_mode = $arg_hash->{SSL_verify_mode} || 0; if ( $verify_mode != $Net_SSLeay_VERIFY_NONE) { for (qw(SSL_ca_file SSL_ca_path)) { $CHECK_SSL_PATH->($_ => $arg_hash->{$_} || next); } } elsif ( $verify_mode ne '0' ) { # some users use the string 'SSL_VERIFY_PEER' instead of the constant die "SSL_verify_mode must be a number and not a string"; } my $self = bless {},$class; my $vcn_scheme = delete $arg_hash->{SSL_verifycn_scheme}; my $vcn_publicsuffix = delete $arg_hash->{SSL_verifycn_publicsuffix}; if ( ! $is_server and $verify_mode & 0x01 and ! $vcn_scheme || $vcn_scheme ne 'none' ) { # gets updated during configure_SSL my $verify_name; $self->{verify_name_ref} = \$verify_name; my $vcb = $arg_hash->{SSL_verify_callback}; $arg_hash->{SSL_verify_callback} = sub { my ($ok,$ctx_store,$certname,$error,$cert,$depth) = @_; $ok = $vcb->($ok,$ctx_store,$certname,$error,$cert,$depth) if $vcb; $ok or return 0; return $ok if $depth != 0; my $host = $verify_name || ref($vcn_scheme) && $vcn_scheme->{callback} && 'unknown'; if ( ! $host ) { if ( $vcn_scheme ) { IO::Socket::SSL->_internal_error( "Cannot determine peer hostname for verification",8); return 0; } warn "Cannot determine hostname of peer for verification. ". "Disabling default hostname verification for now. ". "Please specify hostname with SSL_verifycn_name and better set SSL_verifycn_scheme too.\n"; return $ok; } elsif ( ! $vcn_scheme && $host =~m{^[\d.]+$|:} ) { # don't try to verify IP by default return $ok; } # verify name my $rv = IO::Socket::SSL::verify_hostname_of_cert( $host,$cert,$vcn_scheme,$vcn_publicsuffix ); if ( ! $rv ) { IO::Socket::SSL->_internal_error( "hostname verification failed",5); } return $rv; }; } if ($is_server) { if ($arg_hash->{SSL_ticket_keycb} && !$can_tckt_keycb) { warn "Ticket Key Callback is not supported - ignoring option SSL_ticket_keycb\n"; delete $arg_hash->{SSL_ticket_keycb}; } } my $ssl_op = $DEFAULT_SSL_OP; my $ver = ''; for (split(/\s*:\s*/,$arg_hash->{SSL_version})) { m{^(!?)(?:(SSL(?:v2|v3|v23|v2/3))|(TLSv1(?:_?[123])?))$}i or croak("invalid SSL_version specified"); my $not = $1; ( my $v = lc($2||$3) ) =~s{^(...)}{\U$1}; if ( $not ) { $ssl_op |= $SSL_OP_NO{$v}; } else { croak("cannot set multiple SSL protocols in SSL_version") if $ver && $v ne $ver; $ver = $v; $ver =~s{/}{}; # interpret SSLv2/3 as SSLv23 $ver =~s{(TLSv1)(\d)}{$1\_$2}; # TLSv1_1 } } my $ctx_new_sub = $ver eq 'TLSv1_3' ? $CTX_tlsv1_3_new : UNIVERSAL::can( 'Net::SSLeay', $ver eq 'SSLv2' ? 'CTX_v2_new' : $ver eq 'SSLv3' ? 'CTX_v3_new' : $ver eq 'TLSv1' ? 'CTX_tlsv1_new' : $ver eq 'TLSv1_1' ? 'CTX_tlsv1_1_new' : $ver eq 'TLSv1_2' ? 'CTX_tlsv1_2_new' : 'CTX_new' ) or return IO::Socket::SSL->_internal_error("SSL Version $ver not supported",9); # For SNI in server mode we need a separate context for each certificate. my %ctx; if ($is_server) { my %sni; for my $opt (qw(SSL_key SSL_key_file SSL_cert SSL_cert_file)) { my $val = $arg_hash->{$opt} or next; if ( ref($val) eq 'HASH' ) { while ( my ($host,$v) = each %$val ) { $sni{lc($host)}{$opt} = $v; } } } while (my ($host,$v) = each %sni) { $ctx{$host} = $host =~m{%} ? $v : { %$arg_hash, %$v }; } } $ctx{''} = $arg_hash if ! %ctx; for my $host (sort keys %ctx) { my $arg_hash = delete $ctx{$host}; my $ctx; if ($host =~m{^([^%]*)%}) { $ctx = $ctx{$1} or return IO::Socket::SSL->error( "SSL Context init for $host failed - no config for $1"); if (my @k = grep { !m{^SSL_(?:cert|key)(?:_file)?$} } keys %$arg_hash) { return IO::Socket::SSL->error( "invalid keys @k in configuration '$host' of additional certs"); } $can_multi_cert or return IO::Socket::SSL->error( "no support for both RSA and ECC certificate in same context"); $host = $1; goto just_configure_certs; } $ctx = $ctx_new_sub->() or return IO::Socket::SSL->error("SSL Context init failed"); $CTX_CREATED_IN_THIS_THREAD{$ctx} = 1 if $use_threads; $ctx{$host} = $ctx; # replace value in %ctx with real context # SSL_OP_CIPHER_SERVER_PREFERENCE $ssl_op |= 0x00400000 if $arg_hash->{SSL_honor_cipher_order}; if ($ver eq 'SSLv23' && !($ssl_op & $SSL_OP_NO{SSLv3})) { # At least LibreSSL disables SSLv3 by default in SSL_CTX_new. # If we really want SSL3.0 we need to explicitly allow it with # SSL_CTX_clear_options. Net::SSLeay::CTX_clear_options($ctx,$SSL_OP_NO{SSLv3}); } Net::SSLeay::CTX_set_options($ctx,$ssl_op); # enable X509_V_FLAG_PARTIAL_CHAIN if possible (OpenSSL 1.1.0+) $check_partial_chain && $check_partial_chain->($ctx); # if we don't set session_id_context if client certificate is expected # client session caching will fail # if user does not provide explicit id just use the stringification # of the context if($arg_hash->{SSL_server} and my $id = $arg_hash->{SSL_session_id_context} || ( $arg_hash->{SSL_verify_mode} & 0x01 ) && "$ctx" ) { Net::SSLeay::CTX_set_session_id_context($ctx,$id,length($id)); } # SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER makes syswrite return if at least one # buffer was written and not block for the rest # SSL_MODE_ENABLE_PARTIAL_WRITE can be necessary for non-blocking because we # cannot guarantee, that the location of the buffer stays constant Net::SSLeay::CTX_set_mode( $ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER|SSL_MODE_ENABLE_PARTIAL_WRITE); if ( my $proto_list = $arg_hash->{SSL_npn_protocols} ) { return IO::Socket::SSL->_internal_error("NPN not supported in Net::SSLeay",9) if ! $can_npn; if($arg_hash->{SSL_server}) { # on server side SSL_npn_protocols means a list of advertised protocols Net::SSLeay::CTX_set_next_protos_advertised_cb($ctx, $proto_list); } else { # on client side SSL_npn_protocols means a list of preferred protocols # negotiation algorithm used is "as-openssl-implements-it" Net::SSLeay::CTX_set_next_proto_select_cb($ctx, $proto_list); } } if ( my $proto_list = $arg_hash->{SSL_alpn_protocols} ) { return IO::Socket::SSL->_internal_error("ALPN not supported in Net::SSLeay",9) if ! $can_alpn; if($arg_hash->{SSL_server}) { Net::SSLeay::CTX_set_alpn_select_cb($ctx, $proto_list); } else { Net::SSLeay::CTX_set_alpn_protos($ctx, $proto_list); } } if ($arg_hash->{SSL_ticket_keycb}) { my $cb = $arg_hash->{SSL_ticket_keycb}; ($cb,my $arg) = ref($cb) eq 'CODE' ? ($cb):@$cb; Net::SSLeay::CTX_set_tlsext_ticket_getkey_cb($ctx,$cb,$arg); } # Try to apply SSL_ca even if SSL_verify_mode is 0, so that they can be # used to verify OCSP responses. # If applying fails complain only if verify_mode != VERIFY_NONE. if ( $arg_hash->{SSL_ca} || defined $arg_hash->{SSL_ca_file} || defined $arg_hash->{SSL_ca_path} ) { my $file = $arg_hash->{SSL_ca_file}; $file = undef if ref($file) eq 'SCALAR' && ! $$file; my $dir = $arg_hash->{SSL_ca_path}; $dir = undef if ref($dir) eq 'SCALAR' && ! $$dir; if ( $arg_hash->{SSL_ca} ) { my $store = Net::SSLeay::CTX_get_cert_store($ctx); for (@{$arg_hash->{SSL_ca}}) { Net::SSLeay::X509_STORE_add_cert($store,$_) or return IO::Socket::SSL->error( "Failed to add certificate to CA store"); } } $dir = join($OPENSSL_LIST_SEPARATOR,@$dir) if ref($dir); if ( $file || $dir and ! Net::SSLeay::CTX_load_verify_locations( $ctx, $file || '', $dir || '')) { return IO::Socket::SSL->error( "Invalid certificate authority locations") if $verify_mode != $Net_SSLeay_VERIFY_NONE; } } elsif ( my %ca = IO::Socket::SSL::default_ca()) { # no CA path given, continue with system defaults my $dir = $ca{SSL_ca_path}; $dir = join($OPENSSL_LIST_SEPARATOR,@$dir) if ref($dir); if (! Net::SSLeay::CTX_load_verify_locations( $ctx, $ca{SSL_ca_file} || '',$dir || '') && $verify_mode != $Net_SSLeay_VERIFY_NONE) { return IO::Socket::SSL->error( "Invalid default certificate authority locations") } } if ($is_server && ($verify_mode & $Net_SSLeay_VERIFY_PEER)) { if ($arg_hash->{SSL_client_ca}) { for (@{$arg_hash->{SSL_client_ca}}) { return IO::Socket::SSL->error( "Failed to add certificate to client CA list") if ! Net::SSLeay::CTX_add_client_CA($ctx,$_); } } if ($arg_hash->{SSL_client_ca_file}) { my $list = Net::SSLeay::load_client_CA_file( $arg_hash->{SSL_client_ca_file}) or return IO::Socket::SSL->error( "Failed to load certificate to client CA list"); Net::SSLeay::CTX_set_client_CA_list($ctx,$list); } } my $X509_STORE_flags = $DEFAULT_X509_STORE_flags; if ($arg_hash->{'SSL_check_crl'}) { $X509_STORE_flags |= Net::SSLeay::X509_V_FLAG_CRL_CHECK(); if ($arg_hash->{'SSL_crl_file'}) { my $bio = Net::SSLeay::BIO_new_file($arg_hash->{'SSL_crl_file'}, 'r'); my $crl = Net::SSLeay::PEM_read_bio_X509_CRL($bio); Net::SSLeay::BIO_free($bio); if ( $crl ) { Net::SSLeay::X509_STORE_add_crl(Net::SSLeay::CTX_get_cert_store($ctx), $crl); Net::SSLeay::X509_CRL_free($crl); } else { return IO::Socket::SSL->error("Invalid certificate revocation list"); } } } Net::SSLeay::X509_STORE_set_flags( Net::SSLeay::CTX_get_cert_store($ctx), $X509_STORE_flags ) if $X509_STORE_flags; Net::SSLeay::CTX_set_default_passwd_cb($ctx,$arg_hash->{SSL_passwd_cb}) if $arg_hash->{SSL_passwd_cb}; just_configure_certs: my ($havekey,$havecert); if ( my $x509 = $arg_hash->{SSL_cert} ) { # binary, e.g. X509* # we have either a single certificate or a list with # a chain of certificates my @x509 = ref($x509) eq 'ARRAY' ? @$x509: ($x509); my $cert = shift @x509; Net::SSLeay::CTX_use_certificate( $ctx,$cert ) || return IO::Socket::SSL->error("Failed to use Certificate"); foreach my $ca (@x509) { Net::SSLeay::CTX_add_extra_chain_cert( $ctx,$ca ) || return IO::Socket::SSL->error("Failed to use Certificate"); } $havecert = 'OBJ'; } elsif ( my $f = $arg_hash->{SSL_cert_file} ) { # try to load chain from PEM or certificate from ASN1 if (Net::SSLeay::CTX_use_certificate_chain_file($ctx,$f)) { $havecert = 'PEM'; } elsif (Net::SSLeay::CTX_use_certificate_file($ctx,$f,FILETYPE_ASN1)) { $havecert = 'DER'; } else { # try to load certificate, key and chain from PKCS12 file my ($key,$cert,@chain) = Net::SSLeay::P_PKCS12_load_file($f,1); if (!$cert and $arg_hash->{SSL_passwd_cb} and defined( my $pw = $arg_hash->{SSL_passwd_cb}->(0))) { ($key,$cert,@chain) = Net::SSLeay::P_PKCS12_load_file($f,1,$pw); } PKCS12: while ($cert) { Net::SSLeay::CTX_use_certificate($ctx,$cert) or last; # Net::SSLeay::P_PKCS12_load_file is implemented using # OpenSSL PKCS12_parse which according to the source code # returns the chain with the last CA certificate first (i.e. # reverse order as in the PKCS12 file). This is not # documented but given the age of this function we'll assume # that this will stay this way in the future. while (my $ca = pop @chain) { Net::SSLeay::CTX_add_extra_chain_cert($ctx,$ca) or last PKCS12; } last if $key && ! Net::SSLeay::CTX_use_PrivateKey($ctx,$key); $havecert = 'PKCS12'; last; } $havekey = 'PKCS12' if $key; Net::SSLeay::X509_free($cert) if $cert; Net::SSLeay::EVP_PKEY_free($key) if $key; # don't free @chain, because CTX_add_extra_chain_cert # did not duplicate the certificates } $havecert or return IO::Socket::SSL->error( "Failed to load certificate from file (no PEM, DER or PKCS12)"); } if (!$havecert || $havekey) { # skip SSL_key_* } elsif ( my $pkey = $arg_hash->{SSL_key} ) { # binary, e.g. EVP_PKEY* Net::SSLeay::CTX_use_PrivateKey($ctx, $pkey) || return IO::Socket::SSL->error("Failed to use Private Key"); $havekey = 'MEM'; } elsif ( my $f = $arg_hash->{SSL_key_file} || (($havecert eq 'PEM') ? $arg_hash->{SSL_cert_file}:undef) ) { for my $ft ( FILETYPE_PEM, FILETYPE_ASN1 ) { if (Net::SSLeay::CTX_use_PrivateKey_file($ctx,$f,$ft)) { $havekey = ($ft == FILETYPE_PEM) ? 'PEM':'DER'; last; } } $havekey or return IO::Socket::SSL->error( "Failed to load key from file (no PEM or DER)"); } Net::SSLeay::CTX_set_post_handshake_auth($ctx,1) if (!$is_server && $can_pha && $havecert && $havekey); } if ($arg_hash->{SSL_server}) { if ( my $f = $arg_hash->{SSL_dh_file} ) { my $bio = Net::SSLeay::BIO_new_file( $f,'r' ) || return IO::Socket::SSL->error( "Failed to open DH file $f" ); my $dh = Net::SSLeay::PEM_read_bio_DHparams($bio); Net::SSLeay::BIO_free($bio); $dh || return IO::Socket::SSL->error( "Failed to read PEM for DH from $f - wrong format?" ); my $rv; for (values (%ctx)) { $rv = Net::SSLeay::CTX_set_tmp_dh( $_,$dh ) or last; } Net::SSLeay::DH_free( $dh ); $rv || return IO::Socket::SSL->error( "Failed to set DH from $f" ); } elsif ( my $dh = $arg_hash->{SSL_dh} ) { # binary, e.g. DH* for( values %ctx ) { Net::SSLeay::CTX_set_tmp_dh( $_,$dh ) || return IO::Socket::SSL->error( "Failed to set DH from SSL_dh" ); } } } if ( my $curve = $arg_hash->{SSL_ecdh_curve} ) { return IO::Socket::SSL->_internal_error( "ECDH curve needs Net::SSLeay>=1.56 and OpenSSL>=1.0",9) if ! $can_ecdh; for(values %ctx) { if ($arg_hash->{SSL_server} and $curve eq 'auto') { if ($can_ecdh eq 'can_auto') { Net::SSLeay::CTX_set_ecdh_auto($_,1) or return IO::Socket::SSL->error( "failed to set ECDH curve context"); } elsif ($can_ecdh eq 'auto') { # automatically enabled anyway } else { return IO::Socket::SSL->error( "SSL_CTX_set_ecdh_auto not implemented"); } } elsif ($set_groups_list) { $set_groups_list->($_,$curve) or return IO::Socket::SSL->error( "failed to set ECDH groups/curves on context"); # needed for OpenSSL 1.0.2 if ($can_ecdh eq 'can_auto') { Net::SSLeay::CTX_set_ecdh_auto($_,1) if $can_ecdh eq 'can_auto'; } elsif ($curve =~m{:}) { return IO::Socket::SSL->error( "SSL_CTX_groups_list or SSL_CTX_curves_list not implemented"); } elsif ($arg_hash->{SSL_server}) { if ( $curve !~ /^\d+$/ ) { # name of curve, find NID $curve = Net::SSLeay::OBJ_txt2nid($curve) || return IO::Socket::SSL->error( "cannot find NID for curve name '$curve'"); } my $ecdh = Net::SSLeay::EC_KEY_new_by_curve_name($curve) or return IO::Socket::SSL->error( "cannot create curve for NID $curve"); for( values %ctx ) { Net::SSLeay::CTX_set_tmp_ecdh($_,$ecdh) or return IO::Socket::SSL->error( "failed to set ECDH curve context"); } Net::SSLeay::EC_KEY_free($ecdh); } } } my $verify_cb = $arg_hash->{SSL_verify_callback}; my @accept_fp; if ( my $fp = $arg_hash->{SSL_fingerprint} ) { for( ref($fp) ? @$fp : $fp) { my ($algo,$pubkey,$digest) = m{^(?:([\w-]+)\$)?(pub\$)?([a-f\d:]+)$}i or return IO::Socket::SSL->_internal_error("invalid fingerprint '$_'",9); ( $digest = lc($digest) ) =~s{:}{}g; $algo ||= length($digest) == 32 ? 'md5' : length($digest) == 40 ? 'sha1' : length($digest) == 64 ? 'sha256' : return IO::Socket::SSL->_internal_error( "cannot detect hash algorithem from fingerprint '$_'",9); $algo = lc($algo); push @accept_fp,[ $algo, $pubkey || '', pack('H*',$digest) ] } } my $verify_fingerprint = @accept_fp && do { my $fail; sub { my ($ok,$cert,$depth) = @_; $fail = 1 if ! $ok; return 1 if $depth>0; # to let us continue with verification # Check fingerprint only from top certificate. my %fp; for(@accept_fp) { my $fp = $fp{$_->[0],$_->[1]} ||= $_->[1] ? Net::SSLeay::X509_pubkey_digest($cert,$algo2digest->($_->[0])) : Net::SSLeay::X509_digest($cert,$algo2digest->($_->[0])); next if $fp ne $_->[2]; return 1; } return ! $fail; } }; my $verify_callback = ( $verify_cb || @accept_fp ) && sub { my ($ok, $ctx_store) = @_; my ($certname,$cert,$error,$depth); if ($ctx_store) { $cert = Net::SSLeay::X509_STORE_CTX_get_current_cert($ctx_store); $error = Net::SSLeay::X509_STORE_CTX_get_error($ctx_store); $depth = Net::SSLeay::X509_STORE_CTX_get_error_depth($ctx_store); $certname = Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_issuer_name($cert)). Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_subject_name($cert)); $error &&= Net::SSLeay::ERR_error_string($error); } $DEBUG>=3 && DEBUG( "ok=$ok [$depth] $certname" ); $ok = $verify_cb->($ok,$ctx_store,$certname,$error,$cert,$depth) if $verify_cb; $ok = $verify_fingerprint->($ok,$cert,$depth) if $verify_fingerprint && $cert; return $ok; }; if ( $^O eq 'darwin' ) { # explicitly set error code to disable use of apples TEA patch # https://hynek.me/articles/apple-openssl-verification-surprises/ my $vcb = $verify_callback; $verify_callback = sub { my $rv = $vcb ? &$vcb : $_[0]; if ( $rv != 1 ) { # 50 - X509_V_ERR_APPLICATION_VERIFICATION: application verification failure Net::SSLeay::X509_STORE_CTX_set_error($_[1], 50); } return $rv; }; } Net::SSLeay::CTX_set_verify($_, $verify_mode, $verify_callback) for (values %ctx); my $staple_callback = $arg_hash->{SSL_ocsp_staple_callback}; if ( !$is_server && $can_ocsp_staple && ! $verify_fingerprint) { $self->{ocsp_cache} = $arg_hash->{SSL_ocsp_cache}; my $status_cb = sub { my ($ssl,$resp) = @_; my $iossl = $SSL_OBJECT{$ssl} or die "no IO::Socket::SSL object found for SSL $ssl"; $iossl->[1] and do { # we must return with 1 or it will be called again # and because we have no SSL object we must make the error global Carp::cluck($IO::Socket::SSL::SSL_ERROR = "OCSP callback on server side"); return 1; }; $iossl = $iossl->[0]; # if we have a callback use this # callback must not free or copy $resp !! if ( $staple_callback ) { $staple_callback->($iossl,$resp); return 1; } # default callback does verification if ( ! $resp ) { $DEBUG>=3 && DEBUG("did not get stapled OCSP response"); return 1; } $DEBUG>=3 && DEBUG("got stapled OCSP response"); my $status = Net::SSLeay::OCSP_response_status($resp); if ($status != Net::SSLeay::OCSP_RESPONSE_STATUS_SUCCESSFUL()) { $DEBUG>=3 && DEBUG("bad status of stapled OCSP response: ". Net::SSLeay::OCSP_response_status_str($status)); return 1; } if (!eval { Net::SSLeay::OCSP_response_verify($ssl,$resp) }) { $DEBUG>=3 && DEBUG("verify of stapled OCSP response failed"); return 1; } my (@results,$hard_error); my @chain = $iossl->peer_certificates; for my $cert (@chain) { my $certid = eval { Net::SSLeay::OCSP_cert2ids($ssl,$cert) }; if (!$certid) { $DEBUG>=3 && DEBUG("cannot create OCSP_CERTID: $@"); push @results,[-1,$@]; last; } ($status) = Net::SSLeay::OCSP_response_results($resp,$certid); if ($status && $status->[2]) { my $cache = ${*$iossl}{_SSL_ctx}{ocsp_cache}; if (!$status->[1]) { push @results,[1,$status->[2]{nextUpdate}]; $cache && $cache->put($certid,$status->[2]); } elsif ( $status->[2]{statusType} == Net::SSLeay::V_OCSP_CERTSTATUS_GOOD()) { push @results,[1,$status->[2]{nextUpdate}]; $cache && $cache->put($certid,{ %{$status->[2]}, expire => time()+120, soft_error => $status->[1], }); } else { push @results,($hard_error = [0,$status->[1]]); $cache && $cache->put($certid,{ %{$status->[2]}, hard_error => $status->[1], }); } } } # return result of lead certificate, this should be in chain[0] and # thus result[0], but we better check. But if we had any hard_error # return this instead if ($hard_error) { ${*$iossl}{_SSL_ocsp_verify} = $hard_error; } elsif (@results and $chain[0] == $iossl->peer_certificate) { ${*$iossl}{_SSL_ocsp_verify} = $results[0]; } return 1; }; Net::SSLeay::CTX_set_tlsext_status_cb($_,$status_cb) for (values %ctx); } if ( my $cl = $arg_hash->{SSL_cipher_list} ) { for (keys %ctx) { Net::SSLeay::CTX_set_cipher_list($ctx{$_}, ref($cl) ? $cl->{$_} || $cl->{''} || $DEFAULT_SSL_ARGS{SSL_cipher_list} || next : $cl ) || return IO::Socket::SSL->error("Failed to set SSL cipher list"); } } # Main context is default context or any other if no default context. my $ctx = $ctx{''} || (values %ctx)[0]; if (keys(%ctx) > 1 || ! exists $ctx{''}) { $can_server_sni or return IO::Socket::SSL->_internal_error( "Server side SNI not supported for this openssl/Net::SSLeay",9); Net::SSLeay::CTX_set_tlsext_servername_callback($ctx, sub { my $ssl = shift; my $host = Net::SSLeay::get_servername($ssl); $host = '' if ! defined $host; my $snictx = $ctx{lc($host)} || $ctx{''} or do { $DEBUG>1 and DEBUG( "cannot get context from servername '$host'"); return 0; }; $DEBUG>1 and DEBUG("set context from servername $host"); Net::SSLeay::set_SSL_CTX($ssl,$snictx) if $snictx != $ctx; return 1; }); } if ( my $cb = $arg_hash->{SSL_create_ctx_callback} ) { $cb->($_) for values (%ctx); } $self->{context} = $ctx; $self->{verify_mode} = $arg_hash->{SSL_verify_mode}; $self->{ocsp_mode} = defined($arg_hash->{SSL_ocsp_mode}) ? $arg_hash->{SSL_ocsp_mode} : $self->{verify_mode} ? IO::Socket::SSL::SSL_OCSP_TRY_STAPLE() : 0; $DEBUG>=3 && DEBUG( "new ctx $ctx" ); if ( my $cache = $arg_hash->{SSL_session_cache} ) { # use predefined cache $self->{session_cache} = $cache } elsif ( my $size = $arg_hash->{SSL_session_cache_size}) { $self->{session_cache} = IO::Socket::SSL::Session_Cache->new( $size ); } if ($self->{session_cache} and %sess_cb) { Net::SSLeay::CTX_set_session_cache_mode($ctx, Net::SSLeay::SESS_CACHE_CLIENT()); my $cache = $self->{session_cache}; $sess_cb{new}($ctx, sub { my ($ssl,$session) = @_; my $self = ($SSL_OBJECT{$ssl} || do { warn "callback session new: no known SSL object for $ssl"; return; })->[0]; my $args = ${*$self}{_SSL_arguments}; my $key = $args->{SSL_session_key} or do { warn "callback session new: no known SSL_session_key for $ssl"; return; }; $DEBUG>=3 && DEBUG("callback session new <$key> $session"); Net::SSLeay::SESSION_up_ref($session); $cache->add_session($key,$session); }); $sess_cb{remove}($ctx, sub { my ($ctx,$session) = @_; $DEBUG>=3 && DEBUG("callback session remove $session"); $cache->del_session(undef,$session); }); } return $self; } sub has_session_cache { return defined shift->{session_cache}; } sub CLONE { %CTX_CREATED_IN_THIS_THREAD = (); } sub DESTROY { my $self = shift; if ( my $ctx = $self->{context} ) { $DEBUG>=3 && DEBUG("free ctx $ctx open=".join( " ",keys %CTX_CREATED_IN_THIS_THREAD )); if (!$use_threads or delete $CTX_CREATED_IN_THIS_THREAD{$ctx} ) { # remove any verify callback for this context if ( $self->{verify_mode}) { $DEBUG>=3 && DEBUG("free ctx $ctx callback" ); Net::SSLeay::CTX_set_verify($ctx, 0,undef); } if ( $self->{ocsp_error_ref}) { $DEBUG>=3 && DEBUG("free ctx $ctx tlsext_status_cb" ); Net::SSLeay::CTX_set_tlsext_status_cb($ctx,undef); } $DEBUG>=3 && DEBUG("OK free ctx $ctx" ); Net::SSLeay::CTX_free($ctx); } } delete(@{$self}{'context','session_cache'}); } package IO::Socket::SSL::Session_Cache; *DEBUG = *IO::Socket::SSL::DEBUG; use constant { SESSION => 0, KEY => 1, GNEXT => 2, GPREV => 3, SNEXT => 4, SPREV => 5, }; sub new { my ($class, $size) = @_; $size>0 or return; return bless { room => $size, ghead => undef, shead => {}, }, $class; } sub add_session { my ($self, $key, $session) = @_; # create new my $v = []; $v->[SESSION] = $session; $v->[KEY] = $key; $DEBUG>=3 && DEBUG("add_session($key,$session)"); _add_entry($self,$v); } sub replace_session { my ($self, $key, $session) = @_; $self->del_session($key); $self->add_session($key, $session); } sub del_session { my ($self, $key, $session) = @_; my ($head,$inext) = $key ? ($self->{shead}{$key},SNEXT) : ($self->{ghead},GNEXT); my $v = $head; my @del; while ($v) { if (!$session) { push @del,$v } elsif ($v->[SESSION] == $session) { push @del, $v; last; } $v = $v->[$inext]; last if $v == $head; } $DEBUG>=3 && DEBUG("del_session(" . ($key ? $key : "undef") . ($session ? ",$session) -> " : ") -> ") . (~~@del || 'none')); for (@del) { _del_entry($self,$_); Net::SSLeay::SESSION_free($_->[SESSION]) if $_->[SESSION]; } return ~~@del; } sub get_session { my ($self, $key, $session) = @_; my $v = $self->{shead}{$key}; if ($session) { my $shead = $v; while ($v) { $DEBUG>=3 && DEBUG("check $session - $v->[SESSION]"); last if $v->[SESSION] == $session; $v = $v->[SNEXT]; $v = undef if $v == $shead; # session not found } } if ($v) { _del_entry($self, $v); # remove _add_entry($self, $v); # and add back on top } $DEBUG>=3 && DEBUG("get_session($key" . ( $session ? ",$session) -> " : ") -> ") . ($v? $v->[SESSION]:"none")); return $v && $v->[SESSION]; } sub _add_entry { my ($self,$v) = @_; for( [ SNEXT, SPREV, \$self->{shead}{$v->[KEY]} ], [ GNEXT, GPREV, \$self->{ghead} ], ) { my ($inext,$iprev,$rhead) = @$_; if ($$rhead) { $v->[$inext] = $$rhead; $v->[$iprev] = ${$rhead}->[$iprev]; ${$rhead}->[$iprev][$inext] = $v; ${$rhead}->[$iprev] = $v; } else { $v->[$inext] = $v->[$iprev] = $v; } $$rhead = $v; } $self->{room}--; # drop old entries if necessary if ($self->{room}<0) { my $l = $self->{ghead}[GPREV]; _del_entry($self,$l); Net::SSLeay::SESSION_free($l->[SESSION]) if $l->[SESSION]; } } sub _del_entry { my ($self,$v) = @_; for( [ SNEXT, SPREV, \$self->{shead}{$v->[KEY]} ], [ GNEXT, GPREV, \$self->{ghead} ], ) { my ($inext,$iprev,$rhead) = @$_; $$rhead or return; $v->[$inext][$iprev] = $v->[$iprev]; $v->[$iprev][$inext] = $v->[$inext]; if ($v != $$rhead) { # not removed from top of list } elsif ($v->[$inext] == $v) { # was only element on list, drop list if ($inext == SNEXT) { delete $self->{shead}{$v->[KEY]}; } else { $$rhead = undef; } } else { # was top element, keep others $$rhead = $v->[$inext]; } } $self->{room}++; } sub _dump { my $self = shift; my %v2i; my $v = $self->{ghead}; while ($v) { exists $v2i{$v} and die; $v2i{$v} = int(keys %v2i); $v = $v->[GNEXT]; last if $v == $self->{ghead}; } my $out = "room: $self->{room}\nghead:\n"; $v = $self->{ghead}; while ($v) { $out .= sprintf(" - [%d] <%d,%d> '%s' <%s>\n", $v2i{$v}, $v2i{$v->[GPREV]}, $v2i{$v->[GNEXT]}, $v->[KEY], $v->[SESSION]); $v = $v->[GNEXT]; last if $v == $self->{ghead}; } $out .= "shead:\n"; for my $key (sort keys %{$self->{shead}}) { $out .= " - '$key'\n"; my $shead = $self->{shead}{$key}; my $v = $shead; while ($v) { $out .= sprintf(" - [%d] <%d,%d> '%s' <%s>\n", $v2i{$v}, $v2i{$v->[SPREV]}, $v2i{$v->[SNEXT]}, $v->[KEY], $v->[SESSION]); $v = $v->[SNEXT]; last if $v == $shead; } } return $out; } sub DESTROY { my $self = shift; delete $self->{shead}; my $v = delete $self->{ghead}; while ($v) { Net::SSLeay::SESSION_free($v->[SESSION]) if $v->[SESSION]; my $next = $v->[GNEXT]; @$v = (); $v = $next; } } package IO::Socket::SSL::OCSP_Cache; sub new { my ($class,$size) = @_; return bless { '' => { _lru => 0, size => $size || 100 } },$class; } sub get { my ($self,$id) = @_; my $e = $self->{$id} or return; $e->{_lru} = $self->{''}{_lru}++; if ( $e->{expire} && time()<$e->{expire}) { delete $self->{$id}; return; } if ( $e->{nextUpdate} && time()<$e->{nextUpdate} ) { delete $self->{$id}; return; } return $e; } sub put { my ($self,$id,$e) = @_; $self->{$id} = $e; $e->{_lru} = $self->{''}{_lru}++; my $del = keys(%$self) - $self->{''}{size}; if ($del>0) { my @k = sort { $self->{$a}{_lru} <=> $self->{$b}{_lru} } keys %$self; delete @{$self}{ splice(@k,0,$del) }; } return $e; } package IO::Socket::SSL::OCSP_Resolver; *DEBUG = *IO::Socket::SSL::DEBUG; # create a new resolver # $ssl - the ssl object # $cache - OCSP_Cache object (put,get) # $failhard - flag if we should fail hard on OCSP problems # $certs - list of certs to verify sub new { my ($class,$ssl,$cache,$failhard,$certs) = @_; my (%todo,$done,$hard_error,@soft_error); for my $cert (@$certs) { # skip entries which have no OCSP uri or where we cannot get a certid # (e.g. self-signed or where we don't have the issuer) my $subj = Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_subject_name($cert)); my $uri = Net::SSLeay::P_X509_get_ocsp_uri($cert) or do { $DEBUG>2 && DEBUG("no URI for certificate $subj"); push @soft_error,"no ocsp_uri for $subj"; next; }; my $certid = eval { Net::SSLeay::OCSP_cert2ids($ssl,$cert) } or do { $DEBUG>2 && DEBUG("no OCSP_CERTID for certificate $subj: $@"); push @soft_error,"no certid for $subj: $@"; next; }; if (!($done = $cache->get($certid))) { push @{ $todo{$uri}{ids} }, $certid; push @{ $todo{$uri}{subj} }, $subj; } elsif ( $done->{hard_error} ) { # one error is enough to fail validation $hard_error = $done->{hard_error}; %todo = (); last; } elsif ( $done->{soft_error} ) { push @soft_error,$done->{soft_error}; } } while ( my($uri,$v) = each %todo) { my $ids = $v->{ids}; $v->{req} = Net::SSLeay::i2d_OCSP_REQUEST( Net::SSLeay::OCSP_ids2req(@$ids)); } $hard_error ||= '' if ! %todo; return bless { ssl => $ssl, cache => $cache, failhard => $failhard, hard_error => $hard_error, soft_error => @soft_error ? join("; ",@soft_error) : undef, todo => \%todo, },$class; } # return current result, e.g. '' for no error, else error # if undef we have no final result yet sub hard_error { return shift->{hard_error} } sub soft_error { return shift->{soft_error} } # return hash with uri => ocsp_request_data for open requests sub requests { my $todo = shift()->{todo}; return map { ($_,$todo->{$_}{req}) } keys %$todo; } # add new response sub add_response { my ($self,$uri,$resp) = @_; my $todo = delete $self->{todo}{$uri}; return $self->{error} if ! $todo || $self->{error}; my ($req,@soft_error,@hard_error); # do we have a response if (!$resp) { @soft_error = "http request for OCSP failed; subject: ". join("; ",@{$todo->{subj}}); # is it a valid OCSP_RESPONSE } elsif ( ! eval { $resp = Net::SSLeay::d2i_OCSP_RESPONSE($resp) }) { @soft_error = "invalid response (no OCSP_RESPONSE); subject: ". join("; ",@{$todo->{subj}}); # hopefully short-time error $self->{cache}->put($_,{ soft_error => "@soft_error", expire => time()+10, }) for (@{$todo->{ids}}); # is the OCSP response status success } elsif ( ( my $status = Net::SSLeay::OCSP_response_status($resp)) != Net::SSLeay::OCSP_RESPONSE_STATUS_SUCCESSFUL() ){ @soft_error = "OCSP response failed: ". Net::SSLeay::OCSP_response_status_str($status). "; subject: ".join("; ",@{$todo->{subj}}); # hopefully short-time error $self->{cache}->put($_,{ soft_error => "@soft_error", expire => time()+10, }) for (@{$todo->{ids}}); # does nonce match the request and can the signature be verified } elsif ( ! eval { $req = Net::SSLeay::d2i_OCSP_REQUEST($todo->{req}); Net::SSLeay::OCSP_response_verify($self->{ssl},$resp,$req); }) { if ($@) { @soft_error = $@ } else { my @err; while ( my $err = Net::SSLeay::ERR_get_error()) { push @soft_error, Net::SSLeay::ERR_error_string($err); } @soft_error = 'failed to verify OCSP response; subject: '. join("; ",@{$todo->{subj}}) if ! @soft_error; } # configuration problem or we don't know the signer $self->{cache}->put($_,{ soft_error => "@soft_error", expire => time()+120, }) for (@{$todo->{ids}}); # extract results from response } elsif ( my @result = Net::SSLeay::OCSP_response_results($resp,@{$todo->{ids}})) { my (@found,@miss); for my $rv (@result) { if ($rv->[2]) { push @found,$rv->[0]; if (!$rv->[1]) { # no error $self->{cache}->put($rv->[0],$rv->[2]); } elsif ( $rv->[2]{statusType} == Net::SSLeay::V_OCSP_CERTSTATUS_GOOD()) { # soft error, like response after nextUpdate push @soft_error,$rv->[1]."; subject: ". join("; ",@{$todo->{subj}}); $self->{cache}->put($rv->[0],{ %{$rv->[2]}, soft_error => "@soft_error", expire => time()+120, }); } else { # hard error $self->{cache}->put($rv->[0],$rv->[2]); push @hard_error, $rv->[1]."; subject: ". join("; ",@{$todo->{subj}}); } } else { push @miss,$rv->[0]; } } if (@miss && @found) { # we sent multiple responses, but server answered only to one # try again $self->{todo}{$uri} = $todo; $todo->{ids} = \@miss; $todo->{req} = Net::SSLeay::i2d_OCSP_REQUEST( Net::SSLeay::OCSP_ids2req(@miss)); $DEBUG>=2 && DEBUG("$uri just answered ".@found." of ".(@found+@miss)." requests"); } } else { @soft_error = "no data in response; subject: ". join("; ",@{$todo->{subj}}); # probably configuration problem $self->{cache}->put($_,{ soft_error => "@soft_error", expire => time()+120, }) for (@{$todo->{ids}}); } Net::SSLeay::OCSP_REQUEST_free($req) if $req; if ($self->{failhard}) { push @hard_error,@soft_error; @soft_error = (); } if (@soft_error) { $self->{soft_error} .= "; " if $self->{soft_error}; $self->{soft_error} .= "$uri: ".join('; ',@soft_error); } if (@hard_error) { $self->{hard_error} = "$uri: ".join('; ',@hard_error); %{$self->{todo}} = (); } elsif ( ! %{$self->{todo}} ) { $self->{hard_error} = '' } return $self->{hard_error}; } # make all necessary requests to get OCSP responses blocking sub resolve_blocking { my ($self,%args) = @_; while ( my %todo = $self->requests ) { eval { require HTTP::Tiny } or die "need HTTP::Tiny installed"; # OCSP responses have their own signature, so we don't need SSL verification my $ua = HTTP::Tiny->new(verify_SSL => 0,%args); while (my ($uri,$reqdata) = each %todo) { $DEBUG && DEBUG("sending OCSP request to $uri"); my $resp = $ua->request('POST',$uri, { headers => { 'Content-type' => 'application/ocsp-request' }, content => $reqdata }); $DEBUG && DEBUG("got OCSP response from $uri code=$resp->{status}"); defined ($self->add_response($uri, $resp->{success} && $resp->{content})) && last; } } $DEBUG>=2 && DEBUG("no more open OCSP requests"); return $self->{hard_error}; } 1; __END__ PKk4]\)55IP.pmnu[# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2010-2015 -- leonerd@leonerd.org.uk package IO::Socket::IP; # $VERSION needs to be set before use base 'IO::Socket' # - https://rt.cpan.org/Ticket/Display.html?id=92107 BEGIN { $VERSION = '0.39'; } use strict; use warnings; use base qw( IO::Socket ); use Carp; use Socket 1.97 qw( getaddrinfo getnameinfo sockaddr_family AF_INET AI_PASSIVE IPPROTO_TCP IPPROTO_UDP IPPROTO_IPV6 IPV6_V6ONLY NI_DGRAM NI_NUMERICHOST NI_NUMERICSERV NIx_NOHOST NIx_NOSERV SO_REUSEADDR SO_REUSEPORT SO_BROADCAST SO_ERROR SOCK_DGRAM SOCK_STREAM SOL_SOCKET ); my $AF_INET6 = eval { Socket::AF_INET6() }; # may not be defined my $AI_ADDRCONFIG = eval { Socket::AI_ADDRCONFIG() } || 0; use POSIX qw( dup2 ); use Errno qw( EINVAL EINPROGRESS EISCONN ENOTCONN ETIMEDOUT EWOULDBLOCK EOPNOTSUPP ); use constant HAVE_MSWIN32 => ( $^O eq "MSWin32" ); # At least one OS (Android) is known not to have getprotobyname() use constant HAVE_GETPROTOBYNAME => defined eval { getprotobyname( "tcp" ) }; my $IPv6_re = do { # translation of RFC 3986 3.2.2 ABNF to re my $IPv4address = do { my $dec_octet = q<(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])>; qq<$dec_octet(?: \\. $dec_octet){3}>; }; my $IPv6address = do { my $h16 = qq<[0-9A-Fa-f]{1,4}>; my $ls32 = qq<(?: $h16 : $h16 | $IPv4address)>; qq<(?: (?: $h16 : ){6} $ls32 | :: (?: $h16 : ){5} $ls32 | (?: $h16 )? :: (?: $h16 : ){4} $ls32 | (?: (?: $h16 : ){0,1} $h16 )? :: (?: $h16 : ){3} $ls32 | (?: (?: $h16 : ){0,2} $h16 )? :: (?: $h16 : ){2} $ls32 | (?: (?: $h16 : ){0,3} $h16 )? :: $h16 : $ls32 | (?: (?: $h16 : ){0,4} $h16 )? :: $ls32 | (?: (?: $h16 : ){0,5} $h16 )? :: $h16 | (?: (?: $h16 : ){0,6} $h16 )? :: )> }; qr<$IPv6address>xo; }; =head1 NAME C - Family-neutral IP socket supporting both IPv4 and IPv6 =head1 SYNOPSIS use IO::Socket::IP; my $sock = IO::Socket::IP->new( PeerHost => "www.google.com", PeerPort => "http", Type => SOCK_STREAM, ) or die "Cannot construct socket - $@"; my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" : ( $sock->sockdomain == PF_INET ) ? "IPv4" : "unknown"; printf "Connected to google via %s\n", $familyname; =head1 DESCRIPTION This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a replacement for L. Most constructor arguments and methods are provided in a backward-compatible way. For a list of known differences, see the C INCOMPATIBILITES section below. It uses the C function to convert hostnames and service names or port numbers into sets of possible addresses to connect to or listen on. This allows it to work for IPv6 where the system supports it, while still falling back to IPv4-only on systems which don't. =head1 REPLACING C DEFAULT BEHAVIOUR By placing C<-register> in the import list, L uses C rather than C as the class that handles C. C will also use C rather than C to handle C, provided that the C constant is available. Changing C's default behaviour means that calling the C constructor with either C or C as the C parameter will yield an C object. use IO::Socket::IP -register; my $sock = IO::Socket->new( Domain => PF_INET6, LocalHost => "::1", Listen => 1, ) or die "Cannot create socket - $@\n"; print "Created a socket of type " . ref($sock) . "\n"; Note that C<-register> is a global setting that applies to the entire program; it cannot be applied only for certain callers, removed, or limited by lexical scope. =cut sub import { my $pkg = shift; my @symbols; foreach ( @_ ) { if( $_ eq "-register" ) { IO::Socket::IP::_ForINET->register_domain( AF_INET ); IO::Socket::IP::_ForINET6->register_domain( $AF_INET6 ) if defined $AF_INET6; } else { push @symbols, $_; } } @_ = ( $pkg, @symbols ); goto &IO::Socket::import; } # Convenient capability test function { my $can_disable_v6only; sub CAN_DISABLE_V6ONLY { return $can_disable_v6only if defined $can_disable_v6only; socket my $testsock, Socket::PF_INET6(), SOCK_STREAM, 0 or die "Cannot socket(PF_INET6) - $!"; if( setsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY, 0 ) { return $can_disable_v6only = 1; } elsif( $! == EINVAL || $! == EOPNOTSUPP ) { return $can_disable_v6only = 0; } else { die "Cannot setsockopt() - $!"; } } } =head1 CONSTRUCTORS =cut =head2 $sock = IO::Socket::IP->new( %args ) Creates a new C object, containing a newly created socket handle according to the named arguments passed. The recognised arguments are: =over 8 =item PeerHost => STRING =item PeerService => STRING Hostname and service name for the peer to C to. The service name may be given as a port number, as a decimal string. =item PeerAddr => STRING =item PeerPort => STRING For symmetry with the accessor methods and compatibility with C, these are accepted as synonyms for C and C respectively. =item PeerAddrInfo => ARRAY Alternate form of specifying the peer to C to. This should be an array of the form returned by C. This parameter takes precedence over the C, C, C and C arguments. =item LocalHost => STRING =item LocalService => STRING Hostname and service name for the local address to C to. =item LocalAddr => STRING =item LocalPort => STRING For symmetry with the accessor methods and compatibility with C, these are accepted as synonyms for C and C respectively. =item LocalAddrInfo => ARRAY Alternate form of specifying the local address to C to. This should be an array of the form returned by C. This parameter takes precedence over the C, C, C and C arguments. =item Family => INT The address family to pass to C (e.g. C, C). Normally this will be left undefined, and C will search using any address family supported by the system. =item Type => INT The socket type to pass to C (e.g. C, C). Normally defined by the caller; if left undefined C may attempt to infer the type from the service name. =item Proto => STRING or INT The IP protocol to use for the socket (e.g. C<'tcp'>, C, C<'udp'>,C). Normally this will be left undefined, and either C or the kernel will choose an appropriate value. May be given either in string name or numeric form. =item GetAddrInfoFlags => INT More flags to pass to the C function. If not supplied, a default of C will be used. These flags will be combined with C if the C argument is given. For more information see the documentation about C in the L module. =item Listen => INT If defined, puts the socket into listening mode where new connections can be accepted using the C method. The value given is used as the C queue size. =item ReuseAddr => BOOL If true, set the C sockopt =item ReusePort => BOOL If true, set the C sockopt (not all OSes implement this sockopt) =item Broadcast => BOOL If true, set the C sockopt =item Sockopts => ARRAY An optional array of other socket options to apply after the three listed above. The value is an ARRAY containing 2- or 3-element ARRAYrefs. Each inner array relates to a single option, giving the level and option name, and an optional value. If the value element is missing, it will be given the value of a platform-sized integer 1 constant (i.e. suitable to enable most of the common boolean options). For example, both options given below are equivalent to setting C. Sockopts => [ [ SOL_SOCKET, SO_REUSEADDR ], [ SOL_SOCKET, SO_REUSEADDR, pack( "i", 1 ) ], ] =item V6Only => BOOL If defined, set the C sockopt when creating C sockets to the given value. If true, a listening-mode socket will only listen on the C addresses; if false it will also accept connections from C addresses. If not defined, the socket option will not be changed, and default value set by the operating system will apply. For repeatable behaviour across platforms it is recommended this value always be defined for listening-mode sockets. Note that not all platforms support disabling this option. Some, at least OpenBSD and MirBSD, will fail with C if you attempt to disable it. To determine whether it is possible to disable, you may use the class method if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) { ... } else { ... } If your platform does not support disabling this option but you still want to listen for both C and C connections you will have to create two listening sockets, one bound to each protocol. =item MultiHomed This C-style argument is ignored, except if it is defined but false. See the C INCOMPATIBILITES section below. However, the behaviour it enables is always performed by C. =item Blocking => BOOL If defined but false, the socket will be set to non-blocking mode. Otherwise it will default to blocking mode. See the NON-BLOCKING section below for more detail. =item Timeout => NUM If defined, gives a maximum time in seconds to block per C call when in blocking mode. If missing, no timeout is applied other than that provided by the underlying operating system. When in non-blocking mode this parameter is ignored. Note that if the hostname resolves to multiple address candidates, the same timeout will apply to each connection attempt individually, rather than to the operation as a whole. Further note that the timeout does not apply to the initial hostname resolve operation, if connecting by hostname. This behviour is copied inspired by C; for more fine grained control over connection timeouts, consider performing a nonblocking connect directly. =back If neither C nor C hints are provided, a default of C and C respectively will be set, to maintain compatibility with C. Other named arguments that are not recognised are ignored. If neither C nor any hosts or addresses are passed, nor any C<*AddrInfo>, then the constructor has no information on which to decide a socket family to create. In this case, it performs a C call with the C flag, no host name, and a service name of C<"0">, and uses the family of the first returned result. If the constructor fails, it will set C<$@> to an appropriate error message; this may be from C<$!> or it may be some other string; not every failure necessarily has an associated C value. =head2 $sock = IO::Socket::IP->new( $peeraddr ) As a special case, if the constructor is passed a single argument (as opposed to an even-sized list of key/value pairs), it is taken to be the value of the C parameter. This is parsed in the same way, according to the behaviour given in the C AND C PARSING section below. =cut sub new { my $class = shift; my %arg = (@_ == 1) ? (PeerHost => $_[0]) : @_; return $class->SUPER::new(%arg); } # IO::Socket may call this one; neaten up the arguments from IO::Socket::INET # before calling our real _configure method sub configure { my $self = shift; my ( $arg ) = @_; $arg->{PeerHost} = delete $arg->{PeerAddr} if exists $arg->{PeerAddr} && !exists $arg->{PeerHost}; $arg->{PeerService} = delete $arg->{PeerPort} if exists $arg->{PeerPort} && !exists $arg->{PeerService}; $arg->{LocalHost} = delete $arg->{LocalAddr} if exists $arg->{LocalAddr} && !exists $arg->{LocalHost}; $arg->{LocalService} = delete $arg->{LocalPort} if exists $arg->{LocalPort} && !exists $arg->{LocalService}; for my $type (qw(Peer Local)) { my $host = $type . 'Host'; my $service = $type . 'Service'; if( defined $arg->{$host} ) { ( $arg->{$host}, my $s ) = $self->split_addr( $arg->{$host} ); # IO::Socket::INET compat - *Host parsed port always takes precedence $arg->{$service} = $s if defined $s; } } $self->_io_socket_ip__configure( $arg ); } # Avoid simply calling it _configure, as some subclasses of IO::Socket::INET on CPAN already take that sub _io_socket_ip__configure { my $self = shift; my ( $arg ) = @_; my %hints; my @localinfos; my @peerinfos; my $listenqueue = $arg->{Listen}; if( defined $listenqueue and ( defined $arg->{PeerHost} || defined $arg->{PeerService} || defined $arg->{PeerAddrInfo} ) ) { croak "Cannot Listen with a peer address"; } if( defined $arg->{GetAddrInfoFlags} ) { $hints{flags} = $arg->{GetAddrInfoFlags}; } else { $hints{flags} = $AI_ADDRCONFIG; } if( defined( my $family = $arg->{Family} ) ) { $hints{family} = $family; } if( defined( my $type = $arg->{Type} ) ) { $hints{socktype} = $type; } if( defined( my $proto = $arg->{Proto} ) ) { unless( $proto =~ m/^\d+$/ ) { my $protonum = HAVE_GETPROTOBYNAME ? getprotobyname( $proto ) : eval { Socket->${\"IPPROTO_\U$proto"}() }; defined $protonum or croak "Unrecognised protocol $proto"; $proto = $protonum; } $hints{protocol} = $proto; } # To maintain compatibility with IO::Socket::INET, imply a default of # SOCK_STREAM + IPPROTO_TCP if neither hint is given if( !defined $hints{socktype} and !defined $hints{protocol} ) { $hints{socktype} = SOCK_STREAM; $hints{protocol} = IPPROTO_TCP; } # Some OSes (NetBSD) don't seem to like just a protocol hint without a # socktype hint as well. We'll set a couple of common ones if( !defined $hints{socktype} and defined $hints{protocol} ) { $hints{socktype} = SOCK_STREAM if $hints{protocol} == IPPROTO_TCP; $hints{socktype} = SOCK_DGRAM if $hints{protocol} == IPPROTO_UDP; } if( my $info = $arg->{LocalAddrInfo} ) { ref $info eq "ARRAY" or croak "Expected 'LocalAddrInfo' to be an ARRAY ref"; @localinfos = @$info; } elsif( defined $arg->{LocalHost} or defined $arg->{LocalService} or HAVE_MSWIN32 and $arg->{Listen} ) { # Either may be undef my $host = $arg->{LocalHost}; my $service = $arg->{LocalService}; unless ( defined $host or defined $service ) { $service = 0; } local $1; # Placate a taint-related bug; [perl #67962] defined $service and $service =~ s/\((\d+)\)$// and my $fallback_port = $1; my %localhints = %hints; $localhints{flags} |= AI_PASSIVE; ( my $err, @localinfos ) = getaddrinfo( $host, $service, \%localhints ); if( $err and defined $fallback_port ) { ( $err, @localinfos ) = getaddrinfo( $host, $fallback_port, \%localhints ); } if( $err ) { $@ = "$err"; $! = EINVAL; return; } } if( my $info = $arg->{PeerAddrInfo} ) { ref $info eq "ARRAY" or croak "Expected 'PeerAddrInfo' to be an ARRAY ref"; @peerinfos = @$info; } elsif( defined $arg->{PeerHost} or defined $arg->{PeerService} ) { defined( my $host = $arg->{PeerHost} ) or croak "Expected 'PeerHost'"; defined( my $service = $arg->{PeerService} ) or croak "Expected 'PeerService'"; local $1; # Placate a taint-related bug; [perl #67962] defined $service and $service =~ s/\((\d+)\)$// and my $fallback_port = $1; ( my $err, @peerinfos ) = getaddrinfo( $host, $service, \%hints ); if( $err and defined $fallback_port ) { ( $err, @peerinfos ) = getaddrinfo( $host, $fallback_port, \%hints ); } if( $err ) { $@ = "$err"; $! = EINVAL; return; } } my $INT_1 = pack "i", 1; my @sockopts_enabled; push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEADDR, $INT_1 ] if $arg->{ReuseAddr}; push @sockopts_enabled, [ SOL_SOCKET, SO_REUSEPORT, $INT_1 ] if $arg->{ReusePort}; push @sockopts_enabled, [ SOL_SOCKET, SO_BROADCAST, $INT_1 ] if $arg->{Broadcast}; if( my $sockopts = $arg->{Sockopts} ) { ref $sockopts eq "ARRAY" or croak "Expected 'Sockopts' to be an ARRAY ref"; foreach ( @$sockopts ) { ref $_ eq "ARRAY" or croak "Bad Sockopts item - expected ARRAYref"; @$_ >= 2 and @$_ <= 3 or croak "Bad Sockopts item - expected 2 or 3 elements"; my ( $level, $optname, $value ) = @$_; # TODO: consider more sanity checking on argument values defined $value or $value = $INT_1; push @sockopts_enabled, [ $level, $optname, $value ]; } } my $blocking = $arg->{Blocking}; defined $blocking or $blocking = 1; my $v6only = $arg->{V6Only}; # IO::Socket::INET defines this key. IO::Socket::IP always implements the # behaviour it requests, so we can ignore it, unless the caller is for some # reason asking to disable it. if( defined $arg->{MultiHomed} and !$arg->{MultiHomed} ) { croak "Cannot disable the MultiHomed parameter"; } my @infos; foreach my $local ( @localinfos ? @localinfos : {} ) { foreach my $peer ( @peerinfos ? @peerinfos : {} ) { next if defined $local->{family} and defined $peer->{family} and $local->{family} != $peer->{family}; next if defined $local->{socktype} and defined $peer->{socktype} and $local->{socktype} != $peer->{socktype}; next if defined $local->{protocol} and defined $peer->{protocol} and $local->{protocol} != $peer->{protocol}; my $family = $local->{family} || $peer->{family} or next; my $socktype = $local->{socktype} || $peer->{socktype} or next; my $protocol = $local->{protocol} || $peer->{protocol} || 0; push @infos, { family => $family, socktype => $socktype, protocol => $protocol, localaddr => $local->{addr}, peeraddr => $peer->{addr}, }; } } if( !@infos ) { # If there was a Family hint then create a plain unbound, unconnected socket if( defined $hints{family} ) { @infos = ( { family => $hints{family}, socktype => $hints{socktype}, protocol => $hints{protocol}, } ); } # If there wasn't, use getaddrinfo()'s AI_ADDRCONFIG side-effect to guess a # suitable family first. else { ( my $err, @infos ) = getaddrinfo( "", "0", \%hints ); if( $err ) { $@ = "$err"; $! = EINVAL; return; } # We'll take all the @infos anyway, because some OSes (HPUX) are known to # ignore the AI_ADDRCONFIG hint and return AF_INET6 even if they don't # support them } } # In the nonblocking case, caller will be calling ->setup multiple times. # Store configuration in the object for the ->setup method # Yes, these are messy. Sorry, I can't help that... ${*$self}{io_socket_ip_infos} = \@infos; ${*$self}{io_socket_ip_idx} = -1; ${*$self}{io_socket_ip_sockopts} = \@sockopts_enabled; ${*$self}{io_socket_ip_v6only} = $v6only; ${*$self}{io_socket_ip_listenqueue} = $listenqueue; ${*$self}{io_socket_ip_blocking} = $blocking; ${*$self}{io_socket_ip_errors} = [ undef, undef, undef ]; # ->setup is allowed to return false in nonblocking mode $self->setup or !$blocking or return undef; return $self; } sub setup { my $self = shift; while(1) { ${*$self}{io_socket_ip_idx}++; last if ${*$self}{io_socket_ip_idx} >= @{ ${*$self}{io_socket_ip_infos} }; my $info = ${*$self}{io_socket_ip_infos}->[${*$self}{io_socket_ip_idx}]; $self->socket( @{$info}{qw( family socktype protocol )} ) or ( ${*$self}{io_socket_ip_errors}[2] = $!, next ); $self->blocking( 0 ) unless ${*$self}{io_socket_ip_blocking}; foreach my $sockopt ( @{ ${*$self}{io_socket_ip_sockopts} } ) { my ( $level, $optname, $value ) = @$sockopt; $self->setsockopt( $level, $optname, $value ) or ( $@ = "$!", return undef ); } if( defined ${*$self}{io_socket_ip_v6only} and defined $AF_INET6 and $info->{family} == $AF_INET6 ) { my $v6only = ${*$self}{io_socket_ip_v6only}; $self->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, pack "i", $v6only ) or ( $@ = "$!", return undef ); } if( defined( my $addr = $info->{localaddr} ) ) { $self->bind( $addr ) or ( ${*$self}{io_socket_ip_errors}[1] = $!, next ); } if( defined( my $listenqueue = ${*$self}{io_socket_ip_listenqueue} ) ) { $self->listen( $listenqueue ) or ( $@ = "$!", return undef ); } if( defined( my $addr = $info->{peeraddr} ) ) { if( $self->connect( $addr ) ) { $! = 0; return 1; } if( $! == EINPROGRESS or $! == EWOULDBLOCK ) { ${*$self}{io_socket_ip_connect_in_progress} = 1; return 0; } # If connect failed but we have no system error there must be an error # at the application layer, like a bad certificate with # IO::Socket::SSL. # In this case don't continue IP based multi-homing because the problem # cannot be solved at the IP layer. return 0 if ! $!; ${*$self}{io_socket_ip_errors}[0] = $!; next; } return 1; } # Pick the most appropriate error, stringified $! = ( grep defined, @{ ${*$self}{io_socket_ip_errors}} )[0]; $@ = "$!"; return undef; } sub connect :method { my $self = shift; # It seems that IO::Socket hides EINPROGRESS errors, making them look like # a success. This is annoying here. # Instead of putting up with its frankly-irritating intentional breakage of # useful APIs I'm just going to end-run around it and call core's connect() # directly if( @_ ) { my ( $addr ) = @_; # Annoyingly IO::Socket's connect() is where the timeout logic is # implemented, so we'll have to reinvent it here my $timeout = ${*$self}{'io_socket_timeout'}; return connect( $self, $addr ) unless defined $timeout; my $was_blocking = $self->blocking( 0 ); my $err = defined connect( $self, $addr ) ? 0 : $!+0; if( !$err ) { # All happy $self->blocking( $was_blocking ); return 1; } elsif( not( $err == EINPROGRESS or $err == EWOULDBLOCK ) ) { # Failed for some other reason $self->blocking( $was_blocking ); return undef; } elsif( !$was_blocking ) { # We shouldn't block anyway return undef; } my $vec = ''; vec( $vec, $self->fileno, 1 ) = 1; if( !select( undef, $vec, $vec, $timeout ) ) { $self->blocking( $was_blocking ); $! = ETIMEDOUT; return undef; } # Hoist the error by connect()ing a second time $err = $self->getsockopt( SOL_SOCKET, SO_ERROR ); $err = 0 if $err == EISCONN; # Some OSes give EISCONN $self->blocking( $was_blocking ); $! = $err, return undef if $err; return 1; } return 1 if !${*$self}{io_socket_ip_connect_in_progress}; # See if a connect attempt has just failed with an error if( my $errno = $self->getsockopt( SOL_SOCKET, SO_ERROR ) ) { delete ${*$self}{io_socket_ip_connect_in_progress}; ${*$self}{io_socket_ip_errors}[0] = $! = $errno; return $self->setup; } # No error, so either connect is still in progress, or has completed # successfully. We can tell by trying to connect() again; either it will # succeed or we'll get EISCONN (connected successfully), or EALREADY # (still in progress). This even works on MSWin32. my $addr = ${*$self}{io_socket_ip_infos}[${*$self}{io_socket_ip_idx}]{peeraddr}; if( connect( $self, $addr ) or $! == EISCONN ) { delete ${*$self}{io_socket_ip_connect_in_progress}; $! = 0; return 1; } else { $! = EINPROGRESS; return 0; } } sub connected { my $self = shift; return defined $self->fileno && !${*$self}{io_socket_ip_connect_in_progress} && defined getpeername( $self ); # ->peername caches, we need to detect disconnection } =head1 METHODS As well as the following methods, this class inherits all the methods in L and L. =cut sub _get_host_service { my $self = shift; my ( $addr, $flags, $xflags ) = @_; defined $addr or $! = ENOTCONN, return; $flags |= NI_DGRAM if $self->socktype == SOCK_DGRAM; my ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags || 0 ); croak "getnameinfo - $err" if $err; return ( $host, $service ); } sub _unpack_sockaddr { my ( $addr ) = @_; my $family = sockaddr_family $addr; if( $family == AF_INET ) { return ( Socket::unpack_sockaddr_in( $addr ) )[1]; } elsif( defined $AF_INET6 and $family == $AF_INET6 ) { return ( Socket::unpack_sockaddr_in6( $addr ) )[1]; } else { croak "Unrecognised address family $family"; } } =head2 ( $host, $service ) = $sock->sockhost_service( $numeric ) Returns the hostname and service name of the local address (that is, the socket address given by the C method). If C<$numeric> is true, these will be given in numeric form rather than being resolved into names. The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call C only once. =cut sub sockhost_service { my $self = shift; my ( $numeric ) = @_; $self->_get_host_service( $self->sockname, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 ); } =head2 $addr = $sock->sockhost Return the numeric form of the local address as a textual representation =head2 $port = $sock->sockport Return the numeric form of the local port number =head2 $host = $sock->sockhostname Return the resolved name of the local address =head2 $service = $sock->sockservice Return the resolved name of the local port number =cut sub sockhost { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, NI_NUMERICHOST, NIx_NOSERV ) )[0] } sub sockport { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, NI_NUMERICSERV, NIx_NOHOST ) )[1] } sub sockhostname { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, 0, NIx_NOSERV ) )[0] } sub sockservice { my $self = shift; scalar +( $self->_get_host_service( $self->sockname, 0, NIx_NOHOST ) )[1] } =head2 $addr = $sock->sockaddr Return the local address as a binary octet string =cut sub sockaddr { my $self = shift; _unpack_sockaddr $self->sockname } =head2 ( $host, $service ) = $sock->peerhost_service( $numeric ) Returns the hostname and service name of the peer address (that is, the socket address given by the C method), similar to the C method. The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call C only once. =cut sub peerhost_service { my $self = shift; my ( $numeric ) = @_; $self->_get_host_service( $self->peername, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 ); } =head2 $addr = $sock->peerhost Return the numeric form of the peer address as a textual representation =head2 $port = $sock->peerport Return the numeric form of the peer port number =head2 $host = $sock->peerhostname Return the resolved name of the peer address =head2 $service = $sock->peerservice Return the resolved name of the peer port number =cut sub peerhost { my $self = shift; scalar +( $self->_get_host_service( $self->peername, NI_NUMERICHOST, NIx_NOSERV ) )[0] } sub peerport { my $self = shift; scalar +( $self->_get_host_service( $self->peername, NI_NUMERICSERV, NIx_NOHOST ) )[1] } sub peerhostname { my $self = shift; scalar +( $self->_get_host_service( $self->peername, 0, NIx_NOSERV ) )[0] } sub peerservice { my $self = shift; scalar +( $self->_get_host_service( $self->peername, 0, NIx_NOHOST ) )[1] } =head2 $addr = $peer->peeraddr Return the peer address as a binary octet string =cut sub peeraddr { my $self = shift; _unpack_sockaddr $self->peername } # This unbelievably dodgy hack works around the bug that IO::Socket doesn't do # it # https://rt.cpan.org/Ticket/Display.html?id=61577 sub accept { my $self = shift; my ( $new, $peer ) = $self->SUPER::accept( @_ ) or return; ${*$new}{$_} = ${*$self}{$_} for qw( io_socket_domain io_socket_type io_socket_proto ); return wantarray ? ( $new, $peer ) : $new; } # This second unbelievably dodgy hack guarantees that $self->fileno doesn't # change, which is useful during nonblocking connect sub socket :method { my $self = shift; return $self->SUPER::socket(@_) if not defined $self->fileno; # I hate core prototypes sometimes... socket( my $tmph, $_[0], $_[1], $_[2] ) or return undef; dup2( $tmph->fileno, $self->fileno ) or die "Unable to dup2 $tmph onto $self - $!"; } # Versions of IO::Socket before 1.35 may leave socktype undef if from, say, an # ->fdopen call. In this case we'll apply a fix BEGIN { if( eval($IO::Socket::VERSION) < 1.35 ) { *socktype = sub { my $self = shift; my $type = $self->SUPER::socktype; if( !defined $type ) { $type = $self->sockopt( Socket::SO_TYPE() ); } return $type; }; } } =head2 $inet = $sock->as_inet Returns a new L instance wrapping the same filehandle. This may be useful in cases where it is required, for backward-compatibility, to have a real object of C type instead of C. The new object will wrap the same underlying socket filehandle as the original, so care should be taken not to continue to use both objects concurrently. Ideally the original C<$sock> should be discarded after this method is called. This method checks that the socket domain is C and will throw an exception if it isn't. =cut sub as_inet { my $self = shift; croak "Cannot downgrade a non-PF_INET socket to IO::Socket::INET" unless $self->sockdomain == AF_INET; return IO::Socket::INET->new_from_fd( $self->fileno, "r+" ); } =head1 NON-BLOCKING If the constructor is passed a defined but false value for the C argument then the socket is put into non-blocking mode. When in non-blocking mode, the socket will not be set up by the time the constructor returns, because the underlying C syscall would otherwise have to block. The non-blocking behaviour is an extension of the C API, unique to C, because the former does not support multi-homed non-blocking connect. When using non-blocking mode, the caller must repeatedly check for writeability on the filehandle (for instance using C