1
2=head1 NAME
3
4IO::Socket::SSL - SSL sockets with IO::Socket interface
5
6=head1 SYNOPSIS
7
8    use strict;
9    use IO::Socket::SSL;
10
11    # simple client
12    my $cl = IO::Socket::SSL->new('www.google.com:443');
13    print $cl "GET / HTTP/1.0\r\n\r\n";
14    print <$cl>;
15
16    # simple server
17    my $srv = IO::Socket::SSL->new(
18	LocalAddr => '0.0.0.0:1234',
19	Listen => 10,
20	SSL_cert_file => 'server-cert.pem',
21	SSL_key_file => 'server-key.pem',
22    );
23    $srv->accept;
24
25=head1 DESCRIPTION
26
27IO::Socket::SSL makes using SSL/TLS much easier by wrapping the necessary
28functionality into the familiar L<IO::Socket> interface and providing secure
29defaults whenever possible.
30This way, existing applications can be made SSL-aware without much effort, at
31least if you do blocking I/O and don't use select or poll.
32
33But, under the hood, SSL is a complex beast.
34So there are lots of methods to make it do what you need if the default
35behavior is not adequate.
36Because it is easy to inadvertently introduce critical security bugs or just
37hard to debug problems, I would recommend studying the following
38documentation carefully.
39
40The documentation consists of the following parts:
41
42=over 4
43
44=item * L</"Essential Information About SSL/TLS">
45
46=item * L</"Basic SSL Client">
47
48=item * L</"Basic SSL Server">
49
50=item * L</"Common Usage Errors">
51
52=item * L</"Common Problems with SSL">
53
54=item * L</"Using Non-Blocking Sockets">
55
56=item * L</"Advanced Usage">
57
58=item * L</"Integration Into Own Modules">
59
60=item * L</"Description Of Methods">
61
62=back
63
64Additional documentation can be found in
65
66=over 4
67
68=item * L<IO::Socket::SSL::Intercept> - Doing Man-In-The-Middle with SSL
69
70=item * L<IO::Socket::SSL::Utils> - Useful functions for certificates etc
71
72=back
73
74
75=head1 Essential Information About SSL/TLS
76
77SSL (Secure Socket Layer) or its successor TLS (Transport Layer Security) are
78protocols to facilitate end-to-end security. These protocols are used when
79accessing web sites (https), delivering or retrieving email, and in lots of other
80use cases.
81In the following documentation we will refer to both SSL and TLS as simply 'SSL'.
82
83SSL enables end-to-end security by providing two essential functions:
84
85=over 4
86
87=item Encryption
88
89This part encrypts the data for transit between the communicating parties, so
90that nobody in between can read them. It also provides tamper resistance so that
91nobody in between can manipulate the data.
92
93=item Identification
94
95This part makes sure that you talk to the right peer.
96If the identification is done incorrectly it is easy to mount man-in-the-middle
97attacks, e.g. if Alice wants to talk to Bob it would be possible for Mallory to
98put itself in the middle, so that Alice talks to Mallory and Mallory to Bob.
99All the data would still be encrypted, but not end-to-end between Alice and Bob,
100but only between Alice and Mallory and then between Mallory and Bob.
101Thus Mallory would be able to read and modify all traffic between Alice and Bob.
102
103=back
104
105Identification is the part which is the hardest to understand and the easiest
106to get wrong.
107
108With SSL, the Identification is usually done with B<certificates> inside a B<PKI>
109(Public Key Infrastructure).
110These Certificates are comparable to an identity card, which contains
111information about the owner of the card. The card then is somehow B<signed> by
112the B<issuer> of the card, the B<CA> (Certificate Agency).
113
114To verify the identity of the peer the following must be done inside SSL:
115
116=over 4
117
118=item *
119
120Get the certificate from the peer.
121If the peer does not present a certificate we cannot verify it.
122
123=item *
124
125Check if we trust the certificate, e.g. make sure it's not a forgery.
126
127We believe that a certificate is not a fake if we either know the certificate
128already or if we B<trust> the issuer (the CA) and can verify the issuers
129signature on the certificate.
130In reality there is often a hierarchy of certificate agencies and we only
131directly trust the root of this hierarchy.
132In this case the peer not only sends his own certificate, but also all
133B<intermediate certificates>.
134Verification will be done by building a B<trust path> from the trusted root up
135to the peers certificate and checking in each step if the we can verify the
136issuer's signature.
137
138This step often causes problems because the client does not know the necessary
139trusted root certificates. These are usually stored in a system dependent
140CA store, but often the browsers have their own CA store.
141
142=item *
143
144Check if the certificate is still valid.
145Each certificate has a lifetime and should not be used after that time because
146it might be compromised or the underlying cryptography got broken in the mean
147time.
148
149=item *
150
151Check if the subject of the certificate matches the peer.
152This is like comparing the picture on the identity card against the person
153representing the identity card.
154
155When connecting to a server this is usually done by comparing the hostname used
156for connecting against the names represented in the certificate.
157A certificate might contain multiple names or wildcards, so that it can be used
158for multiple hosts (e.g.  *.example.com and *.example.org).
159
160Although nobody sane would accept an identity card where the picture does not
161match the person we see, it is a common implementation error with SSL to omit
162this check or get it wrong.
163
164=item *
165
166Check if the certificate was revoked by the issuer.
167This might be the case if the certificate was compromised somehow and now
168somebody else might use it to claim the wrong identity.
169Such revocations happened a lot after the heartbleed attack.
170
171For SSL there are two ways to verify a revocation, CRL and OCSP.
172With CRLs (Certificate Revocation List) the CA provides a list of serial numbers
173for revoked certificates. The client somehow has to download the list
174(which can be huge) and keep it up to date.
175With OCSP (Online Certificate Status Protocol) the client can check a single
176certificate directly by asking the issuer.
177
178Revocation is the hardest part of the verification and none of today's browsers
179get it fully correct. But, they are still better than most other implementations
180which don't implement revocation checks or leave the hard parts to the
181developer.
182
183=back
184
185When accessing a web site with SSL or delivering mail in a secure way the
186identity is usually only checked one way, e.g. the client wants to make sure it
187talks to the right server, but the server usually does not care which client it
188talks to.
189But, sometimes the server wants to identify the client too and will request a
190certificate from the client which the server must verify in a similar way.
191
192
193=head1 Basic SSL Client
194
195A basic SSL client is simple:
196
197    my $client = IO::Socket::SSL->new('www.example.com:443')
198	or die "error=$!, ssl_error=$SSL_ERROR";
199
200This will take the OpenSSL default CA store as the store for the trusted CA.
201This usually works on UNIX systems.
202If there are no certificates in the store it will try use L<Mozilla::CA> which
203provides the default CAs of Firefox.
204
205In the default settings, L<IO::Socket::SSL> will use a safer cipher set and SSL
206version, do a proper hostname check against the certificate, and use SNI (server
207name indication) to send the hostname inside the SSL handshake. This is
208necessary to work with servers which have different certificates behind the
209same IP address.
210It will also check the revocation of the certificate with OCSP, but currently
211only if the server provides OCSP stapling (for deeper checks see
212C<ocsp_resolver> method).
213
214Lots of options can be used to change ciphers, SSL version, location of CA and
215much more. See documentation of methods for details.
216
217With protocols like SMTP it is necessary to upgrade an existing socket to SSL.
218This can be done like this:
219
220    my $client = IO::Socket::INET->new('mx.example.com:25') or die $!;
221    # .. read greeting from server
222    # .. send EHLO and read response
223    # .. send STARTTLS command and read response
224    # .. if response was successful we can upgrade the socket to SSL now:
225    IO::Socket::SSL->start_SSL($client,
226	# explicitly set hostname we should use for SNI
227	SSL_hostname => 'mx.example.com'
228    ) or die $SSL_ERROR;
229
230A more complete example for a simple HTTP client:
231
232    my $client = IO::Socket::SSL->new(
233	# where to connect
234	PeerHost => "www.example.com",
235	PeerPort => "https",
236
237	# certificate verification - VERIFY_PEER is default
238	SSL_verify_mode => SSL_VERIFY_PEER,
239
240	# location of CA store
241	# need only be given if default store should not be used
242	SSL_ca_path => '/etc/ssl/certs', # typical CA path on Linux
243	SSL_ca_file => '/etc/ssl/cert.pem', # typical CA file on BSD
244
245	# or just use default path on system:
246	IO::Socket::SSL::default_ca(), # either explicitly
247	# or implicitly by not giving SSL_ca_*
248
249	# easy hostname verification
250	# It will use PeerHost as default name a verification
251	# scheme as default, which is safe enough for most purposes.
252	SSL_verifycn_name => 'foo.bar',
253	SSL_verifycn_scheme => 'http',
254
255	# SNI support - defaults to PeerHost
256	SSL_hostname => 'foo.bar',
257
258    ) or die "failed connect or ssl handshake: $!,$SSL_ERROR";
259
260    # send and receive over SSL connection
261    print $client "GET / HTTP/1.0\r\n\r\n";
262    print <$client>;
263
264And to do revocation checks with OCSP (only available with OpenSSL 1.0.0 or
265higher and L<Net::SSLeay> 1.59 or higher):
266
267    # default will try OCSP stapling and check only leaf certificate
268    my $client = IO::Socket::SSL->new($dst);
269
270    # better yet: require checking of full chain
271    my $client = IO::Socket::SSL->new(
272	PeerAddr => $dst,
273	SSL_ocsp_mode => SSL_OCSP_FULL_CHAIN,
274    );
275
276    # even better: make OCSP errors fatal
277    # (this will probably fail with lots of sites because of bad OCSP setups)
278    # also use common OCSP response cache
279    my $ocsp_cache = IO::Socket::SSL::OCSP_Cache->new;
280    my $client = IO::Socket::SSL->new(
281	PeerAddr => $dst,
282	SSL_ocsp_mode => SSL_OCSP_FULL_CHAIN|SSL_OCSP_FAIL_HARD,
283	SSL_ocsp_cache => $ocsp_cache,
284    );
285
286    # disable OCSP stapling in case server has problems with it
287    my $client = IO::Socket::SSL->new(
288	PeerAddr => $dst,
289	SSL_ocsp_mode => SSL_OCSP_NO_STAPLE,
290    );
291
292    # check any certificates which are not yet checked by OCSP stapling or
293    # where we have already cached results. For your own resolving combine
294    # $ocsp->requests with $ocsp->add_response(uri,response).
295    my $ocsp = $client->ocsp_resolver();
296    my $errors = $ocsp->resolve_blocking();
297    if ($errors) {
298	warn "OCSP verification failed: $errors";
299	close($client);
300    }
301
302=head1 Basic SSL Server
303
304A basic SSL server looks similar to other L<IO::Socket> servers, only that it
305also contains settings for certificate and key:
306
307    # simple server
308    my $server = IO::Socket::SSL->new(
309	# where to listen
310	LocalAddr => '127.0.0.1',
311	LocalPort => 8080,
312	Listen => 10,
313
314	# which certificate to offer
315	# with SNI support there can be different certificates per hostname
316	SSL_cert_file => 'cert.pem',
317	SSL_key_file => 'key.pem',
318    ) or die "failed to listen: $!";
319
320    # accept client
321    my $client = $server->accept or die
322	"failed to accept or ssl handshake: $!,$SSL_ERROR";
323
324This will automatically use a secure set of ciphers and SSL version and also
325supports Forward Secrecy with (Elliptic-Curve) Diffie-Hellmann Key Exchange.
326
327If you are doing a forking or threading server, we recommend that you do the SSL
328handshake inside the new process/thread so that the master is free for new
329connections.
330We recommend this because a client with improper or slow SSL handshake could
331make the server block in the handshake which would be bad to do on the
332listening socket:
333
334    # inet server
335    my $server = IO::Socket::INET->new(
336	# where to listen
337	LocalAddr => '127.0.0.1',
338	LocalPort => 8080,
339	Listen => 10,
340    );
341
342    # accept client
343    my $client = $server->accept or die;
344
345    # SSL upgrade client (in new process/thread)
346    IO::Socket::SSL->start_SSL($client,
347	SSL_server => 1,
348	SSL_cert_file => 'cert.pem',
349	SSL_key_file => 'key.pem',
350    ) or die "failed to ssl handshake: $SSL_ERROR";
351
352Like with normal sockets, neither forking nor threading servers scale well.
353It is recommended to use non-blocking sockets instead, see
354L</"Using Non-Blocking Sockets">
355
356=head1 Common Usage Errors
357
358This is a list of typical errors seen with the use of L<IO::Socket::SSL>:
359
360=over 4
361
362=item *
363
364Disabling verification with C<SSL_verify_mode>.
365
366As described in L</"Essential Information About SSL/TLS">, a proper
367identification of the peer is essential and failing to verify makes
368Man-In-The-Middle attacks possible.
369
370Nevertheless, lots of scripts and even public modules or applications disable
371verification, because it is probably the easiest way to make the thing work
372and usually nobody notices any security problems anyway.
373
374If the verification does not succeed with the default settings, one can do the
375following:
376
377=over 8
378
379=item *
380
381Make sure the needed CAs are in the store, maybe use C<SSL_ca_file> or
382C<SSL_ca_path> to specify a different CA store.
383
384=item *
385
386If the validation fails because the certificate is self-signed and that's what
387you expect, you can use the C<SSL_fingerprint> option to accept specific
388leaf certificates by their certificate or pubkey fingerprint.
389
390=item *
391
392If the validation failed because the hostname does not match and you cannot
393access the host with the name given in the certificate, you can use
394C<SSL_verifycn_name> to specify the hostname you expect in the certificate.
395
396=back
397
398A common error pattern is also to disable verification if they found no CA
399store (different modules look at different "default" places).
400Because L<IO::Socket::SSL> is now able to provide a usable CA store on most
401platforms (UNIX, Mac OSX and Windows) it is better to use the defaults provided
402by L<IO::Socket::SSL>.
403If necessary these can be checked with the C<default_ca> method.
404
405=item *
406
407Polling of SSL sockets (e.g. select, poll and other event loops).
408
409If you sysread one byte on a normal socket it will result in a syscall to read
410one byte. Thus, if more than one byte is available on the socket it will be kept
411in the network stack of your OS and the next select or poll call will return the
412socket as readable.
413But, with SSL you don't deliver single bytes. Multiple data bytes are packaged
414and encrypted together in an SSL frame. Decryption can only be done on the whole
415frame, so a sysread for one byte actually reads the complete SSL frame from the
416socket, decrypts it and returns the first decrypted byte. Further sysreads will
417return more bytes from the same frame until all bytes are returned and the
418next SSL frame will be read from the socket.
419
420Thus, in order to decide if you can read more data (e.g. if sysread will block)
421you must check if there are still data in the current SSL frame by calling
422C<pending> and if there are no data pending you might check the underlying
423socket with select or poll.
424Another way might be if you try to sysread at least 16kByte all the time.
42516kByte is the maximum size of an SSL frame and because sysread returns data
426from only a single SSL frame you can guarantee that there are no pending
427data.
428
429Additionally, contrary to plain sockets the  data delivered on the socket are
430not necessarily application payload.
431It might be a TLS handshake, it might just be the beginning of a TLS record or
432it might be TLS session tickets which are send after the TLS handshake in TLS
4331.3.
434In such situations select will return that data are available for read since it
435only looks at the plain socket.
436A sysread on the IO::Socket::SSL socket will not return any data though since it
437is an abstraction which only returns application data.
438This causes the sysread to hang in case the socket was blocking or to return
439an error with EAGAIN on non-blocking sockets.
440Applications using select or similar should therefore set the socket to
441non-blocking and also expect that the sysread might temporarily fail with
442EAGAIN.
443
444See also L</"Using Non-Blocking Sockets">.
445
446=item *
447
448Expecting exactly the same behavior as plain sockets.
449
450IO::Socket::SSL tries to emulate the usual socket behavior as good as possible,
451but full emulation can not be done. Specifically a read on the SSL socket might
452also result in a write on the TCP socket or a write on the SSL socket might
453result in a read on the TCP socket. Also C<accept> and B<close> on the SSL
454socket will result in writing and reading data to the TCP socket too.
455
456Especially the hidden writes might result in a connection reset if the
457underlying TCP socket is already closed by the peer. Unless signal PIPE is
458explicitly handled by the application this will usually result in the
459application crashing. It is thus recommended to explicitly IGNORE signal PIPE so
460that the errors get propagated as EPIPE instead of causing a crash of the
461application.
462
463=item *
464
465Set 'SSL_version' or 'SSL_cipher_list' to a "better" value.
466
467L<IO::Socket::SSL> tries to set these values to reasonable, secure values which
468are compatible with the rest of the world.
469But, there are some scripts or modules out there which tried to be smart and
470get more secure or compatible settings.
471Unfortunately, they did this years ago and never updated these values, so they
472are still forced to do only 'TLSv1' (instead of also using TLSv12 or TLSv11).
473Or they set 'HIGH' as the cipher list and thought they were secure, but did not
474notice that 'HIGH' includes anonymous ciphers, e.g. without identification of
475the peer.
476
477So it is recommended to leave the settings at the secure defaults which
478L<IO::Socket::SSL> sets and which get updated from time to time to
479better fit the real world.
480
481=item *
482
483Make SSL settings inaccessible by the user, together with bad builtin settings.
484
485Some modules use L<IO::Socket::SSL>, but don't make the SSL settings available
486to the user. This is often combined with bad builtin settings or defaults (like
487switching verification off).
488
489Thus the user needs to hack around these restrictions by using
490C<set_args_filter_hack> or similar.
491
492=item *
493
494Use of constants as strings.
495
496Constants like C<SSL_VERIFY_PEER> or C<SSL_WANT_READ> should be used as
497constants and not be put inside quotes, because they represent numerical values.
498
499=item *
500
501Forking and handling the socket in parent and child.
502
503A B<fork> of the process will duplicate the internal user space SSL state of the
504socket. If both master and child interact with the socket by using their own SSL
505state strange error messages will happen. Such interaction includes explicit or
506implicit B<close> of the SSL socket. To avoid this the socket should be explicitly
507closed with B<SSL_no_shutdown>.
508
509=item *
510
511Forking and executing a new process.
512
513Since the SSL state is stored in user space it will be duplicated by a B<fork> but
514it will be lost when doing B<exec>. This means it is not possible to simply
515redirect stdin and stdout for the new process to the SSL socket by duplicating
516the relevant file handles. Instead explicitly exchanging plain data between
517child-process and SSL socket are needed.
518
519=back
520
521
522
523=head1 Common Problems with SSL
524
525SSL is a complex protocol with multiple implementations and each of these has
526their own quirks. While most of these implementations work together, it often
527gets problematic with older versions, minimal versions in load balancers, or plain
528wrong setups.
529
530Unfortunately these problems are hard to debug.
531Helpful for debugging are a knowledge of SSL internals, wireshark and the use of
532the debug settings of L<IO::Socket::SSL> and L<Net::SSLeay>, which can both be
533set with C<$IO::Socket::SSL::DEBUG>.
534The following debugs levels are defined, but used not in any consistent way:
535
536=over 4
537
538=item *
539
5400 - No debugging (default).
541
542=item *
543
5441 - Print out errors from L<IO::Socket::SSL> and ciphers from L<Net::SSLeay>.
545
546=item *
547
5482 - Print also information about call flow from L<IO::Socket::SSL> and progress
549information from L<Net::SSLeay>.
550
551=item *
552
5533 - Print also some data dumps from L<IO::Socket::SSL> and from L<Net::SSLeay>.
554
555=back
556
557Also, C<analyze-ssl.pl> from the ssl-tools repository at
558L<https://github.com/noxxi/p5-ssl-tools>  might be a helpful tool when debugging
559SSL problems, as do the C<openssl> command line tool and a check with a
560different SSL implementation (e.g. a web browser).
561
562The following problems are not uncommon:
563
564=over 4
565
566=item *
567
568Bad server setup: missing intermediate certificates.
569
570It is a regular problem that administrators fail to include all necessary
571certificates into their server setup, e.g. everything needed to build the trust
572chain from the trusted root.
573If they check the setup with the browser everything looks ok, because browsers
574work around these problems by caching any intermediate certificates and apply
575them to new connections if certificates are missing.
576
577But, fresh browser profiles which have never seen these intermediates cannot
578fill in the missing certificates and fail to verify; the same is true with
579L<IO::Socket::SSL>.
580
581=item *
582
583Old versions of servers or load balancers which do not understand specific TLS
584versions or croak on specific data.
585
586From time to time one encounters an SSL peer, which just closes the connection
587inside the SSL handshake. This can usually be worked around by downgrading the
588SSL version, e.g. by setting C<SSL_version>. Modern Browsers usually deal with
589such servers by automatically downgrading the SSL version and repeat the
590connection attempt until they succeed.
591
592Worse servers do not close the underlying TCP connection but instead just
593drop the relevant packet. This is harder to detect because it looks like a
594stalled connection. But downgrading the SSL version often works here too.
595
596A cause of such problems are often load balancers or security devices, which
597have hardware acceleration and only a minimal (and less robust) SSL stack. They
598can often be detected because they support much fewer ciphers than other
599implementations.
600
601=item *
602
603Bad or old OpenSSL versions.
604
605L<IO::Socket::SSL> uses OpenSSL with the help of the L<Net::SSLeay> library. It
606is recommend to have a recent version of this library, because it has more
607features and usually fewer known bugs.
608
609=item *
610
611Validation of client certificates fail.
612
613Make sure that the purpose of the certificate allows use as ssl client (check
614with C<< openssl x509 -purpose >>, that the necessary root certificate is in the
615path specified by C<SSL_ca*> (or the default path) and that any intermediate
616certificates needed to build the trust chain are sent by the client.
617
618=item *
619
620Validation of self-signed certificate fails even if it is given with
621C<SSL_ca*> argument.
622
623The C<SSL_ca*> arguments do not give a general trust store for arbitrary
624certificates but only specify a store for CA certificates which then can be used
625to verify other certificates.  This especially means that certificates which are
626not a CA get simply ignored, notably self-signed certificates which do not also
627have the CA-flag set.
628
629This behavior of OpenSSL differs from the more general trust-store concept which
630can be found in browsers and where it is possible to simply added arbitrary
631certificates (CA or not) as trusted.
632
633
634=back
635
636
637
638=head1 Using Non-Blocking Sockets
639
640If you have a non-blocking socket, the expected behavior on read, write, accept
641or connect is to set C<$!> to EWOULDBLOCK if the operation cannot be completed
642immediately. Note that EWOULDBLOCK is the same as EAGAIN on UNIX systems, but
643is different on Windows.
644
645With SSL, handshakes might occur at any time, even within an established
646connection. In these cases it is necessary to finish the handshake before
647you can read or write data. This might result in situations where you want to
648read but must first finish the write of a handshake or where you want to write
649but must first finish a read.
650In these cases C<$!> is set to EAGAIN like expected, and additionally
651C<$SSL_ERROR> is set to either SSL_WANT_READ or SSL_WANT_WRITE.
652Thus if you get EWOULDBLOCK on a SSL socket you must check C<$SSL_ERROR> for
653SSL_WANT_* and adapt your event mask accordingly.
654
655Using readline on non-blocking sockets does not make much sense and I would
656advise against using it.
657And, while the behavior is not documented for other L<IO::Socket> classes, it
658will try to emulate the behavior seen there, e.g. to return the received data
659instead of blocking, even if the line is not complete. If an unrecoverable error
660occurs it will return nothing, even if it already received some data.
661
662Also, I would advise against using C<accept> with a non-blocking SSL object
663because it might block and this is not what most would expect. The reason for
664this is that C<accept> on a non-blocking TCP socket (e.g. L<IO::Socket::IP>,
665L<IO::Socket::INET>..) results in a new TCP socket which does not inherit the
666non-blocking behavior of the master socket. And thus, the initial SSL handshake
667on the new socket inside C<IO::Socket::SSL::accept> will be done in a blocking
668way. To work around this you are safer by doing a TCP accept and later upgrade the
669TCP socket in a non-blocking way with C<start_SSL> and C<accept_SSL>.
670
671    my $cl = IO::Socket::SSL->new($dst);
672    $cl->blocking(0);
673    my $sel = IO::Select->new($cl);
674    while (1) {
675	# with SSL a call for reading n bytes does not result in reading of n
676	# bytes from the socket, but instead it must read at least one full SSL
677	# frame. If the socket has no new bytes, but there are unprocessed data
678	# from the SSL frame can_read will block!
679
680	# wait for data on socket
681	$sel->can_read();
682
683	# new data on socket or eof
684	READ:
685	# this does not read only 1 byte from socket, but reads the complete SSL
686	# frame and then just returns one byte. On subsequent calls it than
687	# returns more byte of the same SSL frame until it needs to read the
688	# next frame.
689	my $n = sysread( $cl,my $buf,1);
690	if ( ! defined $n ) {
691	    die $! if not $!{EWOULDBLOCK};
692	    next if $SSL_ERROR == SSL_WANT_READ;
693	    if ( $SSL_ERROR == SSL_WANT_WRITE ) {
694		# need to write data on renegotiation
695		$sel->can_write;
696		next;
697	    }
698	    die "something went wrong: $SSL_ERROR";
699	} elsif ( ! $n ) {
700	    last; # eof
701	} else {
702	    # read next bytes
703	    # we might have still data within the current SSL frame
704	    # thus first process these data instead of waiting on the underlying
705	    # socket object
706	    goto READ if $cl->pending;    # goto sysread
707	    next;                         # goto $sel->can_read
708	}
709    }
710
711
712Additionally there are differences to plain sockets when using select, poll,
713kqueue or similar technologies to get notified if data are available.
714Relying only on these calls is not sufficient in all cases since unread data
715might be internally buffered in the SSL stack. To detect such buffering
716B<pending()> need to be used. Alternatively the buffering can be avoided by using
717B<sysread> with the maximum size of an SSL frame. See L</"Common Usage Errors">
718for details.
719
720=head1 Advanced Usage
721
722=head2 SNI Support
723
724Newer extensions to SSL can distinguish between multiple hostnames on the same
725IP address using Server Name Indication (SNI).
726
727Support for SNI on the client side was added somewhere in the OpenSSL 0.9.8
728series, but with 1.0 a bug was fixed when the server could not decide about
729its hostname. Therefore client side SNI is only supported with OpenSSL 1.0 or
730higher in L<IO::Socket::SSL>.
731With a supported version, SNI is used automatically on the client side, if it
732can determine the hostname from C<PeerAddr> or C<PeerHost> (which are synonyms
733in the underlying IO::Socket:: classes and thus should never be set both or at
734least not to different values).
735On unsupported OpenSSL versions it will silently not use SNI.
736The hostname can also be given explicitly given with C<SSL_hostname>, but in
737this case it will throw in error, if SNI is not supported.
738To check for support you might call C<< IO::Socket::SSL->can_client_sni() >>.
739
740On the server side, earlier versions of OpenSSL are supported, but only together
741with L<Net::SSLeay> version >= 1.50.
742To check for support you might call C<< IO::Socket::SSL->can_server_sni() >>.
743If server side SNI is supported, you might specify different certificates per
744host with C<SSL_cert*> and C<SSL_key*>, and check the requested name using
745C<get_servername>.
746
747=head2 Talk Plain and SSL With The Same Socket
748
749It is often required to first exchange some plain data and then upgrade the
750socket to SSL after some kind of STARTTLS command. Protocols like FTPS even
751need a way to downgrade the socket again back to plain.
752
753The common way to do this would be to create a normal socket and use C<start_SSL>
754to upgrade and stop_SSL to downgrade:
755
756    my $sock = IO::Socket::INET->new(...) or die $!;
757    ... exchange plain data on $sock until starttls command ...
758    IO::Socket::SSL->start_SSL($sock,%sslargs) or die $SSL_ERROR;
759    ... now $sock is an IO::Socket::SSL object ...
760    ... exchange data with SSL on $sock until stoptls command ...
761    $sock->stop_SSL or die $SSL_ERROR;
762    ... now $sock is again an IO::Socket::INET object ...
763
764But, lots of modules just derive directly from L<IO::Socket::INET>.
765While this base class can be replaced with L<IO::Socket::SSL>, these modules cannot
766easily support different base classes for SSL and plain data and switch between
767these classes on a starttls command.
768
769To help in this case, L<IO::Socket::SSL> can be reduced to a plain socket on
770startup, and connect_SSL/accept_SSL/start_SSL can be used to enable SSL and
771C<stop_SSL> to talk plain again:
772
773    my $sock = IO::Socket::SSL->new(
774	PeerAddr => ...
775	SSL_startHandshake => 0,
776	%sslargs
777    ) or die $!;
778    ... exchange plain data on $sock until starttls command ...
779    $sock->connect_SSL or die $SSL_ERROR;
780    ... now $sock is an IO::Socket::SSL object ...
781    ... exchange data with SSL on $sock until stoptls command ...
782    $sock->stop_SSL or die $SSL_ERROR;
783    ... $sock is still an IO::Socket::SSL object ...
784    ... but data exchanged again in plain ...
785
786
787=head1 Integration Into Own Modules
788
789L<IO::Socket::SSL> behaves similarly to other L<IO::Socket> modules and thus could
790be integrated in the same way, but you have to take special care when using
791non-blocking I/O (like for handling timeouts) or using select or poll.
792Please study the documentation on how to deal with these differences.
793
794Also, it is recommended to not set or touch most of the C<SSL_*> options, so
795that they keep their secure defaults. It is also recommended to let the user
796override these SSL specific settings without the need of global settings or hacks
797like C<set_args_filter_hack>.
798
799The notable exception is C<SSL_verifycn_scheme>.
800This should be set to the hostname verification scheme required by the module or
801protocol.
802
803
804
805
806=head1 Description Of Methods
807
808L<IO::Socket::SSL> inherits from another L<IO::Socket> module.
809The choice of the super class depends on the installed modules:
810
811=over 4
812
813=item *
814
815If L<IO::Socket::IP> with at least version 0.20 is installed it will use this
816module as super class, transparently providing IPv6 and IPv4 support.
817
818=item *
819
820If L<IO::Socket::INET6> is installed it will use this module as super class,
821transparently providing IPv6 and IPv4 support.
822
823=item *
824
825Otherwise it will fall back to L<IO::Socket::INET>, which is a perl core module.
826With L<IO::Socket::INET> you only get IPv4 support.
827
828=back
829
830Please be aware that with the IPv6 capable super classes, it will look first
831for the IPv6 address of a given hostname. If the resolver provides an IPv6
832address, but the host cannot be reached by IPv6, there will be no automatic
833fallback to IPv4.
834To avoid these problems you can enforce IPv4 for a specific socket by
835using the C<Domain> or C<Family> option with the value AF_INET as described in
836L<IO::Socket::IP>. Alternatively you can enforce IPv4 globally by loading
837L<IO::Socket::SSL> with the option 'inet4', in which case it will use the IPv4
838only class L<IO::Socket::INET> as the super class.
839
840L<IO::Socket::SSL> will provide all of the methods of its super class, but
841sometimes it will override them to match the behavior expected from SSL or to
842provide additional arguments.
843
844The new or changed methods are described below, but please also read the
845section about SSL specific error handling.
846
847=over 4
848
849=item Error Handling
850
851If an SSL specific error occurs, the global variable C<$SSL_ERROR> will be set.
852If the error occurred on an existing SSL socket, the method C<errstr> will
853give access to the latest socket specific error.
854Both C<$SSL_ERROR> and the C<errstr> method give a dualvar similar to C<$!>, e.g.
855providing an error number in numeric context or an error description in string
856context.
857
858
859=item B<new(...)>
860
861Creates a new L<IO::Socket::SSL> object.  You may use all the friendly options
862that came bundled with the super class (e.g. L<IO::Socket::IP>,
863L<IO::Socket::INET>, ...) plus (optionally) the ones described below.
864If you don't specify any SSL related options it will do its best in using
865secure defaults, e.g. choosing good ciphers, enabling proper verification, etc.
866
867=over 2
868
869=item SSL_server
870
871Set this option to a true value if the socket should be used as a server.
872If this is not explicitly set it is assumed if the C<Listen> parameter is given
873when creating the socket.
874
875=item SSL_hostname
876
877This can be given to specify the hostname used for SNI, which is needed if you
878have multiple SSL hostnames on the same IP address. If not given it will try to
879determine the hostname from C<PeerAddr>, which will fail if only an IP was given or if
880this argument is used within C<start_SSL>.
881
882If you want to disable SNI, set this argument to ''.
883
884Currently only supported for the client side and will be ignored for the server
885side.
886
887See section "SNI Support" for details of SNI the support.
888
889=item SSL_startHandshake
890
891If this option is set to false (defaults to true) it will not start the SSL
892handshake yet. This has to be done later with C<accept_SSL> or C<connect_SSL>.
893Before the handshake is started read/write/etc. can be used to exchange plain
894data.
895
896=item SSL_keepSocketOnError
897
898If this option is set to true (defaults to false) it will not close the
899underlying TCP socket on errors. In most cases there is no real use for this
900behavior since both sides of the TCP connection will probably have a
901different idea of the current state of the connection.
902
903=item SSL_ca | SSL_ca_file | SSL_ca_path
904
905Usually you want to verify that the peer certificate has been signed by a
906trusted certificate authority. In this case you should use this option to
907specify the file (C<SSL_ca_file>) or directory (C<SSL_ca_path>) containing the
908certificateZ<>(s) of the trusted certificate authorities.
909
910C<SSL_ca_path> can also be an array or a string containing multiple path, where
911the path are separated by the platform specific separator. This separator is
912C<;> on DOS, Windows, Netware, C<,> on VMS and C<:> for all the other systems.
913If multiple path are given at least one of these must be accessible.
914
915You can also give a list of X509* certificate handles (like you get from
916L<Net::SSLeay> or L<IO::Socket::SSL::Utils::PEM_xxx2cert>) with C<SSL_ca>. These
917will be added to the CA store before path and file and thus take precedence.
918If neither SSL_ca, nor SSL_ca_file or SSL_ca_path are set it will use
919C<default_ca()> to determine the user-set or system defaults.
920If you really don't want to set a CA set SSL_ca_file or SSL_ca_path to
921C<\undef> or SSL_ca to an empty list. (unfortunately C<''> is used by some
922modules using L<IO::Socket::SSL> when CA is not explicitly given).
923
924=item SSL_client_ca | SSL_client_ca_file
925
926If verify_mode is VERIFY_PEER on the server side these options can be used to
927set the list of acceptable CAs for the client. This way the client can select
928they required certificate from a list of certificates.
929The value for these options is similar to C<SSL_ca> and C<SSL_ca_file>.
930
931=item SSL_fingerprint
932
933Sometimes you have a self-signed certificate or a certificate issued by an
934unknown CA and you really want to accept it, but don't want to disable
935verification at all. In this case you can specify the fingerprint of the
936certificate as C<'algo$hex_fingerprint'>. C<algo> is a fingerprint algorithm
937supported by OpenSSL, e.g. 'sha1','sha256'... and C<hex_fingerprint> is the
938hexadecimal representation of the binary fingerprint. Any colons inside the
939hex string will be ignored.
940
941If you want to use the fingerprint of the pubkey inside the certificate instead
942of the certificate use the syntax C<'algo$pub$hex_fingerprint'> instead.
943To get the fingerprint of an established connection you can use
944C<get_fingerprint>.
945
946It is also possible to skip C<algo$>, i.e. only specify the fingerprint. In
947this case the likely algorithms will be automatically detected based on the
948length of the digest string.
949
950You can specify a list of fingerprints in case you have several acceptable
951certificates.
952If a fingerprint matches the topmost (i.e. leaf) certificate no additional
953validations can make the verification fail.
954
955=item SSL_cert_file | SSL_cert | SSL_key_file | SSL_key
956
957If you create a server you usually need to specify a server certificate which
958should be verified by the client. Same is true for client certificates, which
959should be verified by the server.
960The certificate can be given as a file with SSL_cert_file or as an internal
961representation of an X509* object (like you get from L<Net::SSLeay> or
962L<IO::Socket::SSL::Utils::PEM_xxx2cert>) with SSL_cert.
963If given as a file it will automatically detect the format.
964Supported file formats are PEM, DER and PKCS#12, where PEM and PKCS#12 can
965contain the certificate and the chain to use, while DER can only contain a single
966certificate.
967
968If given as a list of X509* please note, that the all the chain certificates
969(e.g. all except the first) will be "consumed" by openssl and will be freed
970if the SSL context gets destroyed - so you should never free them yourself. But
971the servers certificate (e.g. the first) will not be consumed by openssl and
972thus must be freed by the application.
973
974For each certificate a key is need, which can either be given as a file with
975SSL_key_file or as an internal representation of an EVP_PKEY* object with
976SSL_key (like you get from L<Net::SSLeay> or
977L<IO::Socket::SSL::Utils::PEM_xxx2key>).
978If a key was already given within the PKCS#12 file specified by SSL_cert_file
979it will ignore any SSL_key or SSL_key_file.
980If no SSL_key or SSL_key_file was given it will try to use the PEM file given
981with SSL_cert_file again, maybe it contains the key too.
982
983If your SSL server should be able to use different certificates on the same IP
984address, depending on the name given by SNI, you can use a hash reference
985instead of a file with C<<hostname => cert_file>>.
986
987If your SSL server should be able to use both RSA and ECDSA certificates for the
988same domain/IP a similar hash reference like with SNI is given. The
989domain names used to specify the additional certificates should be
990C<hostname%whatever>, i.e.  C<hostname%ecc> or similar. This needs at least
991OpenSSL 1.0.2. To let the server pick the certificate based on the clients
992cipher preference C<SSL_honor_cipher_order> should be set to false.
993
994In case certs and keys are needed but not given it might fall back to builtin
995defaults, see "Defaults for Cert, Key and CA".
996
997Examples:
998
999 SSL_cert_file => 'mycert.pem',
1000 SSL_key_file => 'mykey.pem',
1001
1002 SSL_cert_file => {
1003    "foo.example.org" => 'foo-cert.pem',
1004    "foo.example.org%ecc" => 'foo-ecc-cert.pem',
1005    "bar.example.org" => 'bar-cert.pem',
1006    # used when nothing matches or client does not support SNI
1007    '' => 'default-cert.pem',
1008    '%ecc' => 'default-ecc-cert.pem',
1009 },
1010 SSL_key_file => {
1011    "foo.example.org" => 'foo-key.pem',
1012    "foo.example.org%ecc" => 'foo-ecc-key.pem',
1013    "bar.example.org" => 'bar-key.pem',
1014    # used when nothing matches or client does not support SNI
1015    '' => 'default-key.pem',
1016    '%ecc' => 'default-ecc-key.pem',
1017 }
1018
1019=item SSL_passwd_cb
1020
1021If your private key is encrypted, you might not want the default password prompt
1022from Net::SSLeay.  This option takes a reference to a subroutine that should
1023return the password required to decrypt your private key.
1024
1025=item SSL_use_cert
1026
1027If this is true, it forces IO::Socket::SSL to use a certificate and key, even if
1028you are setting up an SSL client.  If this is set to 0 (the default), then you
1029will only need a certificate and key if you are setting up a server.
1030
1031SSL_use_cert will implicitly be set if SSL_server is set.
1032For convenience it is also set if it was not given but a cert was given for use
1033(SSL_cert_file or similar).
1034
1035
1036=item SSL_version
1037
1038Sets the version of the SSL protocol used to transmit data.
1039'SSLv23' uses a handshake compatible with SSL2.0, SSL3.0 and TLS1.x, while
1040'SSLv2', 'SSLv3', 'TLSv1', 'TLSv1_1', 'TLSv1_2', or 'TLSv1_3' restrict
1041handshake and protocol to the specified version.
1042All values are case-insensitive.  Instead of 'TLSv1_1', 'TLSv1_2', and
1043'TLSv1_3' one can also use 'TLSv11', 'TLSv12', and 'TLSv13'.  Support for
1044'TLSv1_1', 'TLSv1_2', and 'TLSv1_3' requires recent versions of Net::SSLeay
1045and openssl.
1046
1047Independent from the handshake format you can limit to set of accepted SSL
1048versions by adding !version separated by ':'.
1049
1050The default SSL_version is 'SSLv23:!SSLv3:!SSLv2' which means, that the
1051handshake format is compatible to SSL2.0 and higher, but that the successful
1052handshake is limited to TLS1.0 and higher, that is no SSL2.0 or SSL3.0 because
1053both of these versions have serious security issues and should not be used
1054anymore.
1055You can also use !TLSv1_1 and !TLSv1_2 to disable TLS versions 1.1 and 1.2 while
1056still allowing TLS version 1.0.
1057
1058Setting the version instead to 'TLSv1' might break interaction with older
1059clients, which need and SSL2.0 compatible handshake. On the other
1060side some clients just close the connection when they receive a TLS version 1.1
1061request. In this case setting the version to
1062'SSLv23:!SSLv2:!SSLv3:!TLSv1_1:!TLSv1_2' might help.
1063
1064=item SSL_cipher_list
1065
1066If this option is set the cipher list for the connection will be set to the
1067given value, e.g. something like 'ALL:!LOW:!EXP:!aNULL'. Look into the OpenSSL
1068documentation (L<https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-STRINGS>)
1069for more details.
1070
1071Unless you fail to contact your peer because of no shared ciphers it is
1072recommended to leave this option at the default setting. The default setting
1073prefers ciphers with forward secrecy, disables anonymous authentication and
1074disables known insecure ciphers like MD5, DES etc. This gives a grade A result
1075at the tests of SSL Labs.
1076To use the less secure OpenSSL builtin default (whatever this is) set
1077SSL_cipher_list to ''.
1078
1079In case different cipher lists are needed for different SNI hosts a hash can be
1080given with the host as key and the cipher suite as value, similar to
1081B<SSL_cert*>.
1082
1083=item SSL_honor_cipher_order
1084
1085If this option is true the cipher order the server specified is used instead
1086of the order proposed by the client. This option defaults to true to make use of
1087our secure cipher list setting.
1088
1089=item SSL_dh_file
1090
1091To create a server which provides forward secrecy you need to either give the DH
1092parameters or (better, because faster) the ECDH curve. This setting cares
1093about DH parameters.
1094
1095To support non-elliptic Diffie-Hellman key exchange a suitable file needs to
1096be given here or the SSL_dh should be used with an appropriate value.
1097See dhparam command in openssl for more information.
1098
1099If neither C<SSL_dh_file> nor C<SSL_dh> are set a builtin DH parameter with a
1100length of 2048 bit is used to offer DH key exchange by default. If you don't
1101want this (e.g. disable DH key exchange) explicitly set this or the C<SSL_dh>
1102parameter to undef.
1103
1104=item SSL_dh
1105
1106Like SSL_dh_file, but instead of giving a file you use a preloaded or generated
1107DH*.
1108
1109=item SSL_ecdh_curve
1110
1111To create a server which provides forward secrecy you need to either give the DH
1112parameters or (better, because faster) the ECDH curve. This setting cares
1113about the ECDH curve(s).
1114
1115To support Elliptic Curve Diffie-Hellmann key exchange the OID or NID of at
1116least one suitable curve needs to be provided here.
1117
1118With OpenSSL 1.1.0+ this parameter defaults to C<auto>, which means that it
1119lets OpenSSL pick the best settings. If support for CTX_set_ecdh_auto is
1120implemented in Net::SSLeay (needs at least version 1.86) it will use this to
1121implement the same default.  Otherwise it will default to C<prime256v1>
1122(builtin of OpenSSL) in order to offer ECDH key exchange by default.
1123
1124If setting groups or curves is supported by Net::SSLeay (needs at least
1125version 1.86) then multiple curves can be given here in the order of the
1126preference, i.e.  C<P-521:P-384:P-256>. When used at the client side this
1127will include the supported curves as extension in the TLS handshake.
1128
1129If you don't want to have ECDH key exchange this could be set to undef or
1130set C<SSL_ciphers> to exclude all of these ciphers.
1131
1132You can check if ECDH support is available by calling
1133C<< IO::Socket::SSL->can_ecdh >>.
1134
1135=item SSL_verify_mode
1136
1137This option sets the verification mode for the peer certificate.
1138You may combine SSL_VERIFY_PEER (verify_peer), SSL_VERIFY_FAIL_IF_NO_PEER_CERT
1139(fail verification if no peer certificate exists; ignored for clients),
1140SSL_VERIFY_CLIENT_ONCE (verify client once; ignored for clients).
1141See OpenSSL man page for SSL_CTX_set_verify for more information.
1142
1143The default is SSL_VERIFY_NONE for server  (e.g. no check for client
1144certificate) and SSL_VERIFY_PEER for client (check server certificate).
1145
1146=item SSL_verify_callback
1147
1148If you want to verify certificates yourself, you can pass a sub reference along
1149with this parameter to do so.  When the callback is called, it will be passed:
1150
1151=over 4
1152
1153=item 1.
1154a true/false value that indicates what OpenSSL thinks of the certificate,
1155
1156=item 2.
1157a C-style memory address of the certificate store,
1158
1159=item 3.
1160a string containing the certificate's issuer attributes and owner attributes,
1161and
1162
1163=item 4.
1164a string containing any errors encountered (0 if no errors).
1165
1166=item 5.
1167a C-style memory address of the peer's own certificate (convertible to
1168PEM form with Net::SSLeay::PEM_get_string_X509()).
1169
1170=item 6.
1171The depth of the certificate in the chain. Depth 0 is the leaf certificate.
1172
1173=back
1174
1175The function should return 1 or 0, depending on whether it thinks the
1176certificate is valid or invalid.  The default is to let OpenSSL do all of the
1177busy work.
1178
1179The callback will be called for each element in the certificate chain.
1180
1181See the OpenSSL documentation for SSL_CTX_set_verify for more information.
1182
1183=item SSL_verifycn_scheme
1184
1185The scheme is used to correctly verify the identity inside the certificate
1186by using the hostname of the peer.
1187See the information about the verification schemes in B<verify_hostname>.
1188
1189If you don't specify a scheme it will use 'default', but only complain loudly if
1190the name verification fails instead of letting the whole certificate
1191verification fail. THIS WILL CHANGE, e.g. it will let the certificate
1192verification fail in the future if the hostname does not match the certificate
1193!!!!  To override the name used in verification use B<SSL_verifycn_name>.
1194
1195The scheme 'default' is a superset of the usual schemes, which will accept the
1196hostname in common name and subjectAltName and allow wildcards everywhere.
1197While using this scheme is way more secure than no name verification at all you
1198better should use the scheme specific to your application protocol, e.g. 'http',
1199'ftp'...
1200
1201If you are really sure, that you don't want to verify the identity using the
1202hostname  you can use 'none' as a scheme. In this case you'd better have
1203alternative forms of verification, like a certificate fingerprint or do a manual
1204verification later by calling B<verify_hostname> yourself.
1205
1206=item SSL_verifycn_publicsuffix
1207
1208This option is used to specify the behavior when checking wildcards certificates
1209for public suffixes, e.g. no wildcard certificates for *.com or *.co.uk should
1210be accepted, while *.example.com or *.example.co.uk is ok.
1211
1212If not specified it will simply use the builtin default of
1213L<IO::Socket::SSL::PublicSuffix>, you can create another object with
1214from_string or from_file of this module.
1215
1216To disable verification of public suffix set this option to C<''>.
1217
1218=item SSL_verifycn_name
1219
1220Set the name which is used in verification of hostname. If SSL_verifycn_scheme
1221is set and no SSL_verifycn_name is given it will try to use SSL_hostname or
1222PeerHost and PeerAddr settings and fail if no name can be determined.
1223If SSL_verifycn_scheme is not set it will use a default scheme and warn if it
1224cannot determine a hostname, but it will not fail.
1225
1226Using PeerHost or PeerAddr works only if you create the connection directly
1227with C<< IO::Socket::SSL->new >>, if an IO::Socket::INET object is upgraded
1228with B<start_SSL> the name has to be given in B<SSL_verifycn_name> or
1229B<SSL_hostname>.
1230
1231=item SSL_check_crl
1232
1233If you want to verify that the peer certificate has not been revoked
1234by the signing authority, set this value to true. OpenSSL will search
1235for the CRL in your SSL_ca_path, or use the file specified by
1236SSL_crl_file.  See the Net::SSLeay documentation for more details.
1237Note that this functionality appears to be broken with OpenSSL <
1238v0.9.7b, so its use with lower versions will result in an error.
1239
1240=item SSL_crl_file
1241
1242If you want to specify the CRL file to be used, set this value to the
1243pathname to be used.  This must be used in addition to setting
1244SSL_check_crl.
1245
1246=item SSL_ocsp_mode
1247
1248Defines how certificate revocation is done using OCSP (Online Status Revocation
1249Protocol). The default is to send a request for OCSP stapling to the server and
1250if the server sends an OCSP response back the result will be used.
1251
1252Any other OCSP checking needs to be done manually with C<ocsp_resolver>.
1253
1254The following flags can be combined with C<|>:
1255
1256=over 8
1257
1258=item SSL_OCSP_NO_STAPLE
1259
1260Don't ask for OCSP stapling.
1261This is the default if SSL_verify_mode is VERIFY_NONE.
1262
1263=item SSL_OCSP_TRY_STAPLE
1264
1265Try OCSP stapling, but don't complain if it gets no stapled response back.
1266This is the default if SSL_verify_mode is VERIFY_PEER (the default).
1267
1268=item SSL_OCSP_MUST_STAPLE
1269
1270Consider it a hard error, if the server does not send a stapled OCSP response
1271back. Most servers currently send no stapled OCSP response back.
1272
1273=item SSL_OCSP_FAIL_HARD
1274
1275Fail hard on response errors, default is to fail soft like the browsers do.
1276Soft errors mean, that the OCSP response is not usable, e.g. no response,
1277error response, no valid signature etc.
1278Certificate revocations inside a verified response are considered hard errors
1279in any case.
1280
1281Soft errors inside a stapled response are never considered hard, e.g. it is
1282expected that in this case an OCSP request will be send to the responsible
1283OCSP responder.
1284
1285=item SSL_OCSP_FULL_CHAIN
1286
1287This will set up the C<ocsp_resolver> so that all certificates from the peer
1288chain will be checked, otherwise only the leaf certificate will be checked
1289against revocation.
1290
1291=back
1292
1293=item SSL_ocsp_staple_callback
1294
1295If this callback is defined, it will be called with the SSL object and the OCSP
1296response handle obtained from the peer, e.g. C<<$cb->($ssl,$resp)>>.
1297If the peer did not provide a stapled OCSP response the function will be called
1298with C<$resp=undef>.
1299Because the OCSP response handle is no longer valid after leaving this function
1300it should not by copied or freed. If access to the response is necessary after
1301leaving this function it can be serialized with
1302C<Net::SSLeay::i2d_OCSP_RESPONSE>.
1303
1304If no such callback is provided, it will use the default one, which verifies the
1305response and uses it to check if the certificate(s) of the connection got
1306revoked.
1307
1308=item SSL_ocsp_cache
1309
1310With this option a cache can be given for caching OCSP responses, which could
1311be shared between different SSL contexts. If not given a cache specific to the
1312SSL context only will be used.
1313
1314You can either create a new cache with
1315C<< IO::Socket::SSL::OCSP_Cache->new([size]) >> or implement your own cache,
1316which needs to have methods C<put($key,\%entry)> and C<get($key)> (returning
1317C<\%entry>) where entry is the hash representation of the OCSP response with
1318fields like C<nextUpdate>. The default implementation of the cache will consider
1319responses valid as long as C<nextUpdate> is less then the current time.
1320
1321=item SSL_reuse_ctx
1322
1323If you have already set the above options for a previous instance of
1324IO::Socket::SSL, then you can reuse the SSL context of that instance by passing
1325it as the value for the SSL_reuse_ctx parameter.  You may also create a
1326new instance of the IO::Socket::SSL::SSL_Context class, using any context
1327options that you desire without specifying connection options, and pass that
1328here instead.
1329
1330If you use this option, all other context-related options that you pass
1331in the same call to new() will be ignored unless the context supplied was
1332invalid.  Note that, contrary to versions of IO::Socket::SSL below v0.90, a
1333global SSL context will not be implicitly used unless you use the
1334set_default_context() function.
1335
1336=item SSL_create_ctx_callback
1337
1338With this callback you can make individual settings to the context after it
1339got created and the default setup was done.
1340The callback will be called with the CTX object from Net::SSLeay as the single
1341argument.
1342
1343Example for limiting the server session cache size:
1344
1345  SSL_create_ctx_callback => sub {
1346      my $ctx = shift;
1347      Net::SSLeay::CTX_sess_set_cache_size($ctx,128);
1348  }
1349
1350=item SSL_session_cache_size
1351
1352If you make repeated connections to the same host/port and the SSL renegotiation
1353time is an issue, you can turn on client-side session caching with this option
1354by specifying a positive cache size.  For successive connections, pass the
1355SSL_reuse_ctx option to the new() calls (or use set_default_context()) to make
1356use of the cached sessions.  The session cache size refers to the number of
1357unique host/port pairs that can be stored at one time; the oldest sessions in
1358the cache will be removed if new ones are added.
1359
1360This option does not effect the session cache a server has for it's clients,
1361e.g. it does not affect SSL objects with SSL_server set.
1362
1363Note that session caching with TLS 1.3 needs at least Net::SSLeay 1.86.
1364
1365=item SSL_session_cache
1366
1367Specifies session cache object which should be used instead of creating a new.
1368Overrules SSL_session_cache_size.
1369This option is useful if you want to reuse the cache, but not the rest of
1370the context.
1371
1372A session cache object can be created using
1373C<< IO::Socket::SSL::Session_Cache->new( cachesize ) >>.
1374
1375Use set_default_session_cache() to set a global cache object.
1376
1377=item SSL_session_key
1378
1379Specifies a key to use for lookups and inserts into client-side session cache.
1380Per default ip:port of destination will be used, but sometimes you want to
1381share the same session over multiple ports on the same server (like with FTPS).
1382
1383=item SSL_session_id_context
1384
1385This gives an id for the servers session cache. It's necessary if you want
1386clients to connect with a client certificate. If not given but SSL_verify_mode
1387specifies the need for client certificate a context unique id will be picked.
1388
1389=item SSL_error_trap
1390
1391When using the accept() or connect() methods, it may be the case that the
1392actual socket connection works but the SSL negotiation fails, as in the case of
1393an HTTP client connecting to an HTTPS server.  Passing a subroutine ref attached
1394to this parameter allows you to gain control of the orphaned socket instead of
1395having it be closed forcibly.
1396The subroutine, if called, will be passed two parameters:
1397a reference to the socket on which the SSL negotiation failed and the full
1398text of the error message.
1399
1400=item SSL_npn_protocols
1401
1402If used on the server side it specifies list of protocols advertised by SSL
1403server as an array ref, e.g. ['spdy/2','http1.1'].
1404On the client side it specifies the protocols offered by the client for NPN
1405as an array ref.
1406See also method C<next_proto_negotiated>.
1407
1408Next Protocol Negotiation (NPN) is available with Net::SSLeay 1.46+ and
1409openssl-1.0.1+. NPN is unavailable in TLSv1.3 protocol.
1410To check support you might call C<< IO::Socket::SSL->can_npn() >>.
1411If you use this option with an unsupported Net::SSLeay/OpenSSL it will
1412throw an error.
1413
1414=item SSL_alpn_protocols
1415
1416If used on the server side it specifies list of protocols supported by the SSL
1417server as an array ref, e.g. ['http/2.0', 'spdy/3.1','http/1.1'].
1418On the client side it specifies the protocols advertised by the client for ALPN
1419as an array ref.
1420See also method C<alpn_selected>.
1421
1422Application-Layer Protocol Negotiation (ALPN) is available with Net::SSLeay
14231.56+ and openssl-1.0.2+. More details about the extension are in RFC7301. To
1424check support you might call C<< IO::Socket::SSL->can_alpn() >>. If you use
1425this option with an unsupported Net::SSLeay/OpenSSL it will throw an error.
1426
1427Note that some client implementations may encounter problems if both NPN and
1428ALPN are specified. Since ALPN is intended as a replacement for NPN, try
1429providing ALPN protocols then fall back to NPN if that fails.
1430
1431=item SSL_ticket_keycb => [$sub,$data] | $sub
1432
1433This is a callback used for stateless session reuse (Session Tickets, RFC 5077).
1434
1435This callback will be called as C<< $sub->($data,[$key_name]) >> where C<$data>
1436is the argument given to SSL_ticket_keycb (or undef) and C<$key_name> depends
1437on the mode:
1438
1439=over 8
1440
1441=item encrypt ticket
1442
1443If a ticket needs to be encrypted the callback will be called without
1444C<$key_name>. In this case it should return C<($current_key,$current_key_name>)
1445where C<$current_key> is the current key (32 byte random data) and
1446C<$current_key_name> the name associated with this key (exactly 16 byte). This
1447C<$current_key_name> will be incorporated into the ticket.
1448
1449=item decrypt ticket
1450
1451If a ticket needs to be decrypted the callback will be called with C<$key_name>
1452as found in the ticket. It should return C<($key,$current_key_name>) where
1453C<$key> is the key associated with the given C<$key_name> and
1454C<$current_key_name> the name associated with the currently active key.
1455If C<$current_key_name> is different from the given C<$key_name> the callback
1456will be called again to re-encrypt the ticket with the currently active key.
1457
1458If no key can be found which matches the given C<$key_name> then this function
1459should return nothing (empty list).
1460
1461This mechanism should be used to limit the life time for each key encrypting the
1462ticket. Compromise of a ticket encryption key might lead to decryption of SSL
1463sessions which used session tickets protected by this key.
1464
1465=back
1466
1467Example:
1468
1469    Net::SSLeay::RAND_bytes(my $oldkey,32);
1470    Net::SSLeay::RAND_bytes(my $newkey,32);
1471    my $oldkey_name = pack("a16",'oldsecret');
1472    my $newkey_name = pack("a16",'newsecret');
1473
1474    my @keys = (
1475       [ $newkey_name, $newkey ], # current active key
1476       [ $oldkey_name, $oldkey ], # already expired
1477    );
1478
1479    my $keycb = [ sub {
1480       my ($mykeys,$name) = @_;
1481
1482       # return (current_key, current_key_name) if no name given
1483       return ($mykeys->[0][1],$mykeys->[0][0]) if ! $name;
1484
1485       # return (matching_key, current_key_name) if we find a key matching
1486       # the given name
1487       for(my $i = 0; $i<@$mykeys; $i++) {
1488	   next if $name ne $mykeys->[$i][0];
1489	   return ($mykeys->[$i][1],$mykeys->[0][0]);
1490       }
1491
1492       # no matching key found
1493       return;
1494    },\@keys ];
1495
1496    my $srv = IO::Socket::SSL->new(..., SSL_ticket_keycb => $keycb);
1497
1498=item SSL_mode_release_buffers 1|0
1499
1500This enables or disables the SSL_MODE_RELEASE_BUFFERS option on the SSL object.
1501With this option the read buffer will be released after each SSL_read but will
1502need to be reallocated for each new SSL_read. If memory usage is a concern this
1503might save lots of memory in the mean time though, about 34k per idle SSL
1504connection according to the documentation in SSL_CTX_set_mode(3ssl).
1505
1506=back
1507
1508=item B<accept>
1509
1510This behaves similar to the accept function of the underlying socket class, but
1511additionally does the initial SSL handshake. But because the underlying socket
1512class does return a blocking file handle even when accept is called on a
1513non-blocking socket, the SSL handshake on the new file object will be done in a
1514blocking way. Please see the section about non-blocking I/O for details.
1515If you don't like this behavior you should do accept on the TCP socket and then
1516upgrade it with C<start_SSL> later.
1517
1518=item B<connect(...)>
1519
1520This behaves similar to the connect function but also does an SSL handshake.
1521Because you cannot give SSL specific arguments to this function, you should
1522better either use C<new> to create a connect SSL socket or C<start_SSL> to
1523upgrade an established TCP socket to SSL.
1524
1525=item B<close(...)>
1526
1527Contrary to a close for a simple INET socket a close in SSL also mandates a
1528proper shutdown of the SSL part. This is done by sending a close notify message
1529by both peers.
1530
1531A naive implementation would thus wait until it receives the
1532close notify message from the peer - which conflicts with the commonly expected
1533semantic that a close will not block. The default behavior is thus to only send
1534a close notify but not  wait for the close notify of the peer. If this is
1535required C<SSL_fast_shutdown> need to be explicitly set to false.
1536
1537There are also cases where a SSL shutdown should not be done at all. This is
1538true for example when forking to let a child deal with the socket and closing
1539the socket in the parent process. A naive explicit C<close> or an implicit close
1540when destroying the socket in the parent would send a close notify to the peer
1541which would make the SSL socket in the client process unusable. In this case an
1542explicit C<close> with C<SSL_no_shutdown> set to true should be done in the
1543parent process.
1544
1545For more details and other arguments see C<stop_SSL> which gets called from
1546C<close> to shutdown the SSL state of the socket.
1547
1548=item B<sysread( BUF, LEN, [ OFFSET ] )>
1549
1550This function behaves from the outside the same as B<sysread> in other
1551L<IO::Socket> objects, e.g. it returns at most LEN bytes of data.
1552But in reality it reads not only LEN bytes from the underlying socket, but at
1553a single SSL frame. It then returns up to LEN bytes it decrypted from this SSL
1554frame. If the frame contained more data than requested it will return only LEN
1555data, buffer the rest and return it on further read calls.
1556This means, that it might be possible to read data, even if the underlying
1557socket is not readable, so using poll or select might not be sufficient.
1558
1559sysread will only return data from a single SSL frame, e.g. either the pending
1560data from the already buffered frame or it will read a frame from the underlying
1561socket and return the decrypted data. It will not return data spanning several
1562SSL frames in a single call.
1563
1564Also, calls to sysread might fail, because it must first finish an SSL
1565handshake.
1566
1567To understand these behaviors is essential, if you write applications which use
1568event loops and/or non-blocking sockets. Please read the specific sections in
1569this documentation.
1570
1571=item B<syswrite( BUF, [ LEN, [ OFFSET ]] )>
1572
1573This functions behaves from the outside the same as B<syswrite> in other
1574L<IO::Socket> objects, e.g. it will write at most LEN bytes to the socket, but
1575there is no guarantee, that all LEN bytes are written. It will return the number
1576of bytes written.
1577Because it basically just calls SSL_write from OpenSSL syswrite will write at
1578most a single SSL frame. This means, that no more than 16.384 bytes, which is
1579the maximum size of an SSL frame, will be written at once.
1580
1581For non-blocking sockets SSL specific behavior applies.
1582Pease read the specific section in this documentation.
1583
1584=item B<peek( BUF, LEN, [ OFFSET ])>
1585
1586This function has exactly the same syntax as B<sysread>, and performs nearly the
1587same task but will not advance the read position so that successive calls to
1588peek() with the same arguments will return the same results.  This function
1589requires OpenSSL 0.9.6a or later to work.
1590
1591=item B<pending()>
1592
1593This function gives you the number of bytes available without reading from the
1594underlying socket object. This function is essential if you work with event
1595loops, please see the section about polling SSL sockets.
1596
1597=item B<get_fingerprint([algo,certificate,pubkey])>
1598
1599This methods returns the fingerprint of the given certificate in the form
1600C<algo$digest_hex>, where C<algo> is the used algorithm, default 'sha256'.
1601If no certificate is given the peer certificate of the connection is used.
1602If C<pubkey> is true it will not return the fingerprint of the certificate but
1603instead the fingerprint of the pubkey inside the certificate as
1604C<algo$pub$digest_hex>.
1605
1606=item B<get_fingerprint_bin([algo,certificate,pubkey])>
1607
1608This methods returns the binary fingerprint of the given certificate by using
1609the algorithm C<algo>, default 'sha256'.
1610If no certificate is given the peer certificate of the connection is used.
1611If C<pubkey> is true it will not return the fingerprint of the certificate but
1612instead the fingerprint of the pubkey inside the certificate.
1613
1614=item B<get_cipher()>
1615
1616Returns the string form of the cipher that the IO::Socket::SSL object is using.
1617
1618=item B<get_sslversion()>
1619
1620Returns the string representation of the SSL version of an established
1621connection.
1622
1623=item B<get_sslversion_int()>
1624
1625Returns the integer representation of the SSL version of an established
1626connection.
1627
1628=item B<get_session_reused()>
1629
1630This returns true if the session got reused and false otherwise. Note that with
1631a reused session no certificates are send within the handshake and no ciphers
1632are offered and thus functions which rely on this might not work.
1633
1634=item B<dump_peer_certificate()>
1635
1636Returns a parsable string with select fields from the peer SSL certificate.
1637This method directly returns the result of the dump_peer_certificate() method of
1638Net::SSLeay.
1639
1640=item B<peer_certificate($field;[$refresh])>
1641
1642If a peer certificate exists, this function can retrieve values from it.
1643If no field is given the internal representation of certificate from Net::SSLeay
1644is returned.
1645If refresh is true it will not used a cached version, but check again in case
1646the certificate of the connection has changed due to renegotiation.
1647
1648The following fields can be queried:
1649
1650=over 8
1651
1652=item authority (alias issuer)
1653
1654The certificate authority which signed the certificate.
1655
1656=item owner (alias subject)
1657
1658The owner of the certificate.
1659
1660=item commonName (alias cn) - only for Net::SSLeay version >=1.30
1661
1662The common name, usually the server name for SSL certificates.
1663
1664=item subjectAltNames - only for Net::SSLeay version >=1.33
1665
1666Alternative names for the subject, usually different names for the same
1667server, like example.org, example.com, *.example.com.
1668
1669It returns a list of (typ,value) with typ GEN_DNS, GEN_IPADD etc (these
1670constants are exported from IO::Socket::SSL).
1671See Net::SSLeay::X509_get_subjectAltNames.
1672
1673=back
1674
1675=item B<sock_certificate($field)>
1676
1677This is similar to C<peer_certificate> but will return the sites own
1678certificate. The same arguments for B<$field> can be used.
1679If no B<$field> is given the certificate handle from the underlying OpenSSL will
1680be returned. This handle will only be valid as long as the SSL connection exists
1681and if used afterwards it might result in strange crashes of the application.
1682
1683=item B<peer_certificates>
1684
1685This returns all the certificates send by the peer, e.g. first the peers own
1686certificate and then the rest of the chain. You might use B<CERT_asHash> from
1687L<IO::Socket::SSL::Utils> to inspect each of the certificates.
1688
1689This function depends on a version of Net::SSLeay >= 1.58 .
1690
1691=item B<get_servername>
1692
1693This gives the name requested by the client if Server Name Indication
1694(SNI) was used.
1695
1696=item B<verify_hostname($hostname,$scheme,$publicsuffix)>
1697
1698This verifies the given hostname against the peer certificate using the
1699given scheme. Hostname is usually what you specify within the PeerAddr.
1700See the C<SSL_verifycn_publicsuffix> parameter for an explanation of suffix
1701checking and for the possible values.
1702
1703Verification of hostname against a certificate is different between various
1704applications and RFCs. Some scheme allow wildcards for hostnames, some only
1705in subjectAltNames, and even their different wildcard schemes are possible.
1706RFC 6125 provides a good overview.
1707
1708To ease the verification the following schemes are predefined (both protocol
1709name and rfcXXXX name can be used):
1710
1711=over 8
1712
1713=item rfc2818, xmpp (rfc3920), ftp (rfc4217)
1714
1715Extended wildcards in subjectAltNames and common name are possible, e.g.
1716*.example.org or even www*.example.org. The common
1717name will be only checked if no DNS names are given in subjectAltNames.
1718
1719=item http (alias www)
1720
1721While name checking is defined in rfc2818 the current browsers usually accept
1722also an IP address (w/o wildcards) within the common name as long as no
1723subjectAltNames are defined. Thus this is rfc2818 extended with this feature.
1724
1725=item smtp (rfc2595), imap, pop3, acap (rfc4642), netconf (rfc5538), syslog (rfc5425), snmp (rfc5953)
1726
1727Simple wildcards in subjectAltNames are possible, e.g. *.example.org matches
1728www.example.org but not lala.www.example.org. If nothing from subjectAltNames
1729match it checks against the common name, where wildcards are also allowed to
1730match the full leftmost label.
1731
1732=item ldap (rfc4513)
1733
1734Simple wildcards are allowed in subjectAltNames, but not in common name.
1735Common name will be checked even if subjectAltNames exist.
1736
1737=item sip (rfc5922)
1738
1739No wildcards are allowed and common name is checked even if subjectAltNames
1740exist.
1741
1742=item gist (rfc5971)
1743
1744Simple wildcards are allowed in subjectAltNames and common name, but common name
1745will only be checked if their are no DNS names in subjectAltNames.
1746
1747=item default
1748
1749This is a superset of all the rules and is automatically used if no scheme is
1750given but a hostname (instead of IP) is known.
1751Extended wildcards are allowed in subjectAltNames and common name and common
1752name is checked always.
1753
1754=item none
1755
1756No verification will be done.
1757Actually is does not make any sense to call verify_hostname in this case.
1758
1759=back
1760
1761The scheme can be given either by specifying the name for one of the above
1762predefined schemes, or by using a hash which can have the following keys and
1763values:
1764
1765=over 8
1766
1767=item check_cn:  0|'always'|'when_only'
1768
1769Determines if the common name gets checked. If 'always' it will always be
1770checked (like in ldap), if 'when_only' it will only be checked if no names are
1771given in subjectAltNames (like in http), for any other values the common name
1772will not be checked.
1773
1774=item wildcards_in_alt: 0|'full_label'|'anywhere'
1775
1776Determines if and where wildcards in subjectAltNames are possible. If
1777'full_label' only cases like *.example.org will be possible (like in ldap), for
1778'anywhere' www*.example.org is possible too (like http), dangerous things like
1779but www.*.org or even '*' will not be allowed.
1780For compatibility with older versions 'leftmost' can be given instead of
1781'full_label'.
1782
1783=item wildcards_in_cn: 0|'full_label'|'anywhere'
1784
1785Similar to wildcards_in_alt, but checks the common name. There is no predefined
1786scheme which allows wildcards in common names.
1787
1788=item ip_in_cn: 0|1|4|6
1789
1790Determines if an IP address is allowed in the common name (no wildcards are
1791allowed). If set to 4 or 6 it only allows IPv4 or IPv6 addresses, any other
1792true value allows both.
1793
1794=item callback: \&coderef
1795
1796If you give a subroutine for verification it will be called with the arguments
1797($hostname,$commonName,@subjectAltNames), where hostname is the name given for
1798verification, commonName is the result from peer_certificate('cn') and
1799subjectAltNames is the result from peer_certificate('subjectAltNames').
1800
1801All other arguments for the verification scheme will be ignored in this case.
1802
1803=back
1804
1805=item B<next_proto_negotiated()>
1806
1807This method returns the name of negotiated protocol - e.g. 'http/1.1'. It works
1808for both client and server side of SSL connection.
1809
1810NPN support is available with Net::SSLeay 1.46+ and openssl-1.0.1+.
1811To check support you might call C<< IO::Socket::SSL->can_npn() >>.
1812
1813=item B<alpn_selected()>
1814
1815Returns the protocol negotiated via ALPN as a string, e.g. 'http/1.1',
1816'http/2.0' or 'spdy/3.1'.
1817
1818ALPN support is available with Net::SSLeay 1.56+ and openssl-1.0.2+.
1819To check support, use C<< IO::Socket::SSL->can_alpn() >>.
1820
1821=item B<errstr()>
1822
1823Returns the last error (in string form) that occurred.	If you do not have a
1824real object to perform this method on, call IO::Socket::SSL::errstr() instead.
1825
1826For read and write errors on non-blocking sockets, this method may include the
1827string C<SSL wants a read first!> or C<SSL wants a write first!> meaning that
1828the other side is expecting to read from or write to the socket and wants to be
1829satisfied before you get to do anything. But with version 0.98 you are better
1830comparing the global exported variable $SSL_ERROR against the exported symbols
1831SSL_WANT_READ and SSL_WANT_WRITE.
1832
1833=item B<opened()>
1834
1835This returns false if the socket could not be opened, 1 if the socket could be
1836opened and the SSL handshake was successful done and -1 if the underlying
1837IO::Handle is open, but the SSL handshake failed.
1838
1839=item B<< IO::Socket::SSL->start_SSL($socket, ... ) >>
1840
1841This will convert a glob reference or a socket that you provide to an
1842IO::Socket::SSL object.	 You may also pass parameters to specify context or
1843connection options as with a call to new().  If you are using this function on
1844an accept()ed socket, you must set the parameter "SSL_server" to 1, i.e.
1845IO::Socket::SSL->start_SSL($socket, SSL_server => 1).  If you have a class that
1846inherits from IO::Socket::SSL and you want the $socket to be blessed into your
1847own class instead, use MyClass->start_SSL($socket) to achieve the desired
1848effect.
1849
1850Note that if start_SSL() fails in SSL negotiation, $socket will remain blessed
1851in its original class.	 For non-blocking sockets you better just upgrade the
1852socket to IO::Socket::SSL and call accept_SSL or connect_SSL and the upgraded
1853object. To just upgrade the socket set B<SSL_startHandshake> explicitly to 0. If
1854you call start_SSL w/o this parameter it will revert to blocking behavior for
1855accept_SSL and connect_SSL.
1856
1857If given the parameter "Timeout" it will stop if after the timeout no SSL
1858connection was established. This parameter is only used for blocking sockets, if
1859it is not given the default Timeout from the underlying IO::Socket will be
1860used.
1861
1862=item B<stop_SSL(...)>
1863
1864This is the opposite of start_SSL(), connect_SSL() and accept_SSL(), e.g. it
1865will shutdown the SSL connection and return to the class before start_SSL(). It
1866gets the same arguments as close(), in fact close() calls stop_SSL() (but
1867without downgrading the class).
1868
1869Will return true if it succeeded and undef if failed. This might be the case for
1870non-blocking sockets. In this case $! is set to EWOULDBLOCK and the ssl error to
1871SSL_WANT_READ or SSL_WANT_WRITE. In this case the call should be retried again
1872with the same arguments once the socket is ready.
1873
1874For calling from C<stop_SSL> C<SSL_fast_shutdown> default to false, e.g. it
1875waits for the close_notify of the peer. This is necessary in case you want to
1876downgrade the socket and continue to use it as a plain socket.
1877
1878After stop_SSL the socket can again be used to exchange plain data.
1879
1880=item B<connect_SSL>, B<accept_SSL>
1881
1882These functions should be used to do the relevant handshake, if the socket got
1883created with C<new> or upgraded with C<start_SSL> and C<SSL_startHandshake> was
1884set to false.
1885They will return undef until the handshake succeeded or an error got thrown.
1886As long as the function returns undef and $! is set to EWOULDBLOCK one could
1887retry the call after the socket got readable (SSL_WANT_READ) or writeable
1888(SSL_WANT_WRITE).
1889
1890=item B<ocsp_resolver>
1891
1892This will create an OCSP resolver object, which can be used to create OCSP
1893requests for the certificates of the SSL connection. Which certificates are
1894verified depends on the setting of C<SSL_ocsp_mode>: by default only the leaf
1895certificate will be checked, but with SSL_OCSP_FULL_CHAIN all chain
1896certificates will be checked.
1897
1898Because to create an OCSP request the certificate and its issuer certificate
1899need to be known it is not possible to check certificates when the trust chain
1900is incomplete or if the certificate is self-signed.
1901
1902The OCSP resolver gets created by calling C<< $ssl->ocsp_resolver >> and
1903provides the following methods:
1904
1905=over 8
1906
1907=item hard_error
1908
1909This returns the hard error when checking the OCSP response.
1910Hard errors are certificate revocations. With the C<SSL_ocsp_mode> of
1911SSL_OCSP_FAIL_HARD any soft error (e.g. failures to get signed information
1912about the certificates) will be considered a hard error too.
1913
1914The OCSP resolving will stop on the first hard error.
1915
1916The method will return undef as long as no hard errors occurred and still
1917requests to be resolved. If all requests got resolved and no hard errors
1918occurred the method will return C<''>.
1919
1920=item soft_error
1921
1922This returns the soft error(s) which occurred when asking the OCSP responders.
1923
1924=item requests
1925
1926This will return a hash consisting of C<(url,request)>-tuples, e.g. which
1927contain the OCSP request string and the URL where it should be sent too. The
1928usual way to send such a request is as HTTP POST request with a content-type
1929of C<application/ocsp-request> or as a GET request with the base64 and
1930url-encoded request is added to the path of the URL.
1931
1932After you've handled all these requests and added the response with
1933C<add_response> you should better call this method again to make sure, that no
1934more requests are outstanding. IO::Socket::SSL will combine multiple OCSP
1935requests for the same server inside a single request, but some server don't
1936give a response to all these requests, so that one has to ask again with the
1937remaining requests.
1938
1939=item add_response($uri,$response)
1940
1941This method takes the HTTP body of the response which got received when sending
1942the OCSP request to C<$uri>. If no response was received or an error occurred
1943one should either retry or consider C<$response> as empty which will trigger a
1944soft error.
1945
1946The method returns the current value of C<hard_error>, e.g. a defined value
1947when no more requests need to be done.
1948
1949=item resolve_blocking(%args)
1950
1951This combines C<requests> and C<add_response> which L<HTTP::Tiny> to do all
1952necessary requests in a blocking way. C<%args> will be given to L<HTTP::Tiny>
1953so that you can put proxy settings etc here. L<HTTP::Tiny> will be called with
1954C<verify_SSL> of false, because the OCSP responses have their own signatures so
1955no extra SSL verification is needed.
1956
1957If you don't want to use blocking requests you need to roll your own user agent
1958with C<requests> and C<add_response>.
1959
1960=back
1961
1962=item B<< IO::Socket::SSL->new_from_fd($fd, [mode], %sslargs) >>
1963
1964This will convert a socket identified via a file descriptor into an SSL socket.
1965Note that the argument list does not include a "MODE" argument; if you supply
1966one, it will be thoughtfully ignored (for compatibility with IO::Socket::INET).
1967Instead, a mode of '+<' is assumed, and the file descriptor passed must be able
1968to handle such I/O because the initial SSL handshake requires bidirectional
1969communication.
1970
1971Internally the given $fd will be upgraded to a socket object using the
1972C<new_from_fd> method of the super class (L<IO::Socket::INET> or similar) and
1973then C<start_SSL> will be called using the given C<%sslargs>.
1974If C<$fd> is already an IO::Socket object you should better call C<start_SSL>
1975directly.
1976
1977=item B<IO::Socket::SSL::default_ca([ path|dir| SSL_ca_file => ..., SSL_ca_path => ... ])>
1978
1979Determines or sets the default CA path.
1980If existing path or dir or a hash is given it will set the default CA path to
1981this value and never try to detect it automatically.
1982If C<undef> is given it will forget any stored defaults and continue with
1983detection of system defaults.
1984If no arguments are given it will start detection of system defaults, unless it
1985has already stored user-set or previously detected values.
1986
1987The detection of system defaults works similar to OpenSSL, e.g. it will check
1988the directory specified in environment variable SSL_CERT_DIR or the path
1989OPENSSLDIR/certs (SSLCERTS: on VMS) and the file specified in environment
1990variable SSL_CERT_FILE or the path OPENSSLDIR/cert.pem (SSLCERTS:cert.pem on
1991VMS). Contrary to OpenSSL it will check if the SSL_ca_path contains PEM files
1992with the hash as file name and if the SSL_ca_file looks like PEM.
1993If no usable system default can be found it will try to load and use
1994L<Mozilla::CA> and if not available give up detection.
1995The result of the detection will be saved to speed up future calls.
1996
1997The function returns the saved default CA as hash with SSL_ca_file and
1998SSL_ca_path.
1999
2000=item B<IO::Socket::SSL::set_default_context(...)>
2001
2002You may use this to make IO::Socket::SSL automatically re-use a given context
2003(unless specifically overridden in a call to new()).
2004It accepts one argument, which should be either an IO::Socket::SSL object or an
2005IO::Socket::SSL::SSL_Context object.
2006See the SSL_reuse_ctx option of new() for more details.
2007Note that this sets the default context globally, so use with caution (esp. in
2008mod_perl scripts).
2009
2010=item B<IO::Socket::SSL::set_default_session_cache(...)>
2011
2012You may use this to make IO::Socket::SSL automatically re-use a given session
2013cache (unless specifically overridden in a call to new()).
2014It accepts one argument, which should be an IO::Socket::SSL::Session_Cache
2015object or similar (e.g. something which implements get_session, add_session and
2016del_session like IO::Socket::SSL::Session_Cache does).
2017See the SSL_session_cache option of new() for more details.
2018Note that this sets the default cache globally, so use with caution.
2019
2020=item B<IO::Socket::SSL::set_defaults(%args)>
2021
2022With this function one can set defaults for all SSL_* parameter used for
2023creation of the context, like the SSL_verify* parameter. Any SSL_* parameter can
2024be given or the following short versions:
2025
2026=over 8
2027
2028=item mode - SSL_verify_mode
2029
2030=item callback - SSL_verify_callback
2031
2032=item scheme - SSL_verifycn_scheme
2033
2034=item name - SSL_verifycn_name
2035
2036=back
2037
2038=item B<IO::Socket::SSL::set_client_defaults(%args)>
2039
2040Similar to C<set_defaults>, but only sets the defaults for client mode.
2041
2042=item B<IO::Socket::SSL::set_server_defaults(%args)>
2043
2044Similar to C<set_defaults>, but only sets the defaults for server mode.
2045
2046=item B<IO::Socket::SSL::set_args_filter_hack(\&code|'use_defaults')>
2047
2048Sometimes one has to use code which uses unwanted or invalid arguments for SSL,
2049typically disabling SSL verification or setting wrong ciphers or SSL versions.
2050With this hack it is possible to override these settings and restore sanity.
2051Example:
2052
2053    IO::Socket::SSL::set_args_filter_hack( sub {
2054	my ($is_server,$args) = @_;
2055	if ( ! $is_server ) {
2056	    # client settings - enable verification with default CA
2057	    # and fallback hostname verification etc
2058	    delete @{$args}{qw(
2059		SSL_verify_mode
2060		SSL_ca_file
2061		SSL_ca_path
2062		SSL_verifycn_scheme
2063		SSL_version
2064	    )};
2065	    # and add some fingerprints for known certs which are signed by
2066	    # unknown CAs or are self-signed
2067	    $args->{SSL_fingerprint} = ...
2068	}
2069    });
2070
2071With the short setting C<set_args_filter_hack('use_defaults')> it will prefer
2072the default settings in all cases. These default settings can be modified with
2073C<set_defaults>, C<set_client_defaults> and C<set_server_defaults>.
2074
2075=back
2076
2077The following methods are unsupported (not to mention futile!) and
2078IO::Socket::SSL will emit a large CROAK() if you are silly enough to use them:
2079
2080=over 4
2081
2082=item truncate
2083
2084=item stat
2085
2086=item ungetc
2087
2088=item setbuf
2089
2090=item setvbuf
2091
2092=item fdopen
2093
2094=item send/recv
2095
2096Note that send() and recv() cannot be reliably trapped by a tied filehandle
2097(such as that used by IO::Socket::SSL) and so may send unencrypted data over the
2098socket.	 Object-oriented calls to these functions will fail, telling you to use
2099the print/printf/syswrite and read/sysread families instead.
2100
2101=back
2102
2103=head1 DEPRECATIONS
2104
2105The following functions are deprecated and are only retained for compatibility:
2106
2107=over 2
2108
2109=item context_init()
2110
2111use the SSL_reuse_ctx option if you want to re-use a context
2112
2113=item socketToSSL() and socket_to_SSL()
2114
2115use IO::Socket::SSL->start_SSL() instead
2116
2117=item kill_socket()
2118
2119use close() instead
2120
2121=item get_peer_certificate()
2122
2123use the peer_certificate() function instead.
2124Used to return X509_Certificate with methods subject_name and issuer_name.
2125Now simply returns $self which has these methods (although deprecated).
2126
2127=item issuer_name()
2128
2129use peer_certificate( 'issuer' ) instead
2130
2131=item subject_name()
2132
2133use peer_certificate( 'subject' ) instead
2134
2135=back
2136
2137
2138=head1 EXAMPLES
2139
2140See the 'example' directory, the tests in 't' and also the tools in 'util'.
2141
2142
2143=head1 BUGS
2144
2145If you use IO::Socket::SSL together with threads you should load it (e.g. use or
2146require) inside the main thread before creating any other threads which use it.
2147This way it is much faster because it will be initialized only once. Also there
2148are reports that it might crash the other way.
2149
2150Creating an IO::Socket::SSL object in one thread and closing it in another
2151thread will not work.
2152
2153IO::Socket::SSL does not work together with Storable::fd_retrieve/fd_store.
2154See BUGS file for more information and how to work around the problem.
2155
2156Non-blocking and timeouts (which are based on non-blocking) are not
2157supported on Win32, because the underlying IO::Socket::INET does not support
2158non-blocking on this platform.
2159
2160If you have a server and it looks like you have a memory leak you might
2161check the size of your session cache. Default for Net::SSLeay seems to be
216220480, see the example for SSL_create_ctx_callback for how to limit it.
2163
2164TLS 1.3 support regarding session reuse is incomplete.
2165
2166=head1 SEE ALSO
2167
2168IO::Socket::INET, IO::Socket::INET6, IO::Socket::IP, Net::SSLeay.
2169
2170
2171=head1 THANKS
2172
2173Many thanks to all who added patches or reported bugs or helped IO::Socket::SSL
2174another way. Please keep reporting bugs and help with patches, even if they just
2175fix the documentation.
2176
2177Special thanks to the team of Net::SSLeay for the good cooperation.
2178
2179=head1 AUTHORS
2180
2181Steffen Ullrich, <sullr at cpan.org> is the current maintainer.
2182
2183Peter Behroozi, <behrooz at fas.harvard.edu> (Note the lack of an "i" at the end of "behrooz")
2184
2185Marko Asplund, <marko.asplund at kronodoc.fi>, was the original author of IO::Socket::SSL.
2186
2187Patches incorporated from various people, see file Changes.
2188
2189
2190=head1 COPYRIGHT
2191
2192The original versions of this module are Copyright (C) 1999-2002 Marko Asplund.
2193
2194The rewrite of this module is Copyright (C) 2002-2005 Peter Behroozi.
2195
2196Versions 0.98 and newer are Copyright (C) 2006-2014 Steffen Ullrich.
2197
2198This module is free software; you can redistribute it and/or
2199modify it under the same terms as Perl itself.
2200