1SSLeay(3) User Contributed Perl Documentation 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, same API is offered for access‐
44 ing http servers, too), a sslcat() function for writing your own
45 clients, and finally access to the SSL api of SSLeay/OpenSSL package so
46 you can write servers or clients for more complicated applications.
47
48 For high level functions it is most convinient to import them to your
49 main namespace as indicated in the synopsis.
50
51 Case 1 demonstrates typical invocation of get_https() to fetch an HTML
52 page from secure server. The first argument provides host name or ip in
53 dotted decimal notation of the remote server to contact. Second argu‐
54 ment is the TCP port at the remote end (your own port is picked arbi‐
55 trarily from high numbered ports as usual for TCP). The third argument
56 is the URL of the page without the host name part. If in doubt consult
57 HTTP specifications at <http://www.w3c.org>
58
59 Case 2 demonstrates full fledged use of get_https(). As can be seen,
60 get_https() parses the response and response headers and returns them
61 as a list, which can be captured in a hash for later reference. Also a
62 fourth argument to get_https() is used to insert some additional head‐
63 ers in the request. make_headers() is a function that will convert a
64 list or hash to such headers. By default get_https() supplies Host
65 (make virtual hosting easy) and Accept (reportedly needed by IIS) head‐
66 ers.
67
68 Case 2b demonstrates how to get password protected page. Refer to HTTP
69 protocol specifications for further details (e.g. RFC2617).
70
71 Case 3 invokes post_https() to submit a HTML/CGI form to secure server.
72 First four arguments are equal to get_https() (note that empty string
73 ('') is passed as header argument). The fifth argument is the contents
74 of the form formatted according to CGI specification. In this case the
75 helper function make_https() is used to do the formatting, but you
76 could pass any string. The post_https() automatically adds Content-Type
77 and Content-Length headers to the request.
78
79 Case 4 shows the fundamental sslcat() function (inspired in spirit by
80 netcat utility :-). Its your swiss army knife that allows you to easily
81 contact servers, send some data, and then get the response. You are
82 responsible for formatting the data and parsing the response - sslcat()
83 is just a transport.
84
85 Case 5 is a full invocation of sslcat() which allows return of errors
86 as well as the server (peer) certificate.
87
88 The $trace global variable can be used to control the verbosity of high
89 level functions. Level 0 guarantees silence, level 1 (the default) only
90 emits error messages.
91
92 Alternate versions of the API
93
94 The above mentioned functions actually return the response headers as a
95 list, which only gets converted to hash upon assignment (this assign‐
96 ment looses information if the same header occurs twice, as may be the
97 case with cookies). There are also other variants of the functions that
98 return unprocessed headers and that return a reference to a hash.
99
100 ($page, $response, @headers) = get_https('www.bacus.pt', 443, '/');
101 for ($i = 0; $i < $#headers; $i+=2) {
102 print "$headers[$i] = " . $headers[$i+1] . "\n";
103 }
104
105 ($page, $response, $headers, $server_cert)
106 = get_https3('www.bacus.pt', 443, '/');
107 print "$headers\n";
108
109 ($page, $response, %headers_ref, $server_cert)
110 = get_https4('www.bacus.pt', 443, '/');
111 for $k (sort keys %{headers_ref}) {
112 for $v (@{$headers_ref{$k}}) {
113 print "$k = $v\n";
114 }
115 }
116
117 All of the above code fragments accomplish the same thing: display all
118 values of all headers. The API functions ending in "3" return the head‐
119 ers simply as a scalar string and it is up to the application to split
120 them up. The functions ending in "4" return a reference to hash of
121 arrays (see perlref and perllol manual pages if you are not familiar
122 with complex perl data structures). To access single value of such
123 header hash you would do something like
124
125 print $headers_ref{COOKIE}[0];
126
127 The variants 3 and 4 also allow you to discover the server certificate
128 in case you would like to store or display it, e.g.
129
130 ($p, $resp, $hdrs, $server_cert) = get_https3('www.bacus.pt', 443, '/');
131 if (!defined($server_cert) ⎪⎪ ($server_cert == 0)) {
132 warn "Subject Name: undefined, Issuer Name: undefined";
133 } else {
134 warn 'Subject Name: '
135 . Net::SSLeay::X509_NAME_oneline(
136 Net::SSLeay::X509_get_subject_name($server_cert))
137 . 'Issuer Name: '
138 . Net::SSLeay::X509_NAME_oneline(
139 Net::SSLeay::X509_get_issuer_name($server_cert));
140 }
141
142 Beware that this method only allows after the fact verification of the
143 certificate: by the time get_https3() has returned the https request
144 has already been sent to the server, whether you decide to tryst it or
145 not. To do the verification correctly you must either employ the
146 OpenSSL certificate verification framework or use the lower level API
147 to first connect and verify the certificate and only then send the http
148 data. See implementation of ds_https3() for guidance on how to do this.
149
150 Using client certificates
151
152 Secure web communications are encrypted using symmetric crypto keys
153 exchanged using encryption based on the certificate of the server.
154 Therefore in all SSL connections the server must have a certificate.
155 This serves both to authenticate the server to the clients and to per‐
156 form the key exchange.
157
158 Sometimes it is necessary to authenticate the client as well. Two
159 options are available: http basic authentication and client side cer‐
160 tificate. The basic authentication over https is actually quite safe
161 because https guarantees that the password will not travel in clear.
162 Never-the-less, problems like easily guessable passwords remain. The
163 client certificate method involves authentication of the client at SSL
164 level using a certificate. For this to work, both the client and the
165 server will have certificates (which typically are different) and pri‐
166 vate keys.
167
168 The API functions outlined above accept additional arguments that allow
169 one to supply the client side certificate and key files. The format of
170 these files is the same as used for server certificates and the caveat
171 about encrypting private key applies.
172
173 ($page, $result, %headers) = # 2c
174 = get_https('www.bacus.pt', 443, '/protected.html',
175 make_headers(Authorization =>
176 'Basic ' . MIME::Base64::encode("$user:$pass",'')),
177 '', $mime_type6, $path_to_crt7, $path_to_key8);
178
179 ($page, $response, %reply_headers)
180 = post_https('www.bacus.pt', 443, '/foo.cgi', # 3b
181 make_headers('Authorization' =>
182 'Basic ' . MIME::Base64::encode("$user:$pass",'')),
183 make_form(OK => '1', name => 'Sampo'),
184 $mime_type6, $path_to_crt7, $path_to_key8);
185
186 Case 2c demonstrates getting password protected page that also requires
187 client certificate, i.e. it is possible to use both authentication
188 methods simultaneously.
189
190 Case 3b is full blown post to secure server that requires both password
191 authentication and client certificate, just like in case 2c.
192
193 Note: Client will not send a certificate unless the server requests
194 one. This is typically achieved by setting verify mode to VERIFY_PEER
195 on the server:
196
197 Net::SSLeay::set_verify(ssl, Net::SSLeay::VERIFY_PEER, 0);
198
199 See perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod for full descrip‐
200 tion.
201
202 Working through Web proxy
203
204 Net::SSLeay can use a web proxy to make its connections. You need to
205 first set the proxy host and port using set_proxy() and then just use
206 the normal API functions, e.g:
207
208 Net::SSLeay::set_proxy('gateway.myorg.com', 8080);
209 ($page) = get_https('www.bacus.pt', 443, '/');
210
211 If your proxy requires authentication, you can supply username and
212 password as well
213
214 Net::SSLeay::set_proxy('gateway.myorg.com', 8080, 'joe', 'salainen');
215 ($page, $result, %headers) =
216 = get_https('www.bacus.pt', 443, '/protected.html',
217 make_headers(Authorization =>
218 'Basic ' . MIME::Base64::encode("susie:pass",''))
219 );
220
221 This example demonstrates case where we authenticate to the proxy as
222 "joe" and to the final web server as "susie". Proxy authentication
223 requires MIME::Base64 module to work.
224
225 Certificate verification and Certificate Revoocation Lists (CRLs)
226
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 previ‐
231 ously 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 issuer,
245 and then check for a revocation of the peer cerificate in all of them.
246 (You can also force it to look in a specific named CRL file., see
247 below). You can find out the hash of the issuer subject name in a CRL
248 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'); my $crl =
259 &Net::SSLeay::PEM_read_bio_X509_CRL($bio); if ($crl) {
260 &Net::SSLeay::X509_STORE_add_crl(&Net::SSLeay::CTX_get_cert_store($ssl,
261 $crl); } else {
262 error reading CRL.... }
263
264 Convenience routines
265
266 To be used with Low level API
267
268 Net::SSLeay::randomize($rn_seed_file,$additional_seed);
269 Net::SSLeay::set_cert_and_key($ctx, $cert_path, $key_path);
270 $cert = Net::SSLeay::dump_peer_certificate($ssl);
271 Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
272 $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
273
274 $got = Net::SSLeay::ssl_read_CRLF($ssl [, $max_length]);
275 $got = Net::SSLeay::ssl_read_until($ssl [, $delimit [, $max_length]]);
276 Net::SSLeay::ssl_write_CRLF($ssl, $message);
277
278 randomize() seeds the eay PRNG with /dev/urandom (see top of SSLeay.pm
279 for how to change or configure this) and optionally with user provided
280 data. It is very important to properly seed your random numbers, so do
281 not forget to call this. The high level API functions automatically
282 call randomize() so it is not needed with them. See also caveats.
283
284 set_cert_and_key() takes two file names as arguments and sets the cer‐
285 tificate and private key to those. This can be used to set either
286 cerver certificates or client certificates.
287
288 dump_peer_certificate() allows you to get plaintext description of the
289 certificate the peer (usually server) presented to us.
290
291 ssl_read_all() and ssl_write_all() provide true blocking semantics for
292 these operations (see limitation, below, for explanation). These are
293 much preferred to the low level API equivalents (which implement BSD
294 blocking semantics). The message argument to ssl_write_all() can be
295 reference. This is helpful to avoid unnecessary copy when writing some‐
296 thing big, e.g:
297
298 $data = 'A' x 1000000000;
299 Net::SSLeay::ssl_write_all($ssl, \$data) or die "ssl write failed";
300
301 ssl_read_CRLF() uses ssl_read_all() to read in a line terminated with a
302 carriage return followed by a linefeed (CRLF). The CRLF is included in
303 the returned scalar.
304
305 ssl_read_until() uses ssl_read_all() to read from the SSL input stream
306 until it encounters a programmer specified delimiter. If the delimiter
307 is undefined, $/ is used. If $/ is undefined, \n is used. One can
308 optionally set a maximum length of bytes to read from the SSL input
309 stream.
310
311 ssl_write_CRLF() writes $message and appends CRLF to the SSL output
312 stream.
313
314 Low level API
315
316 In addition to the high level functions outlined above, this module
317 contains straight forward access to SSL part of OpenSSL C api. Only the
318 SSL subpart of OpenSSL is implemented (if anyone wants to implement
319 other parts, feel free to submit patches).
320
321 See ssl.h header from OpenSSL C distribution for list of low lever
322 SSLeay functions to call (to check if some function has been imple‐
323 mented see directly in SSLeay.xs). The module strips SSLeay names of
324 the initial "SSL_", generally you should use Net::SSLeay:: in place.
325 For example:
326
327 In C:
328
329 #include <ssl.h>
330
331 err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
332 &your_call_back_here);
333
334 In perl:
335
336 use Net::SSLeay;
337
338 $err = Net::SSLeay::set_verify ($ssl,
339 &Net::SSLeay::VERIFY_CLIENT_ONCE,
340 \&your_call_back_here);
341
342 If the function does not start by SSL_ you should use the full function
343 name, e.g.:
344
345 $err = &Net::SSLeay::ERR_get_error;
346
347 Following new functions behave in perlish way:
348
349 $got = Net::SSLeay::read($ssl);
350 # Performs SSL_read, but returns $got
351 # resized according to data received.
352 # Returns undef on failure.
353
354 Net::SSLeay::write($ssl, $foo) ⎪⎪ die;
355 # Performs SSL_write, but automatically
356 # figures out the size of $foo
357
358 In order to use the low level API you should start your programs with
359 the following encantation:
360
361 use Net::SSLeay qw(die_now die_if_ssl_error);
362 Net::SSLeay::load_error_strings();
363 Net::SSLeay::SSLeay_add_ssl_algorithms(); # Important!
364 Net::SSLeay::randomize();
365
366 die_now() and die_if_ssl_error() are used to conveniently print SSLeay
367 error stack when something goes wrong, thusly:
368
369 Net::SSLeay:connect($ssl) or die_now("Failed SSL connect ($!)");
370 Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
371
372 You can also use Net::SSLeay::print_errs() to dump the error stack
373 without exiting the program. As can be seen, your code becomes much
374 more readable if you import the error reporting functions to your main
375 name space.
376
377 I can not emphasize enough the need to check error returns. Use these
378 functions even in most simple programs, they will reduce debugging time
379 greatly. Do not ask questions in mailing list without having first
380 sprinkled these in your code.
381
382 Sockets
383
384 Perl uses file handles for all I/O. While SSLeay has quite flexible BIO
385 mechanism and perl has evolved PerlIO mechanism, this module still
386 sticks to using file descriptors. Thus to attach SSLeay to socket you
387 should use fileno() to extract the underlying file descriptor:
388
389 Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
390
391 You should also use "$⎪=1;" to eliminate STDIO buffering so you do not
392 get confused if you use perl I/O functions to manipulate your socket
393 handle.
394
395 If you need to select(2) on the socket, go right ahead, but be warned
396 that OpenSSL does some internal buffering so SSL_read does not always
397 return data even if socket selected for reading (just keep on selecting
398 and trying to read). Net::SSLeay.pm is no different from the C language
399 OpenSSL in this respect.
400
401 Callbacks
402
403 At this moment the implementation of verify_callback is crippeled in
404 the sense that at any given time there can be only one call back which
405 is shared by all SSL contexts, sessions and connections. This is due to
406 having to keep the reference to the perl call back in a static variable
407 so that the callback C glue can find it. To remove this restriction
408 would require either a more complex data structure (like a hash?) in
409 XSUB to map the call backs to their owners or, cleaner, adding a con‐
410 text pointer in the SSL structure. This context would then be passed to
411 the C callback, which in our case would be the glue to look up the
412 proper Perl function from the context and call it.
413
414 ---- inaccurate ---- The verify call back looks like this in C:
415
416 int (*callback)(int ok,X509 *subj_cert,X509 *issuer_cert,
417 int depth,int errorcode,char *arg,STACK *cert_chain)
418
419 The corresponding Perl function should be something like this:
420
421 sub verify {
422 my ($ok, $subj_cert, $issuer_cert, $depth, $errorcode,
423 $arg, $chain) = @_;
424 print "Verifying certificate...\n";
425 ...
426 return $ok;
427 }
428
429 It is used like this:
430
431 Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);
432
433 Callbacks for decrypting private keys are implemented, but have the
434 same limitation as the verify_callback implementation (one password
435 callback shared between all contexts.) You might use it something like
436 this:
437
438 Net::SSLeay::CTX_set_default_passwd_cb($ctx, sub { "top-secret" });
439 Net::SSLeay::CTX_use_PrivateKey_file($ctx, "key.pem",
440 Net::SSLeay::FILETYPE_PEM)
441 or die "Error reading private key";
442 Net::SSLeay::CTX_set_default_passwd_cb($ctx, undef);
443
444 No other callbacks are implemented. You do not need to use any callback
445 for simple (i.e. normal) cases where the SSLeay built-in verify mecha‐
446 nism satisfies your needs.
447
448 It is desirable to reset these callbacks to undef immediately after use
449 to prevent thread safety problems and crashes on exit that can occur if
450 different threads set different callbacks.
451
452 ---- end inaccurate ----
453
454 If you want to use callback stuff, see examples/callback.pl! Its the
455 only one I am able to make work reliably.
456
457 X509 and RAND stuff
458
459 This module largely lacks interface to the X509 and RAND routines, but
460 as I was lazy and needed them, the following kludges are implemented:
461
462 $x509_name = Net::SSLeay::X509_get_subject_name($x509_cert);
463 $x509_name = Net::SSLeay::X509_get_issuer_name($x509_cert);
464 print Net::SSLeay::X509_NAME_oneline($x509_name);
465 $text = Net::SSLeay::X509_NAME_get_text_by_NID($name, $nid);
466
467 Net::SSLeay::RAND_seed($buf); # Perlishly figures out buf size
468 Net::SSLeay::RAND_bytes($buf, $num);
469 Net::SSLeay::RAND_pseudo_bytes($buf, $num);
470 Net::SSLeay::RAND_add($buf, $num, $entropy);
471 Net::SSLeay::RAND_poll();
472 Net::SSLeay::RAND_status();
473 Net::SSLeay::RAND_cleanup();
474 Net::SSLeay::RAND_file_name($num);
475 Net::SSLeay::RAND_load_file($file_name, $how_many_bytes);
476 Net::SSLeay::RAND_write_file($file_name);
477 Net::SSLeay::RAND_egd($path);
478 Net::SSLeay::RAND_egd_bytes($path, $bytes);
479
480 Actually you should consider using the following helper functions:
481
482 print Net::SSLeay::dump_peer_certificate($ssl);
483 Net::SSLeay::randomize();
484
485 RSA interface
486
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
495 Some BIO functions are available:
496
497 Net::SSLeay::BIO_s_mem();
498 $bio = Net::SSLeay::BIO_new(BIO_s_mem())
499 $bio = Net::SSLeay::BIO_new_file($filename, $mode);
500 Net::SSLeay::BIO_free($bio)
501 $count = Net::SSLeay::BIO_write($data);
502 $data = Net::SSLeay::BIO_read($bio);
503 $data = Net::SSLeay::BIO_read($bio, $maxbytes);
504 $is_eof = Net::SSLeay::BIO_eof($bio);
505 $count = Net::SSLeay::BIO_pending($bio);
506 $count = Net::SSLeay::BIO_wpending ($bio);
507
508 Low level API
509
510 Some very low level API functions are available:
511 $client_random = &Net::SSLeay::get_client_random($ssl);
512 $server_random = &Net::SSLeay::get_server_random($ssl);
513 $session = &Net::SSLeay::get_session($ssl);
514 $master_key = &Net::SSLeay::SESSION_get_master_key($session);
515
516 HTTP (without S) API
517
518 Over the years it has become clear that it would be convenient to use
519 the light weight flavour API of Net::SSLeay also for normal http (see
520 LWP for heavy weight object oriented approach). In fact it would be
521 nice to be able to flip https on and off on the fly. Thus regular http
522 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 first argument a flag
555 which indicated whether SSL is used or not.
556
558 One very good example is to look at the implementation of sslcat() in
559 the SSLeay.pm file.
560
561 Following is a simple SSLeay client (with too little error checking :-(
562
563 #!/usr/local/bin/perl
564 use Socket;
565 use Net::SSLeay qw(die_now die_if_ssl_error) ;
566 Net::SSLeay::load_error_strings();
567 Net::SSLeay::SSLeay_add_ssl_algorithms();
568 Net::SSLeay::randomize();
569
570 ($dest_serv, $port, $msg) = @ARGV; # Read command line
571 $port = getservbyname ($port, 'tcp') unless $port =~ /^\d+$/;
572 $dest_ip = gethostbyname ($dest_serv);
573 $dest_serv_params = sockaddr_in($port, $dest_ip);
574
575 socket (S, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
576 connect (S, $dest_serv_params) or die "connect: $!";
577 select (S); $⎪ = 1; select (STDOUT); # Eliminate STDIO buffering
578
579 # The network connection is now open, lets fire up SSL
580
581 $ctx = Net::SSLeay::CTX_new() or die_now("Failed to create SSL_CTX $!");
582 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
583 and die_if_ssl_error("ssl ctx set options");
584 $ssl = Net::SSLeay::new($ctx) or die_now("Failed to create SSL $!");
585 Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
586 $res = Net::SSLeay::connect($ssl) and die_if_ssl_error("ssl connect");
587 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
588
589 # Exchange data
590
591 $res = Net::SSLeay::write($ssl, $msg); # Perl knows how long $msg is
592 die_if_ssl_error("ssl write");
593 CORE::shutdown S, 1; # Half close --> No more output, sends EOF to server
594 $got = Net::SSLeay::read($ssl); # Perl returns undef on failure
595 die_if_ssl_error("ssl read");
596 print $got;
597
598 Net::SSLeay::free ($ssl); # Tear down connection
599 Net::SSLeay::CTX_free ($ctx);
600 close S;
601
602 Following is a simple SSLeay echo server (non forking):
603
604 #!/usr/local/bin/perl -w
605 use Socket;
606 use Net::SSLeay qw(die_now die_if_ssl_error);
607 Net::SSLeay::load_error_strings();
608 Net::SSLeay::SSLeay_add_ssl_algorithms();
609 Net::SSLeay::randomize();
610
611 $our_ip = "\0\0\0\0"; # Bind to all interfaces
612 $port = 1235;
613 $sockaddr_template = 'S n a4 x8';
614 $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);
615
616 socket (S, &AF_INET, &SOCK_STREAM, 0) or die "socket: $!";
617 bind (S, $our_serv_params) or die "bind: $!";
618 listen (S, 5) or die "listen: $!";
619 $ctx = Net::SSLeay::CTX_new () or die_now("CTX_new ($ctx): $!");
620 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
621 and die_if_ssl_error("ssl ctx set options");
622
623 # Following will ask password unless private key is not encrypted
624 Net::SSLeay::CTX_use_RSAPrivateKey_file ($ctx, 'plain-rsa.pem',
625 &Net::SSLeay::FILETYPE_PEM);
626 die_if_ssl_error("private key");
627 Net::SSLeay::CTX_use_certificate_file ($ctx, 'plain-cert.pem',
628 &Net::SSLeay::FILETYPE_PEM);
629 die_if_ssl_error("certificate");
630
631 while (1) {
632 print "Accepting connections...\n";
633 ($addr = accept (NS, S)) or die "accept: $!";
634 select (NS); $⎪ = 1; select (STDOUT); # Piping hot!
635
636 ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
637 @inetaddr = unpack('C4',$client_ip);
638 print "$af connection from " .
639 join ('.', @inetaddr) . ":$client_port\n";
640
641 # We now have a network connection, lets fire up SSLeay...
642
643 $ssl = Net::SSLeay::new($ctx) or die_now("SSL_new ($ssl): $!");
644 Net::SSLeay::set_fd($ssl, fileno(NS));
645
646 $err = Net::SSLeay::accept($ssl) and die_if_ssl_error('ssl accept');
647 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
648
649 # Connected. Exchange some data.
650
651 $got = Net::SSLeay::read($ssl); # Returns undef on fail
652 die_if_ssl_error("ssl read");
653 print "Got `$got' (" . length ($got) . " chars)\n";
654
655 Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
656 die_if_ssl_error("ssl write");
657
658 Net::SSLeay::free ($ssl); # Tear down connection
659 close NS;
660 }
661
662 Yet another echo server. This one runs from /etc/inetd.conf so it
663 avoids all the socket code overhead. Only caveat is opening rsa key
664 file - it had better be without any encryption or else it will not know
665 where to ask for the password. Note how STDIN and STDOUT are wired to
666 SSL.
667
668 #!/usr/local/bin/perl
669 # /etc/inetd.conf
670 # ssltst stream tcp nowait root /path/to/server.pl server.pl
671 # /etc/services
672 # ssltst 1234/tcp
673
674 use Net::SSLeay qw(die_now die_if_ssl_error);
675 Net::SSLeay::load_error_strings();
676 Net::SSLeay::SSLeay_add_ssl_algorithms();
677 Net::SSLeay::randomize();
678
679 chdir '/key/dir' or die "chdir: $!";
680 $⎪ = 1; # Piping hot!
681 open LOG, ">>/dev/console" or die "Can't open log file $!";
682 select LOG; print "server.pl started\n";
683
684 $ctx = Net::SSLeay::CTX_new() or die_now "CTX_new ($ctx) ($!)";
685 $ssl = Net::SSLeay::new($ctx) or die_now "new ($ssl) ($!)";
686 Net::SSLeay::set_options($ssl, &Net::SSLeay::OP_ALL)
687 and die_if_ssl_error("ssl set options");
688
689 # We get already open network connection from inetd, now we just
690 # need to attach SSLeay to STDIN and STDOUT
691 Net::SSLeay::set_rfd($ssl, fileno(STDIN));
692 Net::SSLeay::set_wfd($ssl, fileno(STDOUT));
693
694 Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
695 &Net::SSLeay::FILETYPE_PEM);
696 die_if_ssl_error("private key");
697 Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
698 &Net::SSLeay::FILETYPE_PEM);
699 die_if_ssl_error("certificate");
700
701 Net::SSLeay::accept($ssl) and die_if_ssl_err("ssl accept: $!");
702 print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";
703
704 $got = Net::SSLeay::read($ssl);
705 die_if_ssl_error("ssl read");
706 print "Got `$got' (" . length ($got) . " chars)\n";
707
708 Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";
709 die_if_ssl_error("ssl write");
710
711 Net::SSLeay::free ($ssl); # Tear down the connection
712 Net::SSLeay::CTX_free ($ctx);
713 close LOG;
714
715 There are also a number of example/test programs in the examples direc‐
716 tory:
717
718 sslecho.pl - A simple server, not unlike the one above
719 minicli.pl - Implements a client using low level SSLeay routines
720 sslcat.pl - Demonstrates using high level sslcat utility function
721 get_page.pl - Is a utility for getting html pages from secure servers
722 callback.pl - Demonstrates certificate verification and callback usage
723 stdio_bulk.pl - Does SSL over Unix pipes
724 ssl-inetd-serv.pl - SSL server that can be invoked from inetd.conf
725 httpd-proxy-snif.pl - Utility that allows you to see how a browser
726 sends https request to given server and what reply
727 it gets back (very educative :-)
728 makecert.pl - Creates a self signed cert (does not use this module)
729
731 Net::SSLeay::read uses internal buffer of 32KB, thus no single read
732 will return more. In practice one read returns much less, usually as
733 much as fits in one network packet. To work around this, you should use
734 a loop like this:
735
736 $reply = '';
737 while ($got = Net::SSLeay::read($ssl)) {
738 last if print_errs('SSL_read');
739 $reply .= $got;
740 }
741
742 Although there is no built-in limit in Net::SSLeay::write, the network
743 packet size limitation applies here as well, thus use:
744
745 $written = 0;
746
747 while ($written < length($message)) {
748 $written += Net::SSLeay::write($ssl, substr($message, $written));
749 last if print_errs('SSL_write');
750 }
751
752 Or alternatively you can just use the following convinence functions:
753
754 Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
755 $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";
756
758 Autoloader emits
759
760 Argument "xxx" isn't numeric in entersub at blib/lib/Net/SSLeay.pm'
761
762 warning if die_if_ssl_error is made autoloadable. If you figure out
763 why, drop me a line.
764
765 Callback set using SSL_set_verify() does not appear to work. This may
766 well be eay problem (e.g. see ssl/ssl_lib.c line 1029). Try using
767 SSL_CTX_set_verify() instead and do not be surprised if even this stops
768 working in future versions.
769
770 Callback and certificate verification stuff is generally too little
771 tested.
772
773 Random numbers are not initialized randomly enough, especially if you
774 do not have /dev/random and/or /dev/urandom (such as in Solaris plat‐
775 forms - but I've been suggested that cryptorand daemon from SUNski
776 package solves this). In this case you should investigate third party
777 software that can emulate these devices, e.g. by way of a named pipe to
778 some program.
779
780 Another gotcha with random number initialization is randomness deple‐
781 tion. This phenomenon, which has been extensively discussed in OpenSSL,
782 Apache-SSL, and Apache-mod_ssl forums, can cause your script to block
783 if you use /dev/random or to operate insecurely if you use /dev/uran‐
784 dom. What happens is that when too much randomness is drawn from the
785 operating system's randomness pool then randomness can temporarily be
786 unavailable. /dev/random solves this problem by waiting until enough
787 randomness can be gathered - and this can take a long time since block‐
788 ing reduces activity in the machine and less activity provides less
789 random events: a vicious circle. /dev/urandom solves this dilemma more
790 pragmatically by simply returning predictable "random" numbers. Some
791 /dev/urandom emulation software however actually seems to implement
792 /dev/random semantics. Caveat emptor.
793
794 I've been pointed to two such daemons by Mik Firestone
795 <mik@@speed.stdio._com> who has used them on Solaris 8
796
797 1. Entropy Gathering Daemon (EGD) at http://www.lothar.com/tech/crypto/
798 2. Pseudo-random number generating daemon (PRNGD) at
799 http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html
800
801 If you are using the low level API functions to communicate with other
802 SSL implementations, you would do well to call
803
804 Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
805 and die_if_ssl_error("ssl ctx set options");
806
807 to cope with some well know bugs in some other SSL implementations. The
808 high level API functions always set all known compatibility options.
809
810 Sometimes sslcat (and the high level https functions that build on it)
811 is too fast in signaling the EOF to legacy https servers. This causes
812 the server to return empty page. To work around this problem you can
813 set global variable
814
815 $Net::SSLeay::slowly = 1; # Add sleep so broken servers can keep up
816
817 http/1.1 is not supported. Specifically this module does not know to
818 issue or serve multiple http requests per connection. This is a serious
819 short coming, but using SSL session cache on your server helps to alle‐
820 viate the CPU load somewhat.
821
822 As of version 1.09 many newer OpenSSL auxiliary functions were added
823 (from REM_AUTOMATICALLY_GENERATED_1_09 onwards in SSLeay.xs). Unfortu‐
824 nately I have not had any opportunity to test these. Some of them are
825 trivial enough that I believe they "just work", but others have rather
826 complex interfaces with function pointers and all. In these cases you
827 should proceed wit great caution.
828
829 This module defaults to using OpenSSL automatic protocol negotiation
830 code for automatically detecting the version of the SSL protocol that
831 the other end talks. With most web servers this works just fine, but
832 once in a while I get complaints from people that the module does not
833 work with some web servers. Usually this can be solved by explicitly
834 setting the protocol version, e.g.
835
836 $Net::SSLeay::ssl_version = 2; # Insist on SSLv2
837 $Net::SSLeay::ssl_version = 3; # Insist on SSLv3
838 $Net::SSLeay::ssl_version = 10; # Insist on TLSv1
839
840 Although the autonegotiation is nice to have, the SSL standards do not
841 formally specify any such mechanism. Most of the world has accepted the
842 SSLeay/OpenSSL way of doing it as the de facto standard. But for the
843 few that think differently, you have to explicitly speak the correct
844 version. This is not really a bug, but rather a deficiency in the stan‐
845 dards. If a site refuses to respond or sends back some nonsensical
846 error codes (at SSL handshake level), try this option before mailing
847 me.
848
849 The high level API returns the certificate of the peer, thus allowing
850 one to check what certificate was supplied. However, you will only be
851 able to check the certificate after the fact, i.e. you already sent
852 your form data by the time you find out that you did not trust them,
853 oops.
854
855 So, while being able to know the certificate after the fact is surely
856 useful, the security minded would still choose to do the connection and
857 certificate verification first and only after that exchange data with
858 the site. Currently none of the high level API functions do this, thus
859 you would have to program it using the low level API. A good place to
860 start is to see how Net::SSLeay::http_cat() function is implemented.
861
862 The high level API functions use a global file handle SSLCAT_S inter‐
863 nally. This really should not be a problem because there is no way to
864 interleave the high level API functions, unless you use threads (but
865 threads are not very well supported in perl anyway (as of version
866 5.6.1). However, you may run into problems if you call undocumented
867 internal functions in an interleaved fashion.
868
870 "Random number generator not seeded!!!"
871 This warning indicates that randomize() was not able to read
872 /dev/random or /dev/urandom, possibly because your system does not
873 have them or they are differently named. You can still use SSL, but
874 the encryption will not be as strong.
875
876 "open_tcp_connection: destination host not found:`server' (port 123)
877 ($!)"
878 Name lookup for host named `server' failed.
879
880 "open_tcp_connection: failed `server', 123 ($!)"
881 The name was resolved, but establising the TCP connection failed.
882
883 "msg 123: 1 - error:140770F8:SSL rou‐
884 tines:SSL23_GET_SERVER_HELLO:unknown proto"
885 SSLeay error string. First (123) number is PID, second number (1)
886 indicates
887 the position of the error message in SSLeay error stack. You often
888 see
889 a pile of these messages as errors cascade.
890
891 "msg 123: 1 - error:02001002::lib(2) :func(1) :reason(2)"
892 The same as above, but you didn't call load_error_strings() so SSLeay
893 couldn't verbosely explain the error. You can still find out what it
894 means with this command:
895
896 /usr/local/ssl/bin/ssleay errstr 02001002
897
898 Password is being asked for private key
899 This is normal behaviour if your private key is encrypted. Either
900 you have to supply the password or you have to use unencrypted
901 private key. Scan OpenSSL.org for the FAQ that explains how to
902 do this (or just study examples/makecert.pl which is used
903 during `make test' to do just that).
904
906 Bug reports, patch submission, feature requests, subversion access to
907 the latest source code etc can be obtained at
908 http://alioth.debian.org/projects/net-ssleay
909
910 The developer mailing list (for people interested in contributin to the
911 source code) can be found at http://lists.alioth.debian.org/mail‐
912 man/listinfo/net-ssleay-devel
913
914 Commercial support for Net::SSLeay may be obtained from
915
916 Symlabs (netssleay@symlabs.com)
917 Tel: +351-214.222.630
918 Fax: +351-214.222.637
919
921 This man page documents version 1.24, released on 18.8.2003.
922
923 There are currently two perl modules for using OpenSSL C library:
924 Net::SSLeay (maintaned by me) and SSLeay (maintained by OpenSSL team).
925 This module is the Net::SSLeay variant.
926
927 At the time of making this release, Eric's module was still quite
928 sketchy and could not be used for real work, thus I felt motivated to
929 make this maintenance release. This module is not planned to evolve to
930 contain any further functionality, i.e. I will concentrate on just mak‐
931 ing a simple SSL connection over TCP socket. Presumably Eric's own mod‐
932 ule will offer full SSLeay API one day.
933
934 This module uses OpenSSL-0.9.6c. It does not work with any earlier ver‐
935 sion and there is no guarantee that it will work with later versions
936 either, though as long as C API does not change, it should. This module
937 requires perl5.005, or 5.6.0 (or better?) though I believe it would
938 build with any perl5.002 or newer.
939
941 Originally written by Sampo Kellomäki <sampo@symlabs.com> Maintained by
942 Mike McCauley and Florian Ragwitz since November 2005
943
945 Copyright (c) 1996-2003 Sampo Kellomäki <sampo@symlabs.com> Copyright
946 (C) 2005 Florian Ragwitz <rafl@debian.org> Copyright (C) 2005 Mike
947 McCauley <mikem@open.com.au> All Rights Reserved.
948
949 Distribution and use of this module is under the same terms as the
950 OpenSSL package itself (i.e. free, but mandatory attribution; NO WAR‐
951 RANTY). Please consult LICENSE file in the root of the OpenSSL distri‐
952 bution.
953
954 While the source distribution of this perl module does not contain
955 Eric's or OpenSSL's code, if you use this module you will use OpenSSL
956 library. Please give Eric and OpenSSL team credit (as required by their
957 licenses).
958
959 And remember, you, and nobody else but you, are responsible for audit‐
960 ing this module and OpenSSL library for security problems, backdoors,
961 and general suitability for your application.
962
964 Net::SSLeay::Handle - File handle interface
965 ./Net_SSLeay/examples - Example servers and a clients
966 <http://symlabs.com/Net_SSLeay/index.html> - Net::SSLeay.pm home
967 <http://symlabs.com/Net_SSLeay/smime.html> - Another module using OpenSSL
968 <http://www.openssl.org/> - OpenSSL source, documentation, etc
969 openssl-users-request@openssl.org - General OpenSSL mailing list
970 <http://home.netscape.com/newsref/std/SSL.html> - SSL Draft specification
971 <http://www.w3c.org> - HTTP specifications
972 <http://www.ietf.org/rfc/rfc2617.txt> - How to send password
973 <http://www.lothar.com/tech/crypto/> - Entropy Gathering Daemon (EGD)
974 <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
975 - pseudo-random number generating daemon (PRNGD)
976 perl(1)
977 perlref(1)
978 perllol(1)
979 perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod
980
981
982
983perl v5.8.8 2006-07-17 SSLeay(3)