Mike McCauley > Net-SSLeay-1.45 > Net::SSLeay

Download:
Net-SSLeay-1.45.tar.gz

Dependencies

Annotate this POD

Related Modules

Crypt::SSLeay
LWP::UserAgent
HTTP::Request
XML::Parser
Data::Dumper
LWP::Simple
HTTP::Daemon
IO::Socket
Net::SSL
DBD::mysql
more...
By perlmonks.org

CPAN RT

Open  1
View/Report Bugs
Module Version: 1.45   Source   Latest Release: Net-SSLeay-1.66

NAME ^

Net::SSLeay - Perl extension for using OpenSSL

SYNOPSIS ^

  use Net::SSLeay qw(get_https post_https sslcat make_headers make_form);

  ($page) = get_https('www.bacus.pt', 443, '/');                 # Case 1

  ($page, $response, %reply_headers)
         = get_https('www.bacus.pt', 443, '/',                   # Case 2
                make_headers(User-Agent => 'Cryptozilla/5.0b1',
                             Referer    => 'https://www.bacus.pt'
                ));

  ($page, $result, %headers) =                                   # Case 2b
         = get_https('www.bacus.pt', 443, '/protected.html',
              make_headers(Authorization =>
                           'Basic ' . MIME::Base64::encode("$user:$pass",''))
              );

  ($page, $response, %reply_headers)
         = post_https('www.bacus.pt', 443, '/foo.cgi', '',       # Case 3
                make_form(OK   => '1',
                          name => 'Sampo'
                ));

  $reply = sslcat($host, $port, $request);                       # Case 4

  ($reply, $err, $server_cert) = sslcat($host, $port, $request); # Case 5

  $Net::SSLeay::trace = 2;  # 0=no debugging, 1=ciphers, 2=trace, 3=dump data

  Net::SSLeay::initialize(); # Initialize ssl library once

DESCRIPTION ^

Net::SSLeay module contains perl bindings to openssl (http://www.openssl.org) library.

COMPATIBILITY NOTE: Net::SSLeay cannot be built with pre-0.9.3 openssl. It is strongly recommended to use at least 0.9.7 (as older versions are not tested during development). Some low level API functions may be available with certain openssl versions.

Net::SSLeay module basically comprise of:

There is also a related module called Net::SSLeay::Handle included in this distribution that you might want to use instead. It has its own pod documentation.

High level functions for accessing web servers

This module offers some high level convenience functions for accessing web pages on SSL servers (for symmetry, the same API is offered for accessing http servers, too), an sslcat() function for writing your own clients, and finally access to the SSL api of the SSLeay/OpenSSL package so you can write servers or clients for more complicated applications.

For high level functions it is most convenient to import them into your main namespace as indicated in the synopsis.

Basic set of functions

Case 1 (in SYNOPSIS) demonstrates the typical invocation of get_https() to fetch an HTML page from secure server. The first argument provides the hostname or IP in dotted decimal notation of the remote server to contact. The second argument is the TCP port at the remote end (your own port is picked arbitrarily from high numbered ports as usual for TCP). The third argument is the URL of the page without the host name part. If in doubt consult the HTTP specifications at http://www.w3c.org.

Case 2 (in SYNOPSIS) demonstrates full fledged use of get_https(). As can be seen, get_https() parses the response and response headers and returns them as a list, which can be captured in a hash for later reference. Also a fourth argument to get_https() is used to insert some additional headers in the request. make_headers() is a function that will convert a list or hash to such headers. By default get_https() supplies Host (to make virtual hosting easy) and Accept (reportedly needed by IIS) headers.

Case 2b (in SYNOPSIS) demonstrates how to get a password protected page. Refer to the HTTP protocol specifications for further details (e.g. RFC-2617).

Case 3 (in SYNOPSIS) invokes post_https() to submit a HTML/CGI form to a secure server. The first four arguments are equal to get_https() (note that the empty string ('') is passed as header argument). The fifth argument is the contents of the form formatted according to CGI specification. In this case the helper function make_https() is used to do the formatting, but you could pass any string. post_https() automatically adds Content-Type and Content-Length headers to the request.

Case 4 (in SYNOPSIS) shows the fundamental sslcat() function (inspired in spirit by the netcat utility :-). It's your swiss army knife that allows you to easily contact servers, send some data, and then get the response. You are responsible for formatting the data and parsing the response - sslcat() is just a transport.

Case 5 (in SYNOPSIS) is a full invocation of sslcat() which allows the return of errors as well as the server (peer) certificate.

The $trace global variable can be used to control the verbosity of the high level functions. Level 0 guarantees silence, level 1 (the default) only emits error messages.

Alternate versions of high-level API

The above mentioned functions actually return the response headers as a list, which only gets converted to hash upon assignment (this assignment looses information if the same header occurs twice, as may be the case with cookies). There are also other variants of the functions that return unprocessed headers and that return a reference to a hash.

  ($page, $response, @headers) = get_https('www.bacus.pt', 443, '/');
  for ($i = 0; $i < $#headers; $i+=2) {
      print "$headers[$i] = " . $headers[$i+1] . "\n";
  }

  ($page, $response, $headers, $server_cert)
    = get_https3('www.bacus.pt', 443, '/');
  print "$headers\n";

  ($page, $response, %headers_ref, $server_cert)
    = get_https4('www.bacus.pt', 443, '/');
  for $k (sort keys %{headers_ref}) {
      for $v (@{$headers_ref{$k}}) {
          print "$k = $v\n";
      }
  }

All of the above code fragments accomplish the same thing: display all values of all headers. The API functions ending in "3" return the headers simply as a scalar string and it is up to the application to split them up. The functions ending in "4" return a reference to a hash of arrays (see perlref and perllol if you are not familiar with complex perl data structures). To access a single value of such a header hash you would do something like

  print $headers_ref{COOKIE}[0];

Variants 3 and 4 also allow you to discover the server certificate in case you would like to store or display it, e.g.

  ($p, $resp, $hdrs, $server_cert) = get_https3('www.bacus.pt', 443, '/');
  if (!defined($server_cert) || ($server_cert == 0)) {
      warn "Subject Name: undefined, Issuer  Name: undefined";
  } else {
      warn 'Subject Name: '
          . Net::SSLeay::X509_NAME_oneline(
                 Net::SSLeay::X509_get_subject_name($server_cert))
              . 'Issuer  Name: '
                  . Net::SSLeay::X509_NAME_oneline(
                         Net::SSLeay::X509_get_issuer_name($server_cert));
  }

Beware that this method only allows after the fact verification of the certificate: by the time get_https3() has returned the https request has already been sent to the server, whether you decide to trust it or not. To do the verification correctly you must either employ the OpenSSL certificate verification framework or use the lower level API to first connect and verify the certificate and only then send the http data. See the implementation of ds_https3() for guidance on how to do this.

Using client certificates

Secure web communications are encrypted using symmetric crypto keys exchanged using encryption based on the certificate of the server. Therefore in all SSL connections the server must have a certificate. This serves both to authenticate the server to the clients and to perform the key exchange.

Sometimes it is necessary to authenticate the client as well. Two options are available: HTTP basic authentication and a client side certificate. The basic authentication over HTTPS is actually quite safe because HTTPS guarantees that the password will not travel in the clear. Never-the-less, problems like easily guessable passwords remain. The client certificate method involves authentication of the client at the SSL level using a certificate. For this to work, both the client and the server have certificates (which typically are different) and private keys.

The API functions outlined above accept additional arguments that allow one to supply the client side certificate and key files. The format of these files is the same as used for server certificates and the caveat about encrypting private keys applies.

  ($page, $result, %headers) =                                   # 2c
         = get_https('www.bacus.pt', 443, '/protected.html',
              make_headers(Authorization =>
                           'Basic ' . MIME::Base64::encode("$user:$pass",'')),
              '', $mime_type6, $path_to_crt7, $path_to_key8);

  ($page, $response, %reply_headers)
         = post_https('www.bacus.pt', 443, '/foo.cgi',           # 3b
              make_headers('Authorization' =>
                           'Basic ' . MIME::Base64::encode("$user:$pass",'')),
              make_form(OK   => '1', name => 'Sampo'),
              $mime_type6, $path_to_crt7, $path_to_key8);

Case 2c (in SYNOPSIS) demonstrates getting a password protected page that also requires a client certificate, i.e. it is possible to use both authentication methods simultaneously.

Case 3b (in SYNOPSIS) is a full blown POST to a secure server that requires both password authentication and a client certificate, just like in case 2c.

Note: The client will not send a certificate unless the server requests one. This is typically achieved by setting the verify mode to VERIFY_PEER on the server:

  Net::SSLeay::set_verify(ssl, Net::SSLeay::VERIFY_PEER, 0);

See perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod for a full description.

Working through a web proxy

Net::SSLeay can use a web proxy to make its connections. You need to first set the proxy host and port using set_proxy() and then just use the normal API functions, e.g:

  Net::SSLeay::set_proxy('gateway.myorg.com', 8080);
  ($page) = get_https('www.bacus.pt', 443, '/');

If your proxy requires authentication, you can supply a username and password as well

  Net::SSLeay::set_proxy('gateway.myorg.com', 8080, 'joe', 'salainen');
  ($page, $result, %headers) =
         = get_https('www.bacus.pt', 443, '/protected.html',
              make_headers(Authorization =>
                           'Basic ' . MIME::Base64::encode("susie:pass",''))
              );

This example demonstrates the case where we authenticate to the proxy as "joe" and to the final web server as "susie". Proxy authentication requires the MIME::Base64 module to work.

HTTP (without S) API

Over the years it has become clear that it would be convenient to use the light-weight flavour API of Net::SSLeay for normal HTTP as well (see LWP for the heavy-weight object-oriented approach). In fact it would be nice to be able to flip https on and off on the fly. Thus regular HTTP support was evolved.

  use Net::SSLeay qw(get_http post_http tcpcat
                      get_httpx post_httpx tcpxcat
                      make_headers make_form);

  ($page, $result, %headers)
         = get_http('www.bacus.pt', 443, '/protected.html',
              make_headers(Authorization =>
                           'Basic ' . MIME::Base64::encode("$user:$pass",''))
              );

  ($page, $response, %reply_headers)
         = post_http('www.bacus.pt', 443, '/foo.cgi', '',
                make_form(OK   => '1',
                          name => 'Sampo'
                ));

  ($reply, $err) = tcpcat($host, $port, $request);

  ($page, $result, %headers)
         = get_httpx($usessl, 'www.bacus.pt', 443, '/protected.html',
              make_headers(Authorization =>
                           'Basic ' . MIME::Base64::encode("$user:$pass",''))
              );

  ($page, $response, %reply_headers)
         = post_httpx($usessl, 'www.bacus.pt', 443, '/foo.cgi', '',
                make_form(OK   => '1',  name => 'Sampo' ));

  ($reply, $err, $server_cert) = tcpxcat($usessl, $host, $port, $request);

As can be seen, the "x" family of APIs takes as the first argument a flag which indicates whether SSL is used or not.

Certificate verification and Certificate Revocation Lists (CRLs)

OpenSSL supports the ability to verify peer certificates. It can also optionally check the peer certificate against a Certificate Revocation List (CRL) from the certificates issuer. A CRL is a file, created by the certificate issuer that lists all the certificates that it previously signed, but which it now revokes. CRLs are in PEM format.

You can enable Net::SSLeay CRL checking like this:

            &Net::SSLeay::X509_STORE_set_flags
                (&Net::SSLeay::CTX_get_cert_store($ssl), 
                 &Net::SSLeay::X509_V_FLAG_CRL_CHECK); 

After setting this flag, if OpenSSL checks a peer's certificate, then it will attempt to find a CRL for the issuer. It does this by looking for a specially named file in the search directory specified by CTX_load_verify_locations. CRL files are named with the hash of the issuer's subject name, followed by .r0, .r1 etc. For example ab1331b2.r0, ab1331b2.r1. It will read all the .r files for the issuer, and then check for a revocation of the peer certificate in all of them. (You can also force it to look in a specific named CRL file., see below). You can find out the hash of the issuer subject name in a CRL with

        openssl crl -in crl.pem -hash -noout

If the peer certificate does not pass the revocation list, or if no CRL is found, then the handshaking fails with an error.

You can also force OpenSSL to look for CRLs in one or more arbitrarily named files.

    my $bio = Net::SSLeay::BIO_new_file($crlfilename, 'r');
    my $crl = Net::SSLeay::PEM_read_bio_X509_CRL($bio);
    if ($crl) {
        Net::SSLeay::X509_STORE_add_crl(Net::SSLeay::CTX_get_cert_store($ssl, $crl);
    } else {
        error reading CRL....
    }

Using Net::SSLeay in multi-threaded applications

IMPORTANT: versions 1.42 or earlier are not thread-safe!

Net::SSLeay module implements all necessary stuff to be ready for multi-threaded environment. The implementation fully follows thread safety related requirements of openssl library(see http://www.openssl.org/docs/crypto/threads.html).

If you are about to use Net::SSLeay (or any other module based on Net::SSLeay) in multi-threaded perl application it is recommended to follow this best-practice:

Initialization

Load and initialize Net::SSLeay module in the main thread:

    use threads;
    use Net::SSLeay;
    
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();
    
    sub do_master_job {
      #... call whatever from Net::SSLeay
    }
    
    sub do_worker_job {
      #... call whatever from Net::SSLeay
    }
    
    #start threads
    my $master  = threads->new(\&do_master_job, 'param1', 'param2');
    my @workers = threads->new(\&do_worker_job, 'arg1', 'arg2') for (1..10);
    
    #waiting for all threads to finish
    $_->join() for (threads->list);

NOTE: Openssl's int SSL_library_init(void) function (which is also aliased as SSLeay_add_ssl_algorithms, OpenSSL_add_ssl_algorithms and add_ssl_algorithms) is not re-entrant and multiple calls can cause a crash in threaded application. Net::SSLeay implements flags preventing repeated calls to this function, therefore even multiple initialization via Net::SSLeay::SSLeay_add_ssl_algorithms() should work without trouble.

Using callbacks

Do not use callbacks across threads (the module blocks cross-thread callback operations and throws a warning). Allways do the callback setup, callback use and callback destruction within the same thread.

Using openssl elements

All openssl elements (X509, SSL_CTX, ...) can be directly passed between threads.

    use threads;
    use Net::SSLeay;
    
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();
    
    sub do_job {
      my $context = shift;
      Net::SSLeay::CTX_set_default_passwd_cb($context, sub { "secret" });
      #...
    }
    
    my $c = Net::SSLeay::CTX_new();
    threads->create(\&do_job, $c);

Or:

    use threads;
    use Net::SSLeay;
    
    my $context; #does not need to be 'shared'
    
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();
    
    sub do_job {
      Net::SSLeay::CTX_set_default_passwd_cb($context, sub { "secret" });
      #...
    }
    
    $context = Net::SSLeay::CTX_new();
    threads->create(\&do_job);

Using other perl modules based on Net::SSLeay

It should be fine to use any other module based on Net::SSLeay (like IO::Socket::SSL) in multi-threaded applications. It is generally recommended to do any global initialization of such a module in the main thread before calling threads->new(..) or threads->create(..) but it might differ module by module.

To be play safe you can load and init Net::SSLeay explicitely in the main thread:

    use Net::SSLeay;        
    use Other::SSLeay::Based::Module;
    
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();Net::SSLeay::initialize();
    Net::SSLeay::initialize();

Or even safer:

    use Net::SSLeay;        
    use Other::SSLeay::Based::Module;
    
    BEGIN {
      Net::SSLeay::load_error_strings();
      Net::SSLeay::SSLeay_add_ssl_algorithms();
      Net::SSLeay::randomize();Net::SSLeay::initialize();
    }

Combining Net::SSLeay with other modules linked with openssl

BEWARE: This might be a big trouble! This is not guaranteed be thread-safe!

There are many other (XS) modules linked directly to openssl library (like Crypt::SSLeay).

As it is expected that also "another" module will call SSLeay_add_ssl_algorithms at some point we have again a trouble with multiple openssl initialization by Net::SSLeay and "another" module.

As you can expect Net::SSLeay is not able to avoid multiple initialization of openssl library called by "another" module, thus you have to handle this on your own (in some cases it might not be possible at all to avoid this).

Threading with get_https and friends

The convenience functions get_https, post_https etc all initialize the SSL library by calling Net::SSLeay::initialize which does the conventional library initialization:

    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();

Net::SSLeay::initialize initializes the SSL library at most once. You can override the Net::SSLeay::initialize function if you desire some other type of initialization behaviour by get_https and friends. You can call Net::SSLeay::initialize from your own code if you desire this conventional library initialization.

Convenience routines

To be used with Low level API

    Net::SSLeay::randomize($rn_seed_file,$additional_seed);
    Net::SSLeay::set_cert_and_key($ctx, $cert_path, $key_path);
    $cert = Net::SSLeay::dump_peer_certificate($ssl);
    Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
    $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";

    $got = Net::SSLeay::ssl_read_CRLF($ssl [, $max_length]);
    $got = Net::SSLeay::ssl_read_until($ssl [, $delimit [, $max_length]]);
    Net::SSLeay::ssl_write_CRLF($ssl, $message);

Initialization

In order to use the low level API you should start your programs with the following incantation:

        use Net::SSLeay qw(die_now die_if_ssl_error);
        Net::SSLeay::load_error_strings();
        Net::SSLeay::SSLeay_add_ssl_algorithms();    # Important!
        Net::SSLeay::ENGINE_load_builtin_engines();  # If you want built-in engines
        Net::SSLeay::ENGINE_register_all_complete(); # If you want built-in engines
        Net::SSLeay::randomize();

Error handling functions

I can not emphasize the need to check for error enough. Use these functions even in the most simple programs, they will reduce debugging time greatly. Do not ask questions on the mailing list without having first sprinkled these in your code.

Sockets

Perl uses file handles for all I/O. While SSLeay has a quite flexible BIO mechanism and perl has an evolved PerlIO mechanism, this module still sticks to using file descriptors. Thus to attach SSLeay to a socket you should use fileno() to extract the underlying file descriptor:

    Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno

You should also set $| to 1 to eliminate STDIO buffering so you do not get confused if you use perl I/O functions to manipulate your socket handle.

If you need to select(2) on the socket, go right ahead, but be warned that OpenSSL does some internal buffering so SSL_read does not always return data even if the socket selected for reading (just keep on selecting and trying to read). Net::SSLeay is no different from the C language OpenSSL in this respect.

Callbacks

You can establish a per-context verify callback function something like this:

        sub verify {
            my ($ok, $x509_store_ctx) = @_;
            print "Verifying certificate...\n";
                ...
            return $ok;
        }

It is used like this:

        Net::SSLeay::set_verify ($ssl, Net::SSLeay::VERIFY_PEER, \&verify);

Per-context callbacks for decrypting private keys are implemented.

        Net::SSLeay::CTX_set_default_passwd_cb($ctx, sub { "top-secret" });
        Net::SSLeay::CTX_use_PrivateKey_file($ctx, "key.pem",
                                             Net::SSLeay::FILETYPE_PEM)
            or die "Error reading private key";
        Net::SSLeay::CTX_set_default_passwd_cb($ctx, undef);

If Hello Extensions are supported by your OpenSSL, a session secret callback can be set up to be called when a session secret is set by openssl.

Establish it like this: Net::SSLeay::set_session_secret_cb($ssl, \&session_secret_cb, $somedata);

It will be called like this:

    sub session_secret_cb
    {
        my ($secret, \@cipherlist, \$preferredcipher, $somedata) = @_;
    }

No other callbacks are implemented. You do not need to use any callback for simple (i.e. normal) cases where the SSLeay built-in verify mechanism satisfies your needs.

It is required to reset these callbacks to undef immediately after use to prevent memory leaks, thread safety problems and crashes on exit that can occur if different threads set different callbacks.

If you want to use callback stuff, see examples/callback.pl! It's the only one I am able to make work reliably.

Low level API

In addition to the high level functions outlined above, this module contains straight-forward access to CRYPTO and SSL parts of OpenSSL C API.

See the *.h headers from OpenSSL C distribution for a list of low level SSLeay functions to call (check SSLeay.xs to see if some function has been implemented). The module strips the initial "SSL_" off of the SSLeay names. Generally you should use Net::SSLeay:: in its place.

Note that some functions are prefixed with "P_" - these are very close to the original API however contain some kind of a wrapper making its interface more perl friendly.

For example:

In C:

        #include <ssl.h>

        err = SSL_set_verify (ssl, SSL_VERIFY_CLIENT_ONCE,
                                   &your_call_back_here);

In Perl:

        use Net::SSLeay;

        $err = Net::SSLeay::set_verify ($ssl,
                                        Net::SSLeay::VERIFY_CLIENT_ONCE,
                                        \&your_call_back_here);

If the function does not start with SSL_ you should use the full function name, e.g.:

        $err = Net::SSLeay::ERR_get_error;

The following new functions behave in perlish way:

        $got = Net::SSLeay::read($ssl);
                                    # Performs SSL_read, but returns $got
                                    # resized according to data received.
                                    # Returns undef on failure.

        Net::SSLeay::write($ssl, $foo) || die;
                                    # Performs SSL_write, but automatically
                                    # figures out the size of $foo

Low level API: Version related functions

Low level API: Initialization related functions

Low level API: ERR_* and SSL_alert_* related functions

NOTE: Please note that SSL_alert_* function have "SSL_" part stripped from their names.

Low level API: SSL_METHOD_* related functions

Low level API: ENGINE_* related functions

Low level API: EVP_PKEY_* related functions

Low level API: PEM_* related functions

Check openssl doc http://www.openssl.org/docs/crypto/pem.html

Low level API: SESSION_* related functions

Low level API: SSL_CTX_* related functions

NOTE: Please note that the function described in this chapter have "SSL_" part stripped from their original openssl names.

Low level API: SSL_* related functions

NOTE: Please note that the function described in this chapter have "SSL_" part stripped from their original openssl names.

Low level API: RAND_* related functions

Check openssl doc related to RAND stuff http://www.openssl.org/docs/crypto/rand.html

Low level API: OBJ_* related functions

Low level API: ASN1_TIME_* related functions

Low level API: X509_* related functions

Low level API: Digest related functions

Low level API: CIPHER_* related functions

Low level API: RSA_* related functions

Low level API: BIO_* related functions

Low level API: Other functions

Constants

There are many openssl constants available in Net::SSLeay. You can use them like this:

 use Net::SSLeay;
 print &Net::SSLeay::NID_commonName;
 #or
 print Net::SSLeay::NID_commonName();

Or you can import them and use:

 use Net::SSLeay qw/NID_commonName/;
 print &NID_commonName;
 #or
 print NID_commonName();
 #or
 print NID_commonName;

The list of all available constant names:

 AT_MD5_WITH_RSA_ENCRYPTION         NID_id_ad                                 OP_SSLREF2_REUSE_CERT_TYPE_BUG
 CB_ACCEPT_EXIT                     NID_id_ce                                 OP_TLS_D5_BUG
 CB_ACCEPT_LOOP                     NID_id_kp                                 OP_TLS_ROLLBACK_BUG
 CB_CONNECT_EXIT                    NID_id_pbkdf2                             PE_BAD_CERTIFICATE
 CB_CONNECT_LOOP                    NID_id_pe                                 PE_NO_CERTIFICATE
 CK_DES_192_EDE3_CBC_WITH_MD5       NID_id_pkix                               PE_NO_CIPHER
 CK_DES_192_EDE3_CBC_WITH_SHA       NID_id_qt_cps                             PE_UNSUPPORTED_CERTIFICATE_TYPE
 CK_DES_64_CBC_WITH_MD5             NID_id_qt_unotice                         READING
 CK_DES_64_CBC_WITH_SHA             NID_idea_cbc                              RECEIVED_SHUTDOWN
 CK_DES_64_CFB64_WITH_MD5_1         NID_idea_cfb64                            RSA_3
 CK_IDEA_128_CBC_WITH_MD5           NID_idea_ecb                              RSA_F4
 CK_NULL                            NID_idea_ofb64                            RWERR_BAD_MAC_DECODE
 CK_NULL_WITH_MD5                   NID_info_access                           RWERR_BAD_WRITE_RETRY
 CK_RC2_128_CBC_EXPORT40_WITH_MD5   NID_initials                              RWERR_INTERNAL_ERROR
 CK_RC2_128_CBC_WITH_MD5            NID_invalidity_date                       R_BAD_AUTHENTICATION_TYPE
 CK_RC4_128_EXPORT40_WITH_MD5       NID_issuer_alt_name                       R_BAD_CHECKSUM
 CK_RC4_128_WITH_MD5                NID_keyBag                                R_BAD_MAC_DECODE
 CLIENT_VERSION                     NID_key_usage                             R_BAD_RESPONSE_ARGUMENT
 CT_X509_CERTIFICATE                NID_localKeyID                            R_BAD_SSL_FILETYPE
 ERROR_NONE                         NID_localityName                          R_BAD_SSL_SESSION_ID_LENGTH
 ERROR_SSL                          NID_md2                                   R_BAD_STATE
 ERROR_SYSCALL                      NID_md2WithRSAEncryption                  R_BAD_WRITE_RETRY
 ERROR_WANT_CONNECT                 NID_md5                                   R_CHALLENGE_IS_DIFFERENT
 ERROR_WANT_READ                    NID_md5WithRSA                            R_CIPHER_CODE_TOO_LONG
 ERROR_WANT_WRITE                   NID_md5WithRSAEncryption                  R_CIPHER_TABLE_SRC_ERROR
 ERROR_WANT_X509_LOOKUP             NID_md5_sha1                              R_CONECTION_ID_IS_DIFFERENT
 ERROR_ZERO_RETURN                  NID_mdc2                                  R_INVALID_CHALLENGE_LENGTH
 FILETYPE_ASN1                      NID_mdc2WithRSA                           R_NO_CERTIFICATE_SET
 FILETYPE_PEM                       NID_ms_code_com                           R_NO_CERTIFICATE_SPECIFIED
 F_CLIENT_CERTIFICATE               NID_ms_code_ind                           R_NO_CIPHER_LIST
 F_CLIENT_HELLO                     NID_ms_ctl_sign                           R_NO_CIPHER_MATCH
 F_CLIENT_MASTER_KEY                NID_ms_efs                                R_NO_CIPHER_WE_TRUST
 F_D2I_SSL_SESSION                  NID_ms_ext_req                            R_NO_PRIVATEKEY
 F_GET_CLIENT_FINISHED              NID_ms_sgc                                R_NO_PUBLICKEY
 F_GET_CLIENT_HELLO                 NID_name                                  R_NO_READ_METHOD_SET
 F_GET_CLIENT_MASTER_KEY            NID_netscape                              R_NO_WRITE_METHOD_SET
 F_GET_SERVER_FINISHED              NID_netscape_base_url                     R_NULL_SSL_CTX
 F_GET_SERVER_HELLO                 NID_netscape_ca_policy_url                R_PEER_DID_NOT_RETURN_A_CERTIFICATE
 F_GET_SERVER_VERIFY                NID_netscape_ca_revocation_url            R_PEER_ERROR
 F_I2D_SSL_SESSION                  NID_netscape_cert_extension               R_PEER_ERROR_CERTIFICATE
 F_READ_N                           NID_netscape_cert_sequence                R_PEER_ERROR_NO_CIPHER
 F_REQUEST_CERTIFICATE              NID_netscape_cert_type                    R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
 F_SERVER_HELLO                     NID_netscape_comment                      R_PERR_ERROR_NO_CERTIFICATE
 F_SSL_ACCEPT                       NID_netscape_data_type                    R_PUBLIC_KEY_ENCRYPT_ERROR
 F_SSL_CERT_NEW                     NID_netscape_renewal_url                  R_PUBLIC_KEY_IS_NOT_RSA
 F_SSL_CONNECT                      NID_netscape_revocation_url               R_PUBLIC_KEY_NO_RSA
 F_SSL_ENC_DES_CBC_INIT             NID_netscape_ssl_server_name              R_READ_WRONG_PACKET_TYPE
 F_SSL_ENC_DES_CFB_INIT             NID_ns_sgc                                R_REVERSE_KEY_ARG_LENGTH_IS_WRONG
 F_SSL_ENC_DES_EDE3_CBC_INIT        NID_organizationName                      R_REVERSE_MASTER_KEY_LENGTH_IS_WRONG
 F_SSL_ENC_IDEA_CBC_INIT            NID_organizationalUnitName                R_REVERSE_SSL_SESSION_ID_LENGTH_IS_WRONG
 F_SSL_ENC_NULL_INIT                NID_pbeWithMD2AndDES_CBC                  R_SHORT_READ
 F_SSL_ENC_RC2_CBC_INIT             NID_pbeWithMD2AndRC2_CBC                  R_SSL_SESSION_ID_IS_DIFFERENT
 F_SSL_ENC_RC4_INIT                 NID_pbeWithMD5AndCast5_CBC                R_UNABLE_TO_EXTRACT_PUBLIC_KEY
 F_SSL_GET_NEW_SESSION              NID_pbeWithMD5AndDES_CBC                  R_UNDEFINED_INIT_STATE
 F_SSL_MAKE_CIPHER_LIST             NID_pbeWithMD5AndRC2_CBC                  R_UNKNOWN_REMOTE_ERROR_TYPE
 F_SSL_NEW                          NID_pbeWithSHA1AndDES_CBC                 R_UNKNOWN_STATE
 F_SSL_READ                         NID_pbeWithSHA1AndRC2_CBC                 R_UNSUPORTED_CIPHER
 F_SSL_RSA_PRIVATE_DECRYPT          NID_pbe_WithSHA1And128BitRC2_CBC          R_WRONG_PUBLIC_KEY_TYPE
 F_SSL_RSA_PUBLIC_ENCRYPT           NID_pbe_WithSHA1And128BitRC4              R_X509_LIB
 F_SSL_SESSION_NEW                  NID_pbe_WithSHA1And2_Key_TripleDES_CBC    SENT_SHUTDOWN
 F_SSL_SESSION_PRINT_FP             NID_pbe_WithSHA1And3_Key_TripleDES_CBC    SERVER_VERSION
 F_SSL_SET_CERTIFICATE              NID_pbe_WithSHA1And40BitRC2_CBC           SESSION_ASN1_VERSION
 F_SSL_SET_FD                       NID_pbe_WithSHA1And40BitRC4               ST_ACCEPT
 F_SSL_SET_RFD                      NID_pbes2                                 ST_BEFORE
 F_SSL_SET_WFD                      NID_pbmac1                                ST_CLIENT_START_ENCRYPTION
 F_SSL_STARTUP                      NID_pkcs                                  ST_CONNECT
 F_SSL_USE_CERTIFICATE              NID_pkcs3                                 ST_GET_CLIENT_FINISHED_A
 F_SSL_USE_CERTIFICATE_ASN1         NID_pkcs7                                 ST_GET_CLIENT_FINISHED_B
 F_SSL_USE_CERTIFICATE_FILE         NID_pkcs7_data                            ST_GET_CLIENT_HELLO_A
 F_SSL_USE_PRIVATEKEY               NID_pkcs7_digest                          ST_GET_CLIENT_HELLO_B
 F_SSL_USE_PRIVATEKEY_ASN1          NID_pkcs7_encrypted                       ST_GET_CLIENT_MASTER_KEY_A
 F_SSL_USE_PRIVATEKEY_FILE          NID_pkcs7_enveloped                       ST_GET_CLIENT_MASTER_KEY_B
 F_SSL_USE_RSAPRIVATEKEY            NID_pkcs7_signed                          ST_GET_SERVER_FINISHED_A
 F_SSL_USE_RSAPRIVATEKEY_ASN1       NID_pkcs7_signedAndEnveloped              ST_GET_SERVER_FINISHED_B
 F_SSL_USE_RSAPRIVATEKEY_FILE       NID_pkcs8ShroudedKeyBag                   ST_GET_SERVER_HELLO_A
 F_WRITE_PENDING                    NID_pkcs9                                 ST_GET_SERVER_HELLO_B
 GEN_DIRNAME                        NID_pkcs9_challengePassword               ST_GET_SERVER_VERIFY_A
 GEN_DNS                            NID_pkcs9_contentType                     ST_GET_SERVER_VERIFY_B
 GEN_EDIPARTY                       NID_pkcs9_countersignature                ST_INIT
 GEN_EMAIL                          NID_pkcs9_emailAddress                    ST_OK
 GEN_IPADD                          NID_pkcs9_extCertAttributes               ST_READ_BODY
 GEN_OTHERNAME                      NID_pkcs9_messageDigest                   ST_READ_HEADER
 GEN_RID                            NID_pkcs9_signingTime                     ST_SEND_CLIENT_CERTIFICATE_A
 GEN_URI                            NID_pkcs9_unstructuredAddress             ST_SEND_CLIENT_CERTIFICATE_B
 GEN_X400                           NID_pkcs9_unstructuredName                ST_SEND_CLIENT_CERTIFICATE_C
 MAX_MASTER_KEY_LENGTH_IN_BITS      NID_private_key_usage_period              ST_SEND_CLIENT_CERTIFICATE_D
 MAX_RECORD_LENGTH_2_BYTE_HEADER    NID_rc2_40_cbc                            ST_SEND_CLIENT_FINISHED_A
 MAX_RECORD_LENGTH_3_BYTE_HEADER    NID_rc2_64_cbc                            ST_SEND_CLIENT_FINISHED_B
 MAX_SSL_SESSION_ID_LENGTH_IN_BYTES NID_rc2_cbc                               ST_SEND_CLIENT_HELLO_A
 MIN_RSA_MODULUS_LENGTH_IN_BYTES    NID_rc2_cfb64                             ST_SEND_CLIENT_HELLO_B
 MT_CLIENT_CERTIFICATE              NID_rc2_ecb                               ST_SEND_CLIENT_MASTER_KEY_A
 MT_CLIENT_FINISHED                 NID_rc2_ofb64                             ST_SEND_CLIENT_MASTER_KEY_B
 MT_CLIENT_HELLO                    NID_rc4                                   ST_SEND_REQUEST_CERTIFICATE_A
 MT_CLIENT_MASTER_KEY               NID_rc4_40                                ST_SEND_REQUEST_CERTIFICATE_B
 MT_ERROR                           NID_rc5_cbc                               ST_SEND_REQUEST_CERTIFICATE_C
 MT_REQUEST_CERTIFICATE             NID_rc5_cfb64                             ST_SEND_REQUEST_CERTIFICATE_D
 MT_SERVER_FINISHED                 NID_rc5_ecb                               ST_SEND_SERVER_FINISHED_A
 MT_SERVER_HELLO                    NID_rc5_ofb64                             ST_SEND_SERVER_FINISHED_B
 MT_SERVER_VERIFY                   NID_ripemd160                             ST_SEND_SERVER_HELLO_A
 NID_OCSP_sign                      NID_ripemd160WithRSA                      ST_SEND_SERVER_HELLO_B
 NID_SMIMECapabilities              NID_rle_compression                       ST_SEND_SERVER_VERIFY_A
 NID_X500                           NID_rsa                                   ST_SEND_SERVER_VERIFY_B
 NID_X509                           NID_rsaEncryption                         ST_SERVER_START_ENCRYPTION
 NID_ad_OCSP                        NID_rsadsi                                ST_X509_GET_CLIENT_CERTIFICATE
 NID_ad_ca_issuers                  NID_safeContentsBag                       ST_X509_GET_SERVER_CERTIFICATE
 NID_algorithm                      NID_sdsiCertificate                       TXT_DES_192_EDE3_CBC_WITH_MD5
 NID_authority_key_identifier       NID_secretBag                             TXT_DES_192_EDE3_CBC_WITH_SHA
 NID_basic_constraints              NID_serialNumber                          TXT_DES_64_CBC_WITH_MD5
 NID_bf_cbc                         NID_server_auth                           TXT_DES_64_CBC_WITH_SHA
 NID_bf_cfb64                       NID_sha                                   TXT_DES_64_CFB64_WITH_MD5_1
 NID_bf_ecb                         NID_sha1                                  TXT_IDEA_128_CBC_WITH_MD5
 NID_bf_ofb64                       NID_sha1WithRSA                           TXT_NULL
 NID_cast5_cbc                      NID_sha1WithRSAEncryption                 TXT_NULL_WITH_MD5
 NID_cast5_cfb64                    NID_shaWithRSAEncryption                  TXT_RC2_128_CBC_EXPORT40_WITH_MD5
 NID_cast5_ecb                      NID_stateOrProvinceName                   TXT_RC2_128_CBC_WITH_MD5
 NID_cast5_ofb64                    NID_subject_alt_name                      TXT_RC4_128_EXPORT40_WITH_MD5
 NID_certBag                        NID_subject_key_identifier                TXT_RC4_128_WITH_MD5
 NID_certificate_policies           NID_surname                               VERIFY_CLIENT_ONCE
 NID_client_auth                    NID_sxnet                                 VERIFY_FAIL_IF_NO_PEER_CERT
 NID_code_sign                      NID_time_stamp                            VERIFY_NONE
 NID_commonName                     NID_title                                 VERIFY_PEER
 NID_countryName                    NID_undef                                 WRITING
 NID_crlBag                         NID_uniqueIdentifier                      X509_LOOKUP
 NID_crl_distribution_points        NID_x509Certificate                       X509_PURPOSE_ANY
 NID_crl_number                     NID_x509Crl                               X509_PURPOSE_CRL_SIGN
 NID_crl_reason                     NID_zlib_compression                      X509_PURPOSE_NS_SSL_SERVER
 NID_delta_crl                      NOTHING                                   X509_PURPOSE_OCSP_HELPER
 NID_des_cbc                        OPENSSL_VERSION_NUMBER                    X509_PURPOSE_SMIME_ENCRYPT
 NID_des_cfb64                      OP_ALL                                    X509_PURPOSE_SMIME_SIGN
 NID_des_ecb                        OP_CIPHER_SERVER_PREFERENCE               X509_PURPOSE_SSL_CLIENT
 NID_des_ede                        OP_COOKIE_EXCHANGE                        X509_PURPOSE_SSL_SERVER
 NID_des_ede3                       OP_DONT_INSERT_EMPTY_FRAGMENTS            X509_PURPOSE_TIMESTAMP_SIGN
 NID_des_ede3_cbc                   OP_EPHEMERAL_RSA                          X509_TRUST_COMPAT
 NID_des_ede3_cfb64                 OP_MICROSOFT_BIG_SSLV3_BUFFER             X509_TRUST_EMAIL
 NID_des_ede3_ofb64                 OP_MICROSOFT_SESS_ID_BUG                  X509_TRUST_OBJECT_SIGN
 NID_des_ede_cbc                    OP_MSIE_SSLV2_RSA_PADDING                 X509_TRUST_OCSP_REQUEST
 NID_des_ede_cfb64                  OP_NETSCAPE_CA_DN_BUG                     X509_TRUST_OCSP_SIGN
 NID_des_ede_ofb64                  OP_NETSCAPE_CA_DN_BUG                     X509_TRUST_SSL_CLIENT
 NID_des_ofb64                      OP_NETSCAPE_CHALLENGE_BUG                 X509_TRUST_SSL_SERVER
 NID_description                    OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG        X509_TRUST_TSA
 NID_desx_cbc                       OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG        X509_V_FLAG_ALLOW_PROXY_CERTS
 NID_dhKeyAgreement                 OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG       X509_V_FLAG_CB_ISSUER_CHECK
 NID_dnQualifier                    OP_NON_EXPORT_FIRST                       X509_V_FLAG_CRL_CHECK
 NID_dsa                            OP_NO_COMPRESSION                         X509_V_FLAG_CRL_CHECK_ALL
 NID_dsaWithSHA                     OP_NO_QUERY_MTU                           X509_V_FLAG_EXPLICIT_POLICY
 NID_dsaWithSHA1                    OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION X509_V_FLAG_IGNORE_CRITICAL
 NID_dsaWithSHA1_2                  OP_NO_SSLv2                               X509_V_FLAG_INHIBIT_ANY
 NID_dsa_2                          OP_NO_SSLv3                               X509_V_FLAG_INHIBIT_MAP
 NID_email_protect                  OP_NO_TICKET                              X509_V_FLAG_NOTIFY_POLICY
 NID_ext_key_usage                  OP_NO_TLSv1                               X509_V_FLAG_POLICY_CHECK
 NID_ext_req                        OP_PKCS1_CHECK_1                          X509_V_FLAG_USE_CHECK_TIME
 NID_friendlyName                   OP_PKCS1_CHECK_2                          X509_V_FLAG_X509_STRICT
 NID_givenName                      OP_SINGLE_DH_USE
 NID_hmacWithSHA1                   OP_SSLEAY_080_CLIENT_DH_BUG

INTERNAL ONLY functions (do not use these)

The following functions are not intended for use from outside of Net::SSLeay module. They might be removed, renamed or changed without prior notice in future version.

Simply DO NOT USE THEM!

EXAMPLES ^

One very good example to look at is the implementation of sslcat() in the SSLeay.pm file.

The following is a simple SSLeay client (with too little error checking :-(

    #!/usr/local/bin/perl
    use Socket;
    use Net::SSLeay qw(die_now die_if_ssl_error) ;
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();

    ($dest_serv, $port, $msg) = @ARGV;      # Read command line
    $port = getservbyname ($port, 'tcp') unless $port =~ /^\d+$/;
    $dest_ip = gethostbyname ($dest_serv);
    $dest_serv_params  = sockaddr_in($port, $dest_ip);

    socket  (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
    connect (S, $dest_serv_params)          or die "connect: $!";
    select  (S); $| = 1; select (STDOUT);   # Eliminate STDIO buffering

    # The network connection is now open, lets fire up SSL    

    $ctx = Net::SSLeay::CTX_new() or die_now("Failed to create SSL_CTX $!");
    Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
         and die_if_ssl_error("ssl ctx set options");
    $ssl = Net::SSLeay::new($ctx) or die_now("Failed to create SSL $!");
    Net::SSLeay::set_fd($ssl, fileno(S));   # Must use fileno
    $res = Net::SSLeay::connect($ssl) and die_if_ssl_error("ssl connect");
    print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";

    # Exchange data

    $res = Net::SSLeay::write($ssl, $msg);  # Perl knows how long $msg is
    die_if_ssl_error("ssl write");
    CORE::shutdown S, 1;  # Half close --> No more output, sends EOF to server
    $got = Net::SSLeay::read($ssl);         # Perl returns undef on failure
    die_if_ssl_error("ssl read");
    print $got;

    Net::SSLeay::free ($ssl);               # Tear down connection
    Net::SSLeay::CTX_free ($ctx);
    close S;

The following is a simple SSLeay echo server (non forking):

    #!/usr/local/bin/perl -w
    use Socket;
    use Net::SSLeay qw(die_now die_if_ssl_error);
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();

    $our_ip = "\0\0\0\0"; # Bind to all interfaces
    $port = 1235;                                                        
    $sockaddr_template = 'S n a4 x8';
    $our_serv_params = pack ($sockaddr_template, &AF_INET, $port, $our_ip);

    socket (S, &AF_INET, &SOCK_STREAM, 0)  or die "socket: $!";
    bind (S, $our_serv_params)             or die "bind:   $!";
    listen (S, 5)                          or die "listen: $!";
    $ctx = Net::SSLeay::CTX_new ()         or die_now("CTX_new ($ctx): $!");
    Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
         and die_if_ssl_error("ssl ctx set options");

    # Following will ask password unless private key is not encrypted
    Net::SSLeay::CTX_use_RSAPrivateKey_file ($ctx, 'plain-rsa.pem',
                                             &Net::SSLeay::FILETYPE_PEM);
    die_if_ssl_error("private key");
    Net::SSLeay::CTX_use_certificate_file ($ctx, 'plain-cert.pem',
                                           &Net::SSLeay::FILETYPE_PEM);
    die_if_ssl_error("certificate");

    while (1) {    
        print "Accepting connections...\n";
        ($addr = accept (NS, S))           or die "accept: $!";
        select (NS); $| = 1; select (STDOUT);  # Piping hot!

        ($af,$client_port,$client_ip) = unpack($sockaddr_template,$addr);
        @inetaddr = unpack('C4',$client_ip);
        print "$af connection from " .
        join ('.', @inetaddr) . ":$client_port\n";

        # We now have a network connection, lets fire up SSLeay...

        $ssl = Net::SSLeay::new($ctx)      or die_now("SSL_new ($ssl): $!");
        Net::SSLeay::set_fd($ssl, fileno(NS));

        $err = Net::SSLeay::accept($ssl) and die_if_ssl_error('ssl accept');
        print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";

        # Connected. Exchange some data.

        $got = Net::SSLeay::read($ssl);     # Returns undef on fail
        die_if_ssl_error("ssl read");
        print "Got `$got' (" . length ($got) . " chars)\n";

        Net::SSLeay::write ($ssl, uc ($got)) or die "write: $!";
        die_if_ssl_error("ssl write");

        Net::SSLeay::free ($ssl);           # Tear down connection
        close NS;
    }

Yet another echo server. This one runs from /etc/inetd.conf so it avoids all the socket code overhead. Only caveat is opening an rsa key file - it had better be without any encryption or else it will not know where to ask for the password. Note how STDIN and STDOUT are wired to SSL.

    #!/usr/local/bin/perl
    # /etc/inetd.conf
    #    ssltst stream tcp nowait root /path/to/server.pl server.pl
    # /etc/services
    #    ssltst         1234/tcp

    use Net::SSLeay qw(die_now die_if_ssl_error);
    Net::SSLeay::load_error_strings();
    Net::SSLeay::SSLeay_add_ssl_algorithms();
    Net::SSLeay::randomize();

    chdir '/key/dir' or die "chdir: $!";
    $| = 1;  # Piping hot!
    open LOG, ">>/dev/console" or die "Can't open log file $!";
    select LOG; print "server.pl started\n";

    $ctx = Net::SSLeay::CTX_new()     or die_now "CTX_new ($ctx) ($!)";
    $ssl = Net::SSLeay::new($ctx)     or die_now "new ($ssl) ($!)";
    Net::SSLeay::set_options($ssl, &Net::SSLeay::OP_ALL)
         and die_if_ssl_error("ssl set options");

    # We get already open network connection from inetd, now we just
    # need to attach SSLeay to STDIN and STDOUT
    Net::SSLeay::set_rfd($ssl, fileno(STDIN));
    Net::SSLeay::set_wfd($ssl, fileno(STDOUT));

    Net::SSLeay::use_RSAPrivateKey_file ($ssl, 'plain-rsa.pem',
                                         Net::SSLeay::FILETYPE_PEM);
    die_if_ssl_error("private key");
    Net::SSLeay::use_certificate_file ($ssl, 'plain-cert.pem',
                                       Net::SSLeay::FILETYPE_PEM);
    die_if_ssl_error("certificate");

    Net::SSLeay::accept($ssl) and die_if_ssl_err("ssl accept: $!");
    print "Cipher `" . Net::SSLeay::get_cipher($ssl) . "'\n";

    $got = Net::SSLeay::read($ssl);
    die_if_ssl_error("ssl read");
    print "Got `$got' (" . length ($got) . " chars)\n";

    Net::SSLeay::write ($ssl, uc($got)) or die "write: $!";
    die_if_ssl_error("ssl write");

    Net::SSLeay::free ($ssl);         # Tear down the connection
    Net::SSLeay::CTX_free ($ctx);
    close LOG;

There are also a number of example/test programs in the examples directory:

    sslecho.pl   -  A simple server, not unlike the one above
    minicli.pl   -  Implements a client using low level SSLeay routines
    sslcat.pl    -  Demonstrates using high level sslcat utility function
    get_page.pl  -  Is a utility for getting html pages from secure servers
    callback.pl  -  Demonstrates certificate verification and callback usage
    stdio_bulk.pl       - Does SSL over Unix pipes
    ssl-inetd-serv.pl   - SSL server that can be invoked from inetd.conf
    httpd-proxy-snif.pl - Utility that allows you to see how a browser
                          sends https request to given server and what reply
                          it gets back (very educative :-)
    makecert.pl  -  Creates a self signed cert (does not use this module)

LIMITATIONS ^

Net::SSLeay::read() uses an internal buffer of 32KB, thus no single read will return more. In practice one read returns much less, usually as much as fits in one network packet. To work around this, you should use a loop like this:

    $reply = '';
    while ($got = Net::SSLeay::read($ssl)) {
        last if print_errs('SSL_read');
        $reply .= $got;
    }

Although there is no built-in limit in Net::SSLeay::write(), the network packet size limitation applies here as well, thus use:

    $written = 0;

    while ($written < length($message)) {
        $written += Net::SSLeay::write($ssl, substr($message, $written));
        last if print_errs('SSL_write');
    }

Or alternatively you can just use the following convenience functions:

    Net::SSLeay::ssl_write_all($ssl, $message) or die "ssl write failure";
    $got = Net::SSLeay::ssl_read_all($ssl) or die "ssl read failure";

KNOWN BUGS AND CAVEATS ^

Autoloader emits a

    Argument "xxx" isn't numeric in entersub at blib/lib/Net/SSLeay.pm'

warning if die_if_ssl_error is made autoloadable. If you figure out why, drop me a line.

Callback set using SSL_set_verify() does not appear to work. This may well be an openssl problem (e.g. see ssl/ssl_lib.c line 1029). Try using SSL_CTX_set_verify() instead and do not be surprised if even this stops working in future versions.

Callback and certificate verification stuff is generally too little tested.

Random numbers are not initialized randomly enough, especially if you do not have /dev/random and/or /dev/urandom (such as in Solaris platforms - but it's been suggested that cryptorand daemon from the SUNski package solves this). In this case you should investigate third party software that can emulate these devices, e.g. by way of a named pipe to some program.

Another gotcha with random number initialization is randomness depletion. This phenomenon, which has been extensively discussed in OpenSSL, Apache-SSL, and Apache-mod_ssl forums, can cause your script to block if you use /dev/random or to operate insecurely if you use /dev/urandom. What happens is that when too much randomness is drawn from the operating system's randomness pool then randomness can temporarily be unavailable. /dev/random solves this problem by waiting until enough randomness can be gathered - and this can take a long time since blocking reduces activity in the machine and less activity provides less random events: a vicious circle. /dev/urandom solves this dilemma more pragmatically by simply returning predictable "random" numbers. Some /dev/urandom emulation software however actually seems to implement /dev/random semantics. Caveat emptor.

I've been pointed to two such daemons by Mik Firestone <mik@@speed.stdio._com> who has used them on Solaris 8:

  1. Entropy Gathering Daemon (EGD) at http://www.lothar.com/tech/crypto/
  2. Pseudo-random number generating daemon (PRNGD) at http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html

If you are using the low level API functions to communicate with other SSL implementations, you would do well to call

    Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL)
         and die_if_ssl_error("ssl ctx set options");

to cope with some well know bugs in some other SSL implementations. The high level API functions always set all known compatibility options.

Sometimes sslcat() (and the high level HTTPS functions that build on it) is too fast in signaling the EOF to legacy HTTPS servers. This causes the server to return empty page. To work around this problem you can set the global variable

    $Net::SSLeay::slowly = 1;   # Add sleep so broken servers can keep up

HTTP/1.1 is not supported. Specifically this module does not know to issue or serve multiple http requests per connection. This is a serious shortcoming, but using the SSL session cache on your server helps to alleviate the CPU load somewhat.

As of version 1.09 many newer OpenSSL auxiliary functions were added (from REM_AUTOMATICALLY_GENERATED_1_09 onwards in SSLeay.xs). Unfortunately I have not had any opportunity to test these. Some of them are trivial enough that I believe they "just work", but others have rather complex interfaces with function pointers and all. In these cases you should proceed wit great caution.

This module defaults to using OpenSSL automatic protocol negotiation code for automatically detecting the version of the SSL protocol that the other end talks. With most web servers this works just fine, but once in a while I get complaints from people that the module does not work with some web servers. Usually this can be solved by explicitly setting the protocol version, e.g.

   $Net::SSLeay::ssl_version = 2;  # Insist on SSLv2
   $Net::SSLeay::ssl_version = 3;  # Insist on SSLv3
   $Net::SSLeay::ssl_version = 10; # Insist on TLSv1

Although the autonegotiation is nice to have, the SSL standards do not formally specify any such mechanism. Most of the world has accepted the SSLeay/OpenSSL way of doing it as the de facto standard. But for the few that think differently, you have to explicitly speak the correct version. This is not really a bug, but rather a deficiency in the standards. If a site refuses to respond or sends back some nonsensical error codes (at the SSL handshake level), try this option before mailing me.

On some systems, OpenSSL may be compiled without support for SSLv2. If this is the case, Net::SSLeay will warn if ssl_version has been set to 2.

The high level API returns the certificate of the peer, thus allowing one to check what certificate was supplied. However, you will only be able to check the certificate after the fact, i.e. you already sent your form data by the time you find out that you did not trust them, oops.

So, while being able to know the certificate after the fact is surely useful, the security minded would still choose to do the connection and certificate verification first and only then exchange data with the site. Currently none of the high level API functions do this, thus you would have to program it using the low level API. A good place to start is to see how the Net::SSLeay::http_cat() function is implemented.

The high level API functions use a global file handle SSLCAT_S internally. This really should not be a problem because there is no way to interleave the high level API functions, unless you use threads (but threads are not very well supported in perl anyway (as of version 5.6.1). However, you may run into problems if you call undocumented internal functions in an interleaved fashion. The best solution is to "require Net::SSLeay" in one thread after all the threads have been created.

DIAGNOSTICS ^

Random number generator not seeded!!!

(W) This warning indicates that randomize() was not able to read /dev/random or /dev/urandom, possibly because your system does not have them or they are differently named. You can still use SSL, but the encryption will not be as strong.

open_tcp_connection: destination host not found:`server' (port 123) ($!)

Name lookup for host named server failed.

open_tcp_connection: failed `server', 123 ($!)

The name was resolved, but establishing the TCP connection failed.

msg 123: 1 - error:140770F8:SSL routines:SSL23_GET_SERVER_HELLO:unknown proto

SSLeay error string. The first number (123) is the PID, the second number (1) indicates the position of the error message in SSLeay error stack. You often see a pile of these messages as errors cascade.

msg 123: 1 - error:02001002::lib(2) :func(1) :reason(2)

The same as above, but you didn't call load_error_strings() so SSLeay couldn't verbosely explain the error. You can still find out what it means with this command:

    /usr/local/ssl/bin/ssleay errstr 02001002
Password is being asked for private key

This is normal behaviour if your private key is encrypted. Either you have to supply the password or you have to use an unencrypted private key. Scan OpenSSL.org for the FAQ that explains how to do this (or just study examples/makecert.pl which is used during make test to do just that).

BUGS AND SUPPORT ^

Please report any bugs or feature requests to bug-Net-SSLeay at rt.cpan.org, or through the web interface at http://rt.cpan.org/Public/Dist/Display.html?Name=Net-SSLeay. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

Subversion access to the latest source code etc can be obtained at http://alioth.debian.org/projects/net-ssleay

The developer mailing list (for people interested in contributing to the source code) can be found at http://lists.alioth.debian.org/mailman/listinfo/net-ssleay-devel

You can find documentation for this module with the perldoc command.

    perldoc Net::SSLeay

You can also look for information at:

Commercial support for Net::SSLeay may be obtained from

   Symlabs (netssleay@symlabs.com)
   Tel: +351-214.222.630
   Fax: +351-214.222.637

AUTHOR ^

Maintained by Mike McCauley and Florian Ragwitz since November 2005

Originally written by Sampo Kellomäki <sampo@symlabs.com>

COPYRIGHT ^

Copyright (c) 1996-2003 Sampo Kellomäki <sampo@symlabs.com>

Copyright (C) 2005-2006 Florian Ragwitz <rafl@debian.org>

Copyright (C) 2005 Mike McCauley <mikem@open.com.au>

All Rights Reserved.

Distribution and use of this module is under the same terms as the OpenSSL package itself (i.e. free, but mandatory attribution; NO WARRANTY). Please consult LICENSE file in the root of the OpenSSL distribution.

While the source distribution of this perl module does not contain Eric's or OpenSSL's code, if you use this module you will use OpenSSL library. Please give Eric and OpenSSL team credit (as required by their licenses).

And remember, you, and nobody else but you, are responsible for auditing this module and OpenSSL library for security problems, backdoors, and general suitability for your application.

SEE ALSO ^

  Net::SSLeay::Handle                      - File handle interface
  ./examples                               - Example servers and a clients
  <http://www.openssl.org/>                - OpenSSL source, documentation, etc
  openssl-users-request@openssl.org        - General OpenSSL mailing list
  <http://www.ietf.org/rfc/rfc2246.txt>    - TLS 1.0 specification
  <http://www.w3c.org>                     - HTTP specifications
  <http://www.ietf.org/rfc/rfc2617.txt>    - How to send password
  <http://www.lothar.com/tech/crypto/>     - Entropy Gathering Daemon (EGD)
  <http://www.aet.tu-cottbus.de/personen/jaenicke/postfix_tls/prngd.html>
                           - pseudo-random number generating daemon (PRNGD)
  perl(1)
  perlref(1)
  perllol(1)
  perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod
syntax highlighting: