1Net::SSLeay(3)        User Contributed Perl Documentation       Net::SSLeay(3)
2
3
4

NAME

6       Net::SSLeay - Perl extension for using OpenSSL
7

SYNOPSIS

9         use Net::SSLeay qw(get_https post_https sslcat make_headers make_form);
10
11         ($page) = get_https('www.bacus.pt', 443, '/');                 # 1
12
13         ($page, $response, %reply_headers)
14                = get_https('www.bacus.pt', 443, '/',                   # 2
15                       make_headers(User-Agent => 'Cryptozilla/5.0b1',
16                                    Referer    => 'https://www.bacus.pt'
17                       ));
18
19         ($page, $result, %headers) =                                   # 2b
20                = get_https('www.bacus.pt', 443, '/protected.html',
21                     make_headers(Authorization =>
22                                  'Basic ' . MIME::Base64::encode("$user:$pass",''))
23                     );
24
25         ($page, $response, %reply_headers)
26                = post_https('www.bacus.pt', 443, '/foo.cgi', '',       # 3
27                       make_form(OK   => '1',
28                                 name => 'Sampo'
29                       ));
30
31         $reply = sslcat($host, $port, $request);                       # 4
32
33         ($reply, $err, $server_cert) = sslcat($host, $port, $request); # 5
34
35         $Net::SSLeay::trace = 2;  # 0=no debugging, 1=ciphers, 2=trace, 3=dump data
36

DESCRIPTION

38       There is a related module called "Net::SSLeay::Handle" included in this
39       distribution that you might want to use instead. It has its own pod
40       documentation.
41
42       This module offers some high level convenience functions for accessing
43       web pages on SSL servers (for symmetry, the same API is offered for
44       accessing http servers, too), an "sslcat()" function for writing your
45       own clients, and finally access to the SSL api of the SSLeay/OpenSSL
46       package so you can write servers or clients for more complicated
47       applications.
48
49       For high level functions it is most convenient to import them into your
50       main namespace as indicated in the synopsis.
51
52       Case 1 demonstrates the typical invocation of get_https() to fetch an
53       HTML page from secure server. The first argument provides the hostname
54       or IP in dotted decimal notation of the remote server to contact. The
55       second argument is the TCP port at the remote end (your own port is
56       picked arbitrarily from high numbered ports as usual for TCP). The
57       third argument is the URL of the page without the host name part. If in
58       doubt consult the HTTP specifications at <http://www.w3c.org>.
59
60       Case 2 demonstrates full fledged use of "get_https()". As can be seen,
61       "get_https()" parses the response and response headers and returns them
62       as a list, which can be captured in a hash for later reference. Also a
63       fourth argument to "get_https()" is used to insert some additional
64       headers in the request. "make_headers()" is a function that will
65       convert a list or hash to such headers. By default "get_https()"
66       supplies "Host" (to make virtual hosting easy) and "Accept" (reportedly
67       needed by IIS) headers.
68
69       Case 2b demonstrates how to get a password protected page. Refer to the
70       HTTP protocol specifications for further details (e.g. RFC-2617).
71
72       Case 3 invokes "post_https()" to submit a HTML/CGI form to a secure
73       server. The first four arguments are equal to "get_https()" (note that
74       the empty string ('') is passed as header argument).  The fifth
75       argument is the contents of the form formatted according to CGI
76       specification. In this case the helper function "make_https()" is used
77       to do the formatting, but you could pass any string. "post_https()"
78       automatically adds "Content-Type" and "Content-Length" headers to the
79       request.
80
81       Case 4 shows the fundamental "sslcat()" function (inspired in spirit by
82       the "netcat" utility :-). It's your swiss army knife that allows you to
83       easily contact servers, send some data, and then get the response. You
84       are responsible for formatting the data and parsing the response -
85       "sslcat()" is just a transport.
86
87       Case 5 is a full invocation of "sslcat()" which allows the return of
88       errors as well as the server (peer) certificate.
89
90       The $trace global variable can be used to control the verbosity of the
91       high level functions. Level 0 guarantees silence, level 1 (the default)
92       only emits error messages.
93
94   Alternate versions of the API
95       The above mentioned functions actually return the response headers as a
96       list, which only gets converted to hash upon assignment (this
97       assignment looses information if the same header occurs twice, as may
98       be the case with cookies). There are also other variants of the
99       functions that return unprocessed headers and that return a reference
100       to a hash.
101
102         ($page, $response, @headers) = get_https('www.bacus.pt', 443, '/');
103         for ($i = 0; $i < $#headers; $i+=2) {
104             print "$headers[$i] = " . $headers[$i+1] . "\n";
105         }
106
107         ($page, $response, $headers, $server_cert)
108           = get_https3('www.bacus.pt', 443, '/');
109         print "$headers\n";
110
111         ($page, $response, %headers_ref, $server_cert)
112           = get_https4('www.bacus.pt', 443, '/');
113         for $k (sort keys %{headers_ref}) {
114             for $v (@{$headers_ref{$k}}) {
115                 print "$k = $v\n";
116             }
117         }
118
119       All of the above code fragments accomplish the same thing: display all
120       values of all headers. The API functions ending in "3" return the
121       headers simply as a scalar string and it is up to the application to
122       split them up. The functions ending in "4" return a reference to a hash
123       of arrays (see perlref and perllol if you are not familiar with complex
124       perl data structures). To access a single value of such a header hash
125       you would do something like
126
127         print $headers_ref{COOKIE}[0];
128
129       Variants 3 and 4 also allow you to discover the server certificate in
130       case you would like to store or display it, e.g.
131
132         ($p, $resp, $hdrs, $server_cert) = get_https3('www.bacus.pt', 443, '/');
133         if (!defined($server_cert) || ($server_cert == 0)) {
134             warn "Subject Name: undefined, Issuer  Name: undefined";
135         } else {
136             warn 'Subject Name: '
137                 . Net::SSLeay::X509_NAME_oneline(
138                        Net::SSLeay::X509_get_subject_name($server_cert))
139                     . 'Issuer  Name: '
140                         . Net::SSLeay::X509_NAME_oneline(
141                                Net::SSLeay::X509_get_issuer_name($server_cert));
142         }
143
144       Beware that this method only allows after the fact verification of the
145       certificate: by the time "get_https3()" has returned the https request
146       has already been sent to the server, whether you decide to trust it or
147       not. To do the verification correctly you must either employ the
148       OpenSSL certificate verification framework or use the lower level API
149       to first connect and verify the certificate and only then send the http
150       data. See the implementation of "ds_https3()" for guidance on how to do
151       this.
152
153   Using client certificates
154       Secure web communications are encrypted using symmetric crypto keys
155       exchanged using encryption based on the certificate of the server.
156       Therefore in all SSL connections the server must have a certificate.
157       This serves both to authenticate the server to the clients and to
158       perform the key exchange.
159
160       Sometimes it is necessary to authenticate the client as well. Two
161       options are available: HTTP basic authentication and a client side
162       certificate. The basic authentication over HTTPS is actually quite safe
163       because HTTPS guarantees that the password will not travel in the
164       clear. Never-the-less, problems like easily guessable passwords remain.
165       The client certificate method involves authentication of the client at
166       the SSL level using a certificate. For this to work, both the client
167       and the server have certificates (which typically are different) and
168       private keys.
169
170       The API functions outlined above accept additional arguments that allow
171       one to supply the client side certificate and key files. The format of
172       these files is the same as used for server certificates and the caveat
173       about encrypting private keys applies.
174
175         ($page, $result, %headers) =                                   # 2c
176                = get_https('www.bacus.pt', 443, '/protected.html',
177                     make_headers(Authorization =>
178                                  'Basic ' . MIME::Base64::encode("$user:$pass",'')),
179                     '', $mime_type6, $path_to_crt7, $path_to_key8);
180
181         ($page, $response, %reply_headers)
182                = post_https('www.bacus.pt', 443, '/foo.cgi',           # 3b
183                     make_headers('Authorization' =>
184                                  'Basic ' . MIME::Base64::encode("$user:$pass",'')),
185                     make_form(OK   => '1', name => 'Sampo'),
186                     $mime_type6, $path_to_crt7, $path_to_key8);
187
188       Case 2c demonstrates getting a password protected page that also
189       requires a client certificate, i.e. it is possible to use both
190       authentication methods simultaneously.
191
192       Case 3b is a full blown POST to a secure server that requires both
193       password authentication and a client certificate, just like in case 2c.
194
195       Note: The client will not send a certificate unless the server requests
196       one.  This is typically achieved by setting the verify mode to
197       "VERIFY_PEER" on the server:
198
199         Net::SSLeay::set_verify(ssl, Net::SSLeay::VERIFY_PEER, 0);
200
201       See "perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod" for a full
202       description.
203
204   Working through a web proxy
205       "Net::SSLeay" can use a web proxy to make its connections. You need to
206       first set the proxy host and port using "set_proxy()" and then just use
207       the normal API functions, e.g:
208
209         Net::SSLeay::set_proxy('gateway.myorg.com', 8080);
210         ($page) = get_https('www.bacus.pt', 443, '/');
211
212       If your proxy requires authentication, you can supply a username and
213       password as well
214
215         Net::SSLeay::set_proxy('gateway.myorg.com', 8080, 'joe', 'salainen');
216         ($page, $result, %headers) =
217                = get_https('www.bacus.pt', 443, '/protected.html',
218                     make_headers(Authorization =>
219                                  'Basic ' . MIME::Base64::encode("susie:pass",''))
220                     );
221
222       This example demonstrates the case where we authenticate to the proxy
223       as "joe" and to the final web server as "susie". Proxy authentication
224       requires the "MIME::Base64" module to work.
225
226   Certificate verification and Certificate Revoocation Lists (CRLs)
227       OpenSSL supports the ability to verify peer certificates. It can also
228       optionally check the peer certificate against a Certificate Revocation
229       List (CRL) from the certificates issuer. A CRL is a file, created by
230       the certificate issuer that lists all the certificates that it
231       previously signed, but which it now revokes. CRLs are in PEM format.
232
233       You can enable "Net::SSLeay CRL" checking like this:
234
235                   &Net::SSLeay::X509_STORE_CTX_set_flags
236                       (&Net::SSLeay::CTX_get_cert_store($ssl),
237                        &Net::SSLeay::X509_V_FLAG_CRL_CHECK);
238
239       After setting this flag, if OpenSSL checks a peer's certificate, then
240       it will attempt to find a CRL for the issuer. It does this by looking
241       for a specially named file in the search directory specified by
242       CTX_load_verify_locations.  CRL files are named with the hash of the
243       issuer's subject name, followed by ".r0", ".r1" etc.  For example
244       "ab1331b2.r0", "ab1331b2.r1". It will read all the .r files for the
245       issuer, and then check for a revocation of the peer cerificate in all
246       of them.  (You can also force it to look in a specific named CRL file.,
247       see below).  You can find out the hash of the issuer subject name in a
248       CRL with
249
250               openssl crl -in crl.pem -hash -noout
251
252       If the peer certificate does not pass the revocation list, or if no CRL
253       is found, then the handshaking fails with an error.
254
255       You can also force OpenSSL to look for CRLs in one or more arbitrarily
256       named files.
257
258           my $bio = Net::SSLeay::BIO_new_file($crlfilename, 'r');
259           my $crl = Net::SSLeay::PEM_read_bio_X509_CRL($bio);
260           if ($crl) {
261               Net::SSLeay::X509_STORE_add_crl(Net::SSLeay::CTX_get_cert_store($ssl, $crl);
262           } else {
263               error reading CRL....
264           }
265
266   Convenience routines
267       To be used with Low level API
268
269           Net::SSLeay::randomize($rn_seed_file,$additional_seed);
270           Net::SSLeay::set_cert_and_key($ctx, $cert_path, $key_path);
271           $cert = Net::SSLeay::dump_peer_certificate($ssl);
272           Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
273           $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
274
275           $got = Net::SSLeay::ssl_read_CRLF($ssl [, $max_length]);
276           $got = Net::SSLeay::ssl_read_until($ssl [, $delimit [, $max_length]]);
277           Net::SSLeay::ssl_write_CRLF($ssl, $message);
278
279       "randomize()" seeds the openssl PRNG with "/dev/urandom" (see the top
280       of "SSLeay.pm" for how to change or configure this) and optionally with
281       user provided data. It is very important to properly seed your random
282       numbers, so do not forget to call this. The high level API functions
283       automatically call "randomize()" so it is not needed with them. See
284       also caveats.
285
286       "set_cert_and_key()" takes two file names as arguments and sets the
287       certificate and private key to those. This can be used to set either
288       cerver certificates or client certificates.
289
290       "dump_peer_certificate()" allows you to get a plaintext description of
291       the certificate the peer (usually the server) presented to us.
292
293       "ssl_read_all()" and "ssl_write_all()" provide true blocking semantics
294       for these operations (see limitation, below, for explanation). These
295       are much preferred to the low level API equivalents (which implement
296       BSD blocking semantics). The message argument to "ssl_write_all()" can
297       be a reference. This is helpful to avoid unnecessary copying when
298       writing something big, e.g:
299
300           $data = 'A' x 1000000000;
301           Net::SSLeay::ssl_write_all($ssl, \$data) or die "ssl write failed";
302
303       "ssl_read_CRLF()" uses "ssl_read_all()" to read in a line terminated
304       with a carriage return followed by a linefeed (CRLF).  The CRLF is
305       included in the returned scalar.
306
307       "ssl_read_until()" uses "ssl_read_all()" to read from the SSL input
308       stream until it encounters a programmer specified delimiter.  If the
309       delimiter is undefined, $/ is used.  If $/ is undefined, "\n" is used.
310       One can optionally set a maximum length of bytes to read from the SSL
311       input stream.
312
313       "ssl_write_CRLF()" writes $message and appends CRLF to the SSL output
314       stream.
315
316   Low level API
317       In addition to the high level functions outlined above, this module
318       contains straight-forward access to SSL part of OpenSSL C api. Only the
319       SSL subpart of OpenSSL is implemented (if anyone wants to implement
320       other parts, feel free to submit patches).
321
322       See the "ssl.h" header from OpenSSL C distribution for a list of low
323       level SSLeay functions to call (check SSLeay.xs to see if some function
324       has been implemented). The module strips the initial "SSL_" off of the
325       SSLeay names. Generally you should use "Net::SSLeay::" in its place.
326       For example:
327
328       In C:
329
330               #include <ssl.h>
331
332               err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
333                                          &your_call_back_here);
334
335       In Perl:
336
337               use Net::SSLeay;
338
339               $err = Net::SSLeay::set_verify ($ssl,
340                                               Net::SSLeay::VERIFY_CLIENT_ONCE,
341                                               \&your_call_back_here);
342
343       If the function does not start with "SSL_" you should use the full
344       function name, e.g.:
345
346               $err = Net::SSLeay::ERR_get_error;
347
348       The following new functions behave in perlish way:
349
350               $got = Net::SSLeay::read($ssl);
351                                           # Performs SSL_read, but returns $got
352                                           # resized according to data received.
353                                           # Returns undef on failure.
354
355               Net::SSLeay::write($ssl, $foo) || die;
356                                           # Performs SSL_write, but automatically
357                                           # figures out the size of $foo
358
359       In order to use the low level API you should start your programs with
360       the following incantation:
361
362               use Net::SSLeay qw(die_now die_if_ssl_error);
363               Net::SSLeay::load_error_strings();
364               Net::SSLeay::SSLeay_add_ssl_algorithms();    # Important!
365               Net::SSLeay::ENGINE_load_builtin_engines();  # If you want built-in engines
366               Net::SSLeay::ENGINE_register_all_complete(); # If you want built-in engines
367               Net::SSLeay::randomize();
368
369       "die_now()" and "die_if_ssl_error()" are used to conveniently print the
370       SSLeay error stack when something goes wrong, thusly:
371
372               Net::SSLeay::connect($ssl) or die_now("Failed SSL connect ($!)");
373               Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
374
375       You can also use "Net::SSLeay::print_errs()" to dump the error stack
376       without exiting the program. As can be seen, your code becomes much
377       more readable if you import the error reporting functions into your
378       main name space.
379
380       I can not emphasize the need to check for error enough. Use these
381       functions even in the most simple programs, they will reduce debugging
382       time greatly. Do not ask questions on the mailing list without having
383       first sprinkled these in your code.
384
385   Sockets
386       Perl uses file handles for all I/O. While SSLeay has a quite flexible
387       BIO mechanism and perl has an evolved PerlIO mechanism, this module
388       still sticks to using file descriptors. Thus to attach SSLeay to a
389       socket you should use "fileno()" to extract the underlying file
390       descriptor:
391
392           Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno
393
394       You should also set $| to 1 to eliminate STDIO buffering so you do not
395       get confused if you use perl I/O functions to manipulate your socket
396       handle.
397
398       If you need to select(2) on the socket, go right ahead, but be warned
399       that OpenSSL does some internal buffering so SSL_read does not always
400       return data even if the socket selected for reading (just keep on
401       selecting and trying to read). "Net::SSLeay" is no different from the C
402       language OpenSSL in this respect.
403
404   Callbacks
405       You can establish a per-context verify callback function something like
406       this:
407
408               sub verify {
409                   my ($ok, $x509_store_ctx) = @_;
410                   print "Verifying certificate...\n";
411                       ...
412                   return $ok;
413               }
414
415       It is used like this:
416
417               Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);
418
419       Per-context callbacks for decrypting private keys are implemented.
420
421               Net::SSLeay::CTX_set_default_passwd_cb($ctx, sub { "top-secret" });
422               Net::SSLeay::CTX_use_PrivateKey_file($ctx, "key.pem",
423                                                    Net::SSLeay::FILETYPE_PEM)
424                   or die "Error reading private key";
425               Net::SSLeay::CTX_set_default_passwd_cb($ctx, undef);
426
427       If Hello Extensions are supported by your OpenSSL, a session secret
428       callback can be set up to be called when a session secret is set by
429       openssl.
430
431       Establish it like this:
432           Net::SSLeay::set_session_secret_cb($ssl, \&session_secret_cb,
433       $somedata);
434
435       It will be called like this:
436
437           sub session_secret_cb
438           {
439               my ($secret, \@cipherlist, \$preferredcipher, $somedata) = @_;
440           }
441
442       No other callbacks are implemented. You do not need to use any callback
443       for simple (i.e. normal) cases where the SSLeay built-in verify
444       mechanism satisfies your needs.
445
446       It is required to reset these callbacks to undef immediately after use
447       to prevent memory leaks, thread safety problems and crashes on exit
448       that can occur if different threads set different callbacks.
449
450       If you want to use callback stuff, see examples/callback.pl! Its the
451       only one I am able to make work reliably.
452
453   X509 and RAND stuff
454       This module largely lacks interface to the X509 and RAND routines, but
455       as I was lazy and needed them, the following kludges are implemented:
456
457           $x509_name = Net::SSLeay::X509_get_subject_name($x509_cert);
458           $x509_name = Net::SSLeay::X509_get_issuer_name($x509_cert);
459           print Net::SSLeay::X509_NAME_oneline($x509_name);
460           $text = Net::SSLeay::X509_NAME_get_text_by_NID($name, $nid);
461
462           ($type1, $subject1, $type2, $subject2, ...) =
463              Net::SSLeay::X509_get_subjectAltNames($x509_cert)
464
465           subjectAltName types as per x509v3.h GEN_*, for example
466           GEN_DNS or GEN_IPADD which can be imported.
467
468           Net::SSLeay::RAND_seed($buf);   # Perlishly figures out buf size
469           Net::SSLeay::RAND_bytes($buf, $num);
470           Net::SSLeay::RAND_pseudo_bytes($buf, $num);
471           Net::SSLeay::RAND_add($buf, $num, $entropy);
472           Net::SSLeay::RAND_poll();
473           Net::SSLeay::RAND_status();
474           Net::SSLeay::RAND_cleanup();
475           Net::SSLeay::RAND_file_name($num);
476           Net::SSLeay::RAND_load_file($file_name, $how_many_bytes);
477           Net::SSLeay::RAND_write_file($file_name);
478           Net::SSLeay::RAND_egd($path);
479           Net::SSLeay::RAND_egd_bytes($path, $bytes);
480
481       Actually you should consider using the following helper functions:
482
483           print Net::SSLeay::dump_peer_certificate($ssl);
484           Net::SSLeay::randomize();
485
486   RSA interface
487       Some RSA functions are available:
488
489           $rsakey = Net::SSLeay::RSA_generate_key();
490           Net::SSLeay::CTX_set_tmp_rsa($ctx, $rsakey);
491           Net::SSLeay::RSA_free($rsakey);
492
493   Digests
494       Some Digest functions are available if supported by the underlying
495       library.  These may include MD2, MD4, MD5, and RIPEMD160:
496
497           $hash = Net::SSLeay::MD5($foo);
498           print unpack('H*', $hash);
499
500   BIO interface
501       Some BIO functions are available:
502
503           Net::SSLeay::BIO_s_mem();
504           $bio = Net::SSLeay::BIO_new(BIO_s_mem())
505           $bio = Net::SSLeay::BIO_new_file($filename, $mode);
506           Net::SSLeay::BIO_free($bio)
507           $count = Net::SSLeay::BIO_write($data);
508           $data = Net::SSLeay::BIO_read($bio);
509           $data = Net::SSLeay::BIO_read($bio, $maxbytes);
510           $is_eof = Net::SSLeay::BIO_eof($bio);
511           $count = Net::SSLeay::BIO_pending($bio);
512           $count = Net::SSLeay::BIO_wpending ($bio);
513
514   Low level API
515       Some very low level API functions are available:
516
517           $client_random = Net::SSLeay::get_client_random($ssl);
518           $server_random = Net::SSLeay::get_server_random($ssl);
519           $session = Net::SSLeay::get_session($ssl);
520           $master_key = Net::SSLeay::SESSION_get_master_key($session);
521           Net::SSLeay::SESSION_set_master_key($session, $master_secret);
522           $keyblocksize = Net::SSLeay::get_keyblock_size($session);
523
524   HTTP (without S) API
525       Over the years it has become clear that it would be convenient to use
526       the light-weight flavour API of "Net::SSLeay" for normal HTTP as well
527       (see "LWP" for the heavy-weight object-oriented approach). In fact it
528       would be nice to be able to flip https on and off on the fly. Thus
529       regular HTTP support was evolved.
530
531         use Net::SSLeay qw(get_http post_http tcpcat
532                             get_httpx post_httpx tcpxcat
533                             make_headers make_form);
534
535         ($page, $result, %headers) =
536                = get_http('www.bacus.pt', 443, '/protected.html',
537                     make_headers(Authorization =>
538                                  'Basic ' . MIME::Base64::encode("$user:$pass",''))
539                     );
540
541         ($page, $response, %reply_headers)
542                = post_http('www.bacus.pt', 443, '/foo.cgi', '',
543                       make_form(OK   => '1',
544                                 name => 'Sampo'
545                       ));
546
547         ($reply, $err) = tcpcat($host, $port, $request);
548
549         ($page, $result, %headers) =
550                = get_httpx($usessl, 'www.bacus.pt', 443, '/protected.html',
551                     make_headers(Authorization =>
552                                  'Basic ' . MIME::Base64::encode("$user:$pass",''))
553                     );
554
555         ($page, $response, %reply_headers)
556                = post_httpx($usessl, 'www.bacus.pt', 443, '/foo.cgi', '',
557                       make_form(OK   => '1',  name => 'Sampo' ));
558
559         ($reply, $err, $server_cert) = tcpxcat($usessl, $host, $port, $request);
560
561       As can be seen, the "x" family of APIs takes as the first argument a
562       flag which indicates whether SSL is used or not.
563

EXAMPLES

565       One very good example to look at is the implementation of "sslcat()" in
566       the "SSLeay.pm" file.
567
568       The following is a simple SSLeay client (with too little error checking
569       :-(
570
571           #!/usr/local/bin/perl
572           use Socket;
573           use Net::SSLeay qw(die_now die_if_ssl_error) ;
574           Net::SSLeay::load_error_strings();
575           Net::SSLeay::SSLeay_add_ssl_algorithms();
576           Net::SSLeay::randomize();
577
578           ($dest_serv, $port, $msg) = @ARGV;      # Read command line
579           $port = getservbyname ($port, 'tcp') unless $port =~ /^\d+$/;
580           $dest_ip = gethostbyname ($dest_serv);
581           $dest_serv_params  = sockaddr_in($port, $dest_ip);
582
583           socket  (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
584           connect (S, $dest_serv_params)          or die "connect: $!";
585           select  (S); $| = 1; select (STDOUT);   # Eliminate STDIO buffering
586
587           # The network connection is now open, lets fire up SSL
588
589           $ctx = Net::SSLeay::CTX_new() or die_now("Failed to create SSL_CTX $!");
590           Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
591                and die_if_ssl_error("ssl ctx set options");
592           $ssl = Net::SSLeay::new($ctx) or die_now("Failed to create SSL $!");
593           Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno
594           $res = Net::SSLeay::connect($ssl) and die_if_ssl_error("ssl connect");
595           print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
596
597           # Exchange data
598
599           $res = Net::SSLeay::write($ssl, $msg);  # Perl knows how long $msg is
600           die_if_ssl_error("ssl write");
601           CORE::shutdown S, 1;  # Half close --> No more output, sends EOF to server
602           $got = Net::SSLeay::read($ssl);         # Perl returns undef on failure
603           die_if_ssl_error("ssl read");
604           print $got;
605
606           Net::SSLeay::free ($ssl);               # Tear down connection
607           Net::SSLeay::CTX_free ($ctx);
608           close S;
609
610       The following is a simple SSLeay echo server (non forking):
611
612           #!/usr/local/bin/perl -w
613           use Socket;
614           use Net::SSLeay qw(die_now die_if_ssl_error);
615           Net::SSLeay::load_error_strings();
616           Net::SSLeay::SSLeay_add_ssl_algorithms();
617           Net::SSLeay::randomize();
618
619           $our_ip = "\0\0\0\0"; # Bind to all interfaces
620           $port = 1235;
621           $sockaddr_template = 'S n a4 x8';
622           $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);
623
624           socket (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
625           bind (S, $our_serv_params)             or die "bind:   $!";
626           listen (S, 5)                          or die "listen: $!";
627           $ctx = Net::SSLeay::CTX_new ()         or die_now("CTX_new ($ctx): $!");
628           Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
629                and die_if_ssl_error("ssl ctx set options");
630
631           # Following will ask password unless private key is not encrypted
632           Net::SSLeay::CTX_use_RSAPrivateKey_file ($ctx, 'plain-rsa.pem',
633                                                    &Net::SSLeay::FILETYPE_PEM);
634           die_if_ssl_error("private key");
635           Net::SSLeay::CTX_use_certificate_file ($ctx, 'plain-cert.pem',
636                                                  &Net::SSLeay::FILETYPE_PEM);
637           die_if_ssl_error("certificate");
638
639           while (1) {
640               print "Accepting connections...\n";
641               ($addr = accept (NS, S))           or die "accept: $!";
642               select (NS); $| = 1; select (STDOUT);  # Piping hot!
643
644               ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
645               @inetaddr = unpack('C4',$client_ip);
646               print "$af connection from " .
647               join ('.', @inetaddr) . ":$client_port\n";
648
649               # We now have a network connection, lets fire up SSLeay...
650
651               $ssl = Net::SSLeay::new($ctx)      or die_now("SSL_new ($ssl): $!");
652               Net::SSLeay::set_fd($ssl, fileno(NS));
653
654               $err = Net::SSLeay::accept($ssl) and die_if_ssl_error('ssl accept');
655               print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
656
657               # Connected. Exchange some data.
658
659               $got = Net::SSLeay::read($ssl);     # Returns undef on fail
660               die_if_ssl_error("ssl read");
661               print "Got `$got' (" . length ($got) . " chars)\n";
662
663               Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
664               die_if_ssl_error("ssl write");
665
666               Net::SSLeay::free ($ssl);           # Tear down connection
667               close NS;
668           }
669
670       Yet another echo server. This one runs from "/etc/inetd.conf" so it
671       avoids all the socket code overhead. Only caveat is opening an rsa key
672       file - it had better be without any encryption or else it will not know
673       where to ask for the password. Note how "STDIN" and "STDOUT" are wired
674       to SSL.
675
676           #!/usr/local/bin/perl
677           # /etc/inetd.conf
678           #    ssltst stream tcp nowait root /path/to/server.pl server.pl
679           # /etc/services
680           #    ssltst         1234/tcp
681
682           use Net::SSLeay qw(die_now die_if_ssl_error);
683           Net::SSLeay::load_error_strings();
684           Net::SSLeay::SSLeay_add_ssl_algorithms();
685           Net::SSLeay::randomize();
686
687           chdir '/key/dir' or die "chdir: $!";
688           $| = 1;  # Piping hot!
689           open LOG, ">>/dev/console" or die "Can't open log file $!";
690           select LOG; print "server.pl started\n";
691
692           $ctx = Net::SSLeay::CTX_new()     or die_now "CTX_new ($ctx) ($!)";
693           $ssl = Net::SSLeay::new($ctx)     or die_now "new ($ssl) ($!)";
694           Net::SSLeay::set_options($ssl, &Net::SSLeay::OP_ALL)
695                and die_if_ssl_error("ssl set options");
696
697           # We get already open network connection from inetd, now we just
698           # need to attach SSLeay to STDIN and STDOUT
699           Net::SSLeay::set_rfd($ssl, fileno(STDIN));
700           Net::SSLeay::set_wfd($ssl, fileno(STDOUT));
701
702           Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
703                                                Net::SSLeay::FILETYPE_PEM);
704           die_if_ssl_error("private key");
705           Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
706                                              Net::SSLeay::FILETYPE_PEM);
707           die_if_ssl_error("certificate");
708
709           Net::SSLeay::accept($ssl) and die_if_ssl_err("ssl accept: $!");
710           print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
711
712           $got = Net::SSLeay::read($ssl);
713           die_if_ssl_error("ssl read");
714           print "Got `$got' (" . length ($got) . " chars)\n";
715
716           Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";
717           die_if_ssl_error("ssl write");
718
719           Net::SSLeay::free ($ssl);         # Tear down the connection
720           Net::SSLeay::CTX_free ($ctx);
721           close LOG;
722
723       There are also a number of example/test programs in the examples
724       directory:
725
726           sslecho.pl   -  A simple server, not unlike the one above
727           minicli.pl   -  Implements a client using low level SSLeay routines
728           sslcat.pl    -  Demonstrates using high level sslcat utility function
729           get_page.pl  -  Is a utility for getting html pages from secure servers
730           callback.pl  -  Demonstrates certificate verification and callback usage
731           stdio_bulk.pl       - Does SSL over Unix pipes
732           ssl-inetd-serv.pl   - SSL server that can be invoked from inetd.conf
733           httpd-proxy-snif.pl - Utility that allows you to see how a browser
734                                 sends https request to given server and what reply
735                                 it gets back (very educative :-)
736           makecert.pl  -  Creates a self signed cert (does not use this module)
737

LIMITATIONS

739       "Net::SSLeay::read()" uses an internal buffer of 32KB, thus no single
740       read will return more. In practice one read returns much less, usually
741       as much as fits in one network packet. To work around this, you should
742       use a loop like this:
743
744           $reply = '';
745           while ($got = Net::SSLeay::read($ssl)) {
746               last if print_errs('SSL_read');
747               $reply .= $got;
748           }
749
750       Although there is no built-in limit in "Net::SSLeay::write()", the
751       network packet size limitation applies here as well, thus use:
752
753           $written = 0;
754
755           while ($written < length($message)) {
756               $written += Net::SSLeay::write($ssl, substr($message, $written));
757               last if print_errs('SSL_write');
758           }
759
760       Or alternatively you can just use the following convenience functions:
761
762           Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
763           $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
764

KNOWN BUGS AND CAVEATS

766       Autoloader emits a
767
768           Argument "xxx" isn't numeric in entersub at blib/lib/Net/SSLeay.pm'
769
770       warning if die_if_ssl_error is made autoloadable. If you figure out
771       why, drop me a line.
772
773       Callback set using "SSL_set_verify()" does not appear to work. This may
774       well be an openssl problem (e.g. see "ssl/ssl_lib.c" line 1029). Try
775       using "SSL_CTX_set_verify()" instead and do not be surprised if even
776       this stops working in future versions.
777
778       Callback and certificate verification stuff is generally too little
779       tested.
780
781       Random numbers are not initialized randomly enough, especially if you
782       do not have "/dev/random" and/or "/dev/urandom" (such as in Solaris
783       platforms - but I've been suggested that cryptorand daemon from the
784       SUNski package solves this). In this case you should investigate third
785       party software that can emulate these devices, e.g. by way of a named
786       pipe to some program.
787
788       Another gotcha with random number initialization is randomness
789       depletion. This phenomenon, which has been extensively discussed in
790       OpenSSL, Apache-SSL, and Apache-mod_ssl forums, can cause your script
791       to block if you use "/dev/random" or to operate insecurely if you use
792       "/dev/urandom". What happens is that when too much randomness is drawn
793       from the operating system's randomness pool then randomness can
794       temporarily be unavailable. "/dev/random" solves this problem by
795       waiting until enough randomness can be gathered - and this can take a
796       long time since blocking reduces activity in the machine and less
797       activity provides less random events: a vicious circle.  "/dev/urandom"
798       solves this dilemma more pragmatically by simply returning predictable
799       "random" numbers. Some" /dev/urandom" emulation software however
800       actually seems to implement "/dev/random" semantics. Caveat emptor.
801
802       I've been pointed to two such daemons by Mik Firestone
803       <mik@@speed.stdio._com> who has used them on Solaris 8:
804
805       1.  Entropy Gathering Daemon (EGD) at
806           <http://www.lothar.com/tech/crypto/>
807
808       2.  Pseudo-random number generating daemon (PRNGD) at
809           http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html
810           <http://www.aet.tu-
811           cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
812
813       If you are using the low level API functions to communicate with other
814       SSL implementations, you would do well to call
815
816           Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
817                and die_if_ssl_error("ssl ctx set options");
818
819       to cope with some well know bugs in some other SSL implementations. The
820       high level API functions always set all known compatibility options.
821
822       Sometimes "sslcat()" (and the high level HTTPS functions that build on
823       it) is too fast in signaling the EOF to legacy HTTPS servers. This
824       causes the server to return empty page. To work around this problem you
825       can set the global variable
826
827           $Net::SSLeay::slowly = 1;   # Add sleep so broken servers can keep up
828
829       HTTP/1.1 is not supported. Specifically this module does not know to
830       issue or serve multiple http requests per connection. This is a serious
831       shortcoming, but using the SSL session cache on your server helps to
832       alleviate the CPU load somewhat.
833
834       As of version 1.09 many newer OpenSSL auxiliary functions were added
835       (from "REM_AUTOMATICALLY_GENERATED_1_09" onwards in "SSLeay.xs").
836       Unfortunately I have not had any opportunity to test these. Some of
837       them are trivial enough that I believe they "just work", but others
838       have rather complex interfaces with function pointers and all. In these
839       cases you should proceed wit great caution.
840
841       This module defaults to using OpenSSL automatic protocol negotiation
842       code for automatically detecting the version of the SSL protocol that
843       the other end talks. With most web servers this works just fine, but
844       once in a while I get complaints from people that the module does not
845       work with some web servers. Usually this can be solved by explicitly
846       setting the protocol version, e.g.
847
848          $Net::SSLeay::ssl_version = 2;  # Insist on SSLv2
849          $Net::SSLeay::ssl_version = 3;  # Insist on SSLv3
850          $Net::SSLeay::ssl_version = 10; # Insist on TLSv1
851
852       Although the autonegotiation is nice to have, the SSL standards do not
853       formally specify any such mechanism. Most of the world has accepted the
854       SSLeay/OpenSSL way of doing it as the de facto standard. But for the
855       few that think differently, you have to explicitly speak the correct
856       version. This is not really a bug, but rather a deficiency in the
857       standards. If a site refuses to respond or sends back some nonsensical
858       error codes (at the SSL handshake level), try this option before
859       mailing me.
860
861       The high level API returns the certificate of the peer, thus allowing
862       one to check what certificate was supplied. However, you will only be
863       able to check the certificate after the fact, i.e. you already sent
864       your form data by the time you find out that you did not trust them,
865       oops.
866
867       So, while being able to know the certificate after the fact is surely
868       useful, the security minded would still choose to do the connection and
869       certificate verification first and only then exchange data with the
870       site. Currently none of the high level API functions do this, thus you
871       would have to program it using the low level API. A good place to start
872       is to see how the "Net::SSLeay::http_cat()" function is implemented.
873
874       The high level API functions use a global file handle "SSLCAT_S"
875       internally. This really should not be a problem because there is no way
876       to interleave the high level API functions, unless you use threads (but
877       threads are not very well supported in perl anyway (as of version
878       5.6.1). However, you may run into problems if you call undocumented
879       internal functions in an interleaved fashion.
880

DIAGNOSTICS

882       Random number generator not seeded!!!
883           (W) This warning indicates that "randomize()" was not able to read
884           "/dev/random" or "/dev/urandom", possibly because your system does
885           not have them or they are differently named. You can still use SSL,
886           but the encryption will not be as strong.
887
888       open_tcp_connection: destination host not found:`server' (port 123)
889       ($!)
890           Name lookup for host named "server" failed.
891
892       open_tcp_connection: failed `server', 123 ($!)
893           The name was resolved, but establising the TCP connection failed.
894
895       msg 123: 1 - error:140770F8:SSL routines:SSL23_GET_SERVER_HELLO:unknown
896       proto
897           SSLeay error string. The first number (123) is the PID, the second
898           number (1) indicates the position of the error message in SSLeay
899           error stack.  You often see a pile of these messages as errors
900           cascade.
901
902       msg 123: 1 - error:02001002::lib(2) :func(1) :reason(2)
903           The same as above, but you didn't call load_error_strings() so
904           SSLeay couldn't verbosely explain the error. You can still find out
905           what it means with this command:
906
907               /usr/local/ssl/bin/ssleay errstr 02001002
908
909       Password is being asked for private key
910           This is normal behaviour if your private key is encrypted. Either
911           you have to supply the password or you have to use an unencrypted
912           private key. Scan OpenSSL.org for the FAQ that explains how to do
913           this (or just study examples/makecert.pl which is used during "make
914           test" to do just that).
915

BUGS AND SUPPORT

917       Please report any bugs or feature requests to "bug-Net-SSLeay at
918       rt.cpan.org", or through the web interface at
919       http://rt.cpan.org/Public/Dist/Display.html?Name=Net-SSLeay
920       <http://rt.cpan.org/Public/Dist/Display.html?Name=Net-SSLeay>.  I will
921       be notified, and then you'll automatically be notified of progress on
922       your bug as I make changes.
923
924       Subversion access to the latest source code etc can be obtained at
925       http://alioth.debian.org/projects/net-ssleay
926       <http://alioth.debian.org/projects/net-ssleay>
927
928       The developer mailing list (for people interested in contributing to
929       the source code) can be found at
930       http://lists.alioth.debian.org/mailman/listinfo/net-ssleay-devel
931       <http://lists.alioth.debian.org/mailman/listinfo/net-ssleay-devel>
932
933       You can find documentation for this module with the "perldoc" command.
934
935           perldoc Net::SSLeay
936
937       You can also look for information at:
938
939       ·   AnnoCPAN: Annotated CPAN documentation
940
941           http://annocpan.org/dist/Net-SSLeay <http://annocpan.org/dist/Net-
942           SSLeay>
943
944       ·   CPAN Ratings
945
946           http://cpanratings.perl.org/d/Net-SSLeay
947           <http://cpanratings.perl.org/d/Net-SSLeay>
948
949       ·   Search CPAN
950
951           http://search.cpan.org/dist/Net-SSLeay
952           <http://search.cpan.org/dist/Net-SSLeay>
953
954       Commercial support for Net::SSLeay may be obtained from
955
956          Symlabs (netssleay@symlabs.com)
957          Tel: +351-214.222.630
958          Fax: +351-214.222.637
959

AUTHOR

961       Maintained by Mike McCauley and Florian Ragwitz since November 2005
962
963       Originally written by Sampo KellomA~Xki <sampo@symlabs.com>
964
966       Copyright (c) 1996-2003 Sampo KellomA~Xki <sampo@symlabs.com>
967
968       Copyright (C) 2005-2006 Florian Ragwitz <rafl@debian.org>
969
970       Copyright (C) 2005 Mike McCauley <mikem@open.com.au>
971
972       All Rights Reserved.
973
974       Distribution and use of this module is under the same terms as the
975       OpenSSL package itself (i.e. free, but mandatory attribution; NO
976       WARRANTY). Please consult LICENSE file in the root of the OpenSSL
977       distribution.
978
979       While the source distribution of this perl module does not contain
980       Eric's or OpenSSL's code, if you use this module you will use OpenSSL
981       library. Please give Eric and OpenSSL team credit (as required by their
982       licenses).
983
984       And remember, you, and nobody else but you, are responsible for
985       auditing this module and OpenSSL library for security problems,
986       backdoors, and general suitability for your application.
987

SEE ALSO

989         Net::SSLeay::Handle                      - File handle interface
990         ./examples                               - Example servers and a clients
991         <http://www.openssl.org/>                - OpenSSL source, documentation, etc
992         openssl-users-request@openssl.org        - General OpenSSL mailing list
993         <http://www.ietf.org/rfc/rfc2246.txt>    - TLS 1.0 specification
994         <http://www.w3c.org>                     - HTTP specifications
995         <http://www.ietf.org/rfc/rfc2617.txt>    - How to send password
996         <http://www.lothar.com/tech/crypto/>     - Entropy Gathering Daemon (EGD)
997         <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
998                                  - pseudo-random number generating daemon (PRNGD)
999         perl(1)
1000         perlref(1)
1001         perllol(1)
1002         perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod
1003
1004
1005
1006perl v5.12.0                      2010-05-04                    Net::SSLeay(3)
Impressum