1Net::SSLeay(3) User Contributed Perl Documentation Net::SSLeay(3)
2
3
4
6 Net::SSLeay - Perl extension for using OpenSSL
7
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
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 convinience 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 BIO interface
494 Some BIO functions are available:
495
496 Net::SSLeay::BIO_s_mem();
497 $bio = Net::SSLeay::BIO_new(BIO_s_mem())
498 $bio = Net::SSLeay::BIO_new_file($filename, $mode);
499 Net::SSLeay::BIO_free($bio)
500 $count = Net::SSLeay::BIO_write($data);
501 $data = Net::SSLeay::BIO_read($bio);
502 $data = Net::SSLeay::BIO_read($bio, $maxbytes);
503 $is_eof = Net::SSLeay::BIO_eof($bio);
504 $count = Net::SSLeay::BIO_pending($bio);
505 $count = Net::SSLeay::BIO_wpending ($bio);
506
507 Low level API
508 Some very low level API functions are available:
509
510 $client_random = Net::SSLeay::get_client_random($ssl);
511 $server_random = Net::SSLeay::get_server_random($ssl);
512 $session = Net::SSLeay::get_session($ssl);
513 $master_key = Net::SSLeay::SESSION_get_master_key($session);
514 Net::SSLeay::SESSION_set_master_key($session, $master_secret);
515 $keyblocksize = Net::SSLeay::get_keyblock_size($session);
516
517 HTTP (without S) API
518 Over the years it has become clear that it would be convenient to use
519 the light-weight flavour API of "Net::SSLeay" for normal HTTP as well
520 (see "LWP" for the heavy-weight object-oriented approach). In fact it
521 would be nice to be able to flip https on and off on the fly. Thus
522 regular HTTP support was evolved.
523
524 use Net::SSLeay qw(get_http post_http tcpcat
525 get_httpx post_httpx tcpxcat
526 make_headers make_form);
527
528 ($page, $result, %headers) =
529 = get_http('www.bacus.pt', 443, '/protected.html',
530 make_headers(Authorization =>
531 'Basic ' . MIME::Base64::encode("$user:$pass",''))
532 );
533
534 ($page, $response, %reply_headers)
535 = post_http('www.bacus.pt', 443, '/foo.cgi', '',
536 make_form(OK => '1',
537 name => 'Sampo'
538 ));
539
540 ($reply, $err) = tcpcat($host, $port, $request);
541
542 ($page, $result, %headers) =
543 = get_httpx($usessl, 'www.bacus.pt', 443, '/protected.html',
544 make_headers(Authorization =>
545 'Basic ' . MIME::Base64::encode("$user:$pass",''))
546 );
547
548 ($page, $response, %reply_headers)
549 = post_httpx($usessl, 'www.bacus.pt', 443, '/foo.cgi', '',
550 make_form(OK => '1', name => 'Sampo' ));
551
552 ($reply, $err, $server_cert) = tcpxcat($usessl, $host, $port, $request);
553
554 As can be seen, the "x" family of APIs takes as the first argument a
555 flag which indicates whether SSL is used or not.
556
558 One very good example to look at is the implementation of "sslcat()" in
559 the "SSLeay.pm" file.
560
561 The following is a simple SSLeay client (with too little error checking
562 :-(
563
564 #!/usr/local/bin/perl
565 use Socket;
566 use Net::SSLeay qw(die_now die_if_ssl_error) ;
567 Net::SSLeay::load_error_strings();
568 Net::SSLeay::SSLeay_add_ssl_algorithms();
569 Net::SSLeay::randomize();
570
571 ($dest_serv, $port, $msg) = @ARGV; # Read command line
572 $port = getservbyname ($port, 'tcp') unless $port =~ /^\d+$/;
573 $dest_ip = gethostbyname ($dest_serv);
574 $dest_serv_params = sockaddr_in($port, $dest_ip);
575
576 socket (S, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
577 connect (S, $dest_serv_params) or die "connect: $!";
578 select (S); $| = 1; select (STDOUT); # Eliminate STDIO buffering
579
580 # The network connection is now open, lets fire up SSL
581
582 $ctx = Net::SSLeay::CTX_new() or die_now("Failed to create SSL_CTX $!");
583 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
584 and die_if_ssl_error("ssl ctx set options");
585 $ssl = Net::SSLeay::new($ctx) or die_now("Failed to create SSL $!");
586 Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
587 $res = Net::SSLeay::connect($ssl) and die_if_ssl_error("ssl connect");
588 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
589
590 # Exchange data
591
592 $res = Net::SSLeay::write($ssl, $msg); # Perl knows how long $msg is
593 die_if_ssl_error("ssl write");
594 CORE::shutdown S, 1; # Half close --> No more output, sends EOF to server
595 $got = Net::SSLeay::read($ssl); # Perl returns undef on failure
596 die_if_ssl_error("ssl read");
597 print $got;
598
599 Net::SSLeay::free ($ssl); # Tear down connection
600 Net::SSLeay::CTX_free ($ctx);
601 close S;
602
603 The following is a simple SSLeay echo server (non forking):
604
605 #!/usr/local/bin/perl -w
606 use Socket;
607 use Net::SSLeay qw(die_now die_if_ssl_error);
608 Net::SSLeay::load_error_strings();
609 Net::SSLeay::SSLeay_add_ssl_algorithms();
610 Net::SSLeay::randomize();
611
612 $our_ip = "\0\0\0\0"; # Bind to all interfaces
613 $port = 1235;
614 $sockaddr_template = 'S n a4 x8';
615 $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);
616
617 socket (S, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
618 bind (S, $our_serv_params) or die "bind: $!";
619 listen (S, 5) or die "listen: $!";
620 $ctx = Net::SSLeay::CTX_new () or die_now("CTX_new ($ctx): $!");
621 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
622 and die_if_ssl_error("ssl ctx set options");
623
624 # Following will ask password unless private key is not encrypted
625 Net::SSLeay::CTX_use_RSAPrivateKey_file ($ctx, 'plain-rsa.pem',
626 &Net::SSLeay::FILETYPE_PEM);
627 die_if_ssl_error("private key");
628 Net::SSLeay::CTX_use_certificate_file ($ctx, 'plain-cert.pem',
629 &Net::SSLeay::FILETYPE_PEM);
630 die_if_ssl_error("certificate");
631
632 while (1) {
633 print "Accepting connections...\n";
634 ($addr = accept (NS, S)) or die "accept: $!";
635 select (NS); $| = 1; select (STDOUT); # Piping hot!
636
637 ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
638 @inetaddr = unpack('C4',$client_ip);
639 print "$af connection from " .
640 join ('.', @inetaddr) . ":$client_port\n";
641
642 # We now have a network connection, lets fire up SSLeay...
643
644 $ssl = Net::SSLeay::new($ctx) or die_now("SSL_new ($ssl): $!");
645 Net::SSLeay::set_fd($ssl, fileno(NS));
646
647 $err = Net::SSLeay::accept($ssl) and die_if_ssl_error('ssl accept');
648 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
649
650 # Connected. Exchange some data.
651
652 $got = Net::SSLeay::read($ssl); # Returns undef on fail
653 die_if_ssl_error("ssl read");
654 print "Got `$got' (" . length ($got) . " chars)\n";
655
656 Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
657 die_if_ssl_error("ssl write");
658
659 Net::SSLeay::free ($ssl); # Tear down connection
660 close NS;
661 }
662
663 Yet another echo server. This one runs from "/etc/inetd.conf" so it
664 avoids all the socket code overhead. Only caveat is opening an rsa key
665 file - it had better be without any encryption or else it will not know
666 where to ask for the password. Note how "STDIN" and "STDOUT" are wired
667 to SSL.
668
669 #!/usr/local/bin/perl
670 # /etc/inetd.conf
671 # ssltst stream tcp nowait root /path/to/server.pl server.pl
672 # /etc/services
673 # ssltst 1234/tcp
674
675 use Net::SSLeay qw(die_now die_if_ssl_error);
676 Net::SSLeay::load_error_strings();
677 Net::SSLeay::SSLeay_add_ssl_algorithms();
678 Net::SSLeay::randomize();
679
680 chdir '/key/dir' or die "chdir: $!";
681 $| = 1; # Piping hot!
682 open LOG, ">>/dev/console" or die "Can't open log file $!";
683 select LOG; print "server.pl started\n";
684
685 $ctx = Net::SSLeay::CTX_new() or die_now "CTX_new ($ctx) ($!)";
686 $ssl = Net::SSLeay::new($ctx) or die_now "new ($ssl) ($!)";
687 Net::SSLeay::set_options($ssl, &Net::SSLeay::OP_ALL)
688 and die_if_ssl_error("ssl set options");
689
690 # We get already open network connection from inetd, now we just
691 # need to attach SSLeay to STDIN and STDOUT
692 Net::SSLeay::set_rfd($ssl, fileno(STDIN));
693 Net::SSLeay::set_wfd($ssl, fileno(STDOUT));
694
695 Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
696 Net::SSLeay::FILETYPE_PEM);
697 die_if_ssl_error("private key");
698 Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
699 Net::SSLeay::FILETYPE_PEM);
700 die_if_ssl_error("certificate");
701
702 Net::SSLeay::accept($ssl) and die_if_ssl_err("ssl accept: $!");
703 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
704
705 $got = Net::SSLeay::read($ssl);
706 die_if_ssl_error("ssl read");
707 print "Got `$got' (" . length ($got) . " chars)\n";
708
709 Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";
710 die_if_ssl_error("ssl write");
711
712 Net::SSLeay::free ($ssl); # Tear down the connection
713 Net::SSLeay::CTX_free ($ctx);
714 close LOG;
715
716 There are also a number of example/test programs in the examples
717 directory:
718
719 sslecho.pl - A simple server, not unlike the one above
720 minicli.pl - Implements a client using low level SSLeay routines
721 sslcat.pl - Demonstrates using high level sslcat utility function
722 get_page.pl - Is a utility for getting html pages from secure servers
723 callback.pl - Demonstrates certificate verification and callback usage
724 stdio_bulk.pl - Does SSL over Unix pipes
725 ssl-inetd-serv.pl - SSL server that can be invoked from inetd.conf
726 httpd-proxy-snif.pl - Utility that allows you to see how a browser
727 sends https request to given server and what reply
728 it gets back (very educative :-)
729 makecert.pl - Creates a self signed cert (does not use this module)
730
732 "Net::SSLeay::read()" uses an internal buffer of 32KB, thus no single
733 read will return more. In practice one read returns much less, usually
734 as much as fits in one network packet. To work around this, you should
735 use a loop like this:
736
737 $reply = '';
738 while ($got = Net::SSLeay::read($ssl)) {
739 last if print_errs('SSL_read');
740 $reply .= $got;
741 }
742
743 Although there is no built-in limit in "Net::SSLeay::write()", the
744 network packet size limitation applies here as well, thus use:
745
746 $written = 0;
747
748 while ($written < length($message)) {
749 $written += Net::SSLeay::write($ssl, substr($message, $written));
750 last if print_errs('SSL_write');
751 }
752
753 Or alternatively you can just use the following convenience functions:
754
755 Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
756 $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
757
759 Autoloader emits a
760
761 Argument "xxx" isn't numeric in entersub at blib/lib/Net/SSLeay.pm'
762
763 warning if die_if_ssl_error is made autoloadable. If you figure out
764 why, drop me a line.
765
766 Callback set using "SSL_set_verify()" does not appear to work. This may
767 well be an openssl problem (e.g. see "ssl/ssl_lib.c" line 1029). Try
768 using "SSL_CTX_set_verify()" instead and do not be surprised if even
769 this stops working in future versions.
770
771 Callback and certificate verification stuff is generally too little
772 tested.
773
774 Random numbers are not initialized randomly enough, especially if you
775 do not have "/dev/random" and/or "/dev/urandom" (such as in Solaris
776 platforms - but I've been suggested that cryptorand daemon from the
777 SUNski package solves this). In this case you should investigate third
778 party software that can emulate these devices, e.g. by way of a named
779 pipe to some program.
780
781 Another gotcha with random number initialization is randomness
782 depletion. This phenomenon, which has been extensively discussed in
783 OpenSSL, Apache-SSL, and Apache-mod_ssl forums, can cause your script
784 to block if you use "/dev/random" or to operate insecurely if you use
785 "/dev/urandom". What happens is that when too much randomness is drawn
786 from the operating system's randomness pool then randomness can
787 temporarily be unavailable. "/dev/random" solves this problem by
788 waiting until enough randomness can be gathered - and this can take a
789 long time since blocking reduces activity in the machine and less
790 activity provides less random events: a vicious circle. "/dev/urandom"
791 solves this dilemma more pragmatically by simply returning predictable
792 "random" numbers. Some" /dev/urandom" emulation software however
793 actually seems to implement "/dev/random" semantics. Caveat emptor.
794
795 I've been pointed to two such daemons by Mik Firestone
796 <mik@@speed.stdio._com> who has used them on Solaris 8:
797
798 1. Entropy Gathering Daemon (EGD) at
799 <http://www.lothar.com/tech/crypto/>
800
801 2. Pseudo-random number generating daemon (PRNGD) at
802 <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
803
804 If you are using the low level API functions to communicate with other
805 SSL implementations, you would do well to call
806
807 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
808 and die_if_ssl_error("ssl ctx set options");
809
810 to cope with some well know bugs in some other SSL implementations. The
811 high level API functions always set all known compatibility options.
812
813 Sometimes "sslcat()" (and the high level HTTPS functions that build on
814 it) is too fast in signaling the EOF to legacy HTTPS servers. This
815 causes the server to return empty page. To work around this problem you
816 can set the global variable
817
818 $Net::SSLeay::slowly = 1; # Add sleep so broken servers can keep up
819
820 HTTP/1.1 is not supported. Specifically this module does not know to
821 issue or serve multiple http requests per connection. This is a serious
822 shortcoming, but using the SSL session cache on your server helps to
823 alleviate the CPU load somewhat.
824
825 As of version 1.09 many newer OpenSSL auxiliary functions were added
826 (from "REM_AUTOMATICALLY_GENERATED_1_09" onwards in "SSLeay.xs").
827 Unfortunately I have not had any opportunity to test these. Some of
828 them are trivial enough that I believe they "just work", but others
829 have rather complex interfaces with function pointers and all. In these
830 cases you should proceed wit great caution.
831
832 This module defaults to using OpenSSL automatic protocol negotiation
833 code for automatically detecting the version of the SSL protocol that
834 the other end talks. With most web servers this works just fine, but
835 once in a while I get complaints from people that the module does not
836 work with some web servers. Usually this can be solved by explicitly
837 setting the protocol version, e.g.
838
839 $Net::SSLeay::ssl_version = 2; # Insist on SSLv2
840 $Net::SSLeay::ssl_version = 3; # Insist on SSLv3
841 $Net::SSLeay::ssl_version = 10; # Insist on TLSv1
842
843 Although the autonegotiation is nice to have, the SSL standards do not
844 formally specify any such mechanism. Most of the world has accepted the
845 SSLeay/OpenSSL way of doing it as the de facto standard. But for the
846 few that think differently, you have to explicitly speak the correct
847 version. This is not really a bug, but rather a deficiency in the
848 standards. If a site refuses to respond or sends back some nonsensical
849 error codes (at the SSL handshake level), try this option before
850 mailing me.
851
852 The high level API returns the certificate of the peer, thus allowing
853 one to check what certificate was supplied. However, you will only be
854 able to check the certificate after the fact, i.e. you already sent
855 your form data by the time you find out that you did not trust them,
856 oops.
857
858 So, while being able to know the certificate after the fact is surely
859 useful, the security minded would still choose to do the connection and
860 certificate verification first and only then exchange data with the
861 site. Currently none of the high level API functions do this, thus you
862 would have to program it using the low level API. A good place to start
863 is to see how the "Net::SSLeay::http_cat()" function is implemented.
864
865 The high level API functions use a global file handle "SSLCAT_S"
866 internally. This really should not be a problem because there is no way
867 to interleave the high level API functions, unless you use threads (but
868 threads are not very well supported in perl anyway (as of version
869 5.6.1). However, you may run into problems if you call undocumented
870 internal functions in an interleaved fashion.
871
873 Random number generator not seeded!!!
874 (W) This warning indicates that "randomize()" was not able to read
875 "/dev/random" or "/dev/urandom", possibly because your system does
876 not have them or they are differently named. You can still use SSL,
877 but the encryption will not be as strong.
878
879 open_tcp_connection: destination host not found:`server' (port 123)
880 ($!)
881 Name lookup for host named "server" failed.
882
883 open_tcp_connection: failed `server', 123 ($!)
884 The name was resolved, but establising the TCP connection failed.
885
886 msg 123: 1 - error:140770F8:SSL routines:SSL23_GET_SERVER_HELLO:unknown
887 proto
888 SSLeay error string. The first number (123) is the PID, the second
889 number (1) indicates the position of the error message in SSLeay
890 error stack. You often see a pile of these messages as errors
891 cascade.
892
893 msg 123: 1 - error:02001002::lib(2) :func(1) :reason(2)
894 The same as above, but you didn't call load_error_strings() so
895 SSLeay couldn't verbosely explain the error. You can still find out
896 what it means with this command:
897
898 /usr/local/ssl/bin/ssleay errstr 02001002
899
900 Password is being asked for private key
901 This is normal behaviour if your private key is encrypted. Either
902 you have to supply the password or you have to use an unencrypted
903 private key. Scan OpenSSL.org for the FAQ that explains how to do
904 this (or just study examples/makecert.pl which is used during "make
905 test" to do just that).
906
908 Please report any bugs or feature requests to "bug-Net-SSLeay at
909 rt.cpan.org", or through the web interface at
910 <http://rt.cpan.org/Public/Dist/Display.html?Name=Net-SSLeay>. I will
911 be notified, and then you'll automatically be notified of progress on
912 your bug as I make changes.
913
914 Subversion access to the latest source code etc can be obtained at
915 <http://alioth.debian.org/projects/net-ssleay>
916
917 The developer mailing list (for people interested in contributing to
918 the source code) can be found at
919 <http://lists.alioth.debian.org/mailman/listinfo/net-ssleay-devel>
920
921 You can find documentation for this module with the "perldoc" command.
922
923 perldoc Net::SSLeay
924
925 You can also look for information at:
926
927 · AnnoCPAN: Annotated CPAN documentation
928
929 <http://annocpan.org/dist/Net-SSLeay>
930
931 · CPAN Ratings
932
933 <http://cpanratings.perl.org/d/Net-SSLeay>
934
935 · Search CPAN
936
937 <http://search.cpan.org/dist/Net-SSLeay>
938
939 Commercial support for Net::SSLeay may be obtained from
940
941 Symlabs (netssleay@symlabs.com)
942 Tel: +351-214.222.630
943 Fax: +351-214.222.637
944
946 Maintained by Mike McCauley and Florian Ragwitz since November 2005
947
948 Originally written by Sampo KellomA~Xki <sampo@symlabs.com>
949
951 Copyright (c) 1996-2003 Sampo KellomA~Xki <sampo@symlabs.com>
952
953 Copyright (C) 2005-2006 Florian Ragwitz <rafl@debian.org>
954
955 Copyright (C) 2005 Mike McCauley <mikem@open.com.au>
956
957 All Rights Reserved.
958
959 Distribution and use of this module is under the same terms as the
960 OpenSSL package itself (i.e. free, but mandatory attribution; NO
961 WARRANTY). Please consult LICENSE file in the root of the OpenSSL
962 distribution.
963
964 While the source distribution of this perl module does not contain
965 Eric's or OpenSSL's code, if you use this module you will use OpenSSL
966 library. Please give Eric and OpenSSL team credit (as required by their
967 licenses).
968
969 And remember, you, and nobody else but you, are responsible for
970 auditing this module and OpenSSL library for security problems,
971 backdoors, and general suitability for your application.
972
974 Net::SSLeay::Handle - File handle interface
975 ./Net_SSLeay/examples - Example servers and a clients
976 <http://www.openssl.org/> - OpenSSL source, documentation, etc
977 openssl-users-request@openssl.org - General OpenSSL mailing list
978 <http://www.ietf.org/rfc/rfc2246.txt> - TLS 1.0 specification
979 <http://www.w3c.org> - HTTP specifications
980 <http://www.ietf.org/rfc/rfc2617.txt> - How to send password
981 <http://www.lothar.com/tech/crypto/> - Entropy Gathering Daemon (EGD)
982 <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
983 - pseudo-random number generating daemon (PRNGD)
984 perl(1)
985 perlref(1)
986 perllol(1)
987 perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod
988
989
990
991perl v5.10.1 2016-10-04 Net::SSLeay(3)