CONTENTS

NAME

Net::SSLeay - Perl bindings for OpenSSL and LibreSSL

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

This module provides Perl bindings for libssl (an SSL/TLS API) and libcrypto (a cryptography API).

COMPATIBILITY

Net::SSLeay supports the following libssl implementations:

Net::SSLeay may not function as expected with releases other than the ones listed above due to libssl API incompatibilities, or, in the case of LibreSSL, because of deviations from the libssl API.

Net::SSLeay is only as secure as the underlying libssl implementation you use. Although Net::SSLeay maintains compatibility with old versions of OpenSSL and LibreSSL, it is strongly recommended that you use a version of OpenSSL or LibreSSL that is supported by the OpenSSL/LibreSSL developers and/or your operating system vendor. Many unsupported versions of OpenSSL and LibreSSL are known to contain severe security vulnerabilities. Refer to the OpenSSL Release Strategy and LibreSSL Support Schedule for information on which versions are currently supported.

The libssl API has changed significantly since OpenSSL 0.9.8: hundreds of functions have been added, deprecated or removed in the intervening versions. Although this documentation lists all of the functions and constants that Net::SSLeay may expose, they will not be available for use if they are missing from the underlying libssl implementation. Refer to the compatibility notes in this documentation, as well as the OpenSSL/LibreSSL manual pages, for information on which OpenSSL/LibreSSL versions support each function or constant. At run-time, you can check whether a function or constant is exposed before calling it using the following convention:

if ( defined &Net::SSLeay::libssl_function ) {
    # libssl_function() (or SSL_libssl_function()) is available
    Net::SSLeay::libssl_function(...);
}

OVERVIEW

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 https://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. Do not post UTF-8 data as content: use utf8::downgrade first. 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)
    = 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 sprintf('Subject Name: %s Issuer  Name: %s',
        Net::SSLeay::X509_NAME_oneline(
            Net::SSLeay::X509_get_subject_name($server_cert)),
        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....
}

Usually the URLs where you can download the CRLs is contained in the certificate itself and you can extract them with

my @url = Net::SSLeay::P_X509_get_crl_distribution_points($cert);

But there is no automatic downloading of the CRLs and often these CRLs are too huge to just download them to verify a single certificate. Also, these CRLs are often in DER format which you need to convert to PEM before you can use it:

openssl crl -in crl.der -inform der -out crl.pem

So as an alternative for faster and timely revocation checks you better use the Online Status Revocation Protocol (OCSP).

Certificate verification and Online Status Revocation Protocol (OCSP)

While checking for revoked certificates is possible and fast with Certificate Revocation Lists, you need to download the complete and often huge list before you can verify a single certificate.

A faster way is to ask the CA to check the revocation of just a single or a few certificates using OCSP. Basically you generate for each certificate an OCSP_CERTID based on the certificate itself and its issuer, put the ids together into an OCSP_REQUEST and send the request to the URL given in the certificate.

As a result you get back an OCSP_RESPONSE and need to check the status of the response, check that it is valid (e.g. signed by the CA) and finally extract the information about each OCSP_CERTID to find out if the certificate is still valid or got revoked.

With Net::SSLeay this can be done like this:

# get id(s) for given certs, like from get_peer_certificate
# or get_peer_cert_chain. This will croak if
# - one tries to make an OCSP_CERTID for a self-signed certificate
# - the issuer of the certificate cannot be found in the SSL objects
#   store, nor in the current certificate chain
my $cert = Net::SSLeay::get_peer_certificate($ssl);
my $id = eval { Net::SSLeay::OCSP_cert2ids($ssl,$cert) };
die "failed to make OCSP_CERTID: $@" if $@;

# create OCSP_REQUEST from id(s)
# Multiple can be put into the same request, if the same OCSP responder
# is responsible for them.
my $req = Net::SSLeay::OCSP_ids2req($id);

# determine URI of OCSP responder
my $uri = Net::SSLeay::P_X509_get_ocsp_uri($cert);

# Send stringified OCSP_REQUEST with POST to $uri.
# We can ignore certificate verification for https, because the OCSP
# response itself is signed.
my $ua = HTTP::Tiny->new(verify_SSL => 0);
my $res = $ua->request( 'POST',$uri, {
    headers => { 'Content-type' => 'application/ocsp-request' },
    content => Net::SSLeay::i2d_OCSP_REQUEST($req)
});
my $content = $res && $res->{success} && $res->{content}
    or die "query failed";

# Extract OCSP_RESPONSE.
# this will croak if the string is not an OCSP_RESPONSE
my $resp = eval { Net::SSLeay::d2i_OCSP_RESPONSE($content) };

# Check status of response.
my $status = Net::SSLeay::OCSP_response_status($resp);
if ($status != Net::SSLeay::OCSP_RESPONSE_STATUS_SUCCESSFUL()) {
    die "OCSP response failed: " .
        Net::SSLeay::OCSP_response_status_str($status);
}

# Verify signature of response and if nonce matches request.
# This will croak if there is a nonce in the response, but it does not match
# the request. It will return false if the signature could not be verified,
# in which case details can be retrieved with Net::SSLeay::ERR_get_error.
# It will not complain if the response does not contain a nonce, which is
# usually the case with pre-signed responses.
if ( ! eval { Net::SSLeay::OCSP_response_verify($ssl,$resp,$req) }) {
    die "OCSP response verification failed";
}

# Extract information from OCSP_RESPONSE for each of the ids.

# If called in scalar context it will return the time (as time_t), when the
# next update is due (minimum of all successful responses inside $resp). It
# will croak on the following problems:
# - response is expired or not yet valid
# - no response for given OCSP_CERTID
# - certificate status is not good (e.g. revoked or unknown)
if ( my $nextupd = eval { Net::SSLeay::OCSP_response_results($resp,$id) }) {
    warn "certificate is valid, next update in " .
        ($nextupd-time()) . " seconds\n";
} else {
    die "certificate is not valid: $@";
}

# But in array context it will return detailed information about each given
# OCSP_CERTID instead croaking on errors:
# if no @ids are given it will return information about all single responses
# in the OCSP_RESPONSE
my @results = Net::SSLeay::OCSP_response_results($resp,@ids);
for my $r (@results) {
    print Dumper($r);
    # @results are in the same order as the @ids and contain:
    # $r->[0] - OCSP_CERTID
    # $r->[1] - undef if no error (certificate good) OR error message as string
    # $r->[2] - hash with details:
    #   thisUpdate - time_t of this single response
    #   nextUpdate - time_t when update is expected
    #   statusType - integer:
    #      V_OCSP_CERTSTATUS_GOOD(0)
    #      V_OCSP_CERTSTATUS_REVOKED(1)
    #      V_OCSP_CERTSTATUS_UNKNOWN(2)
    #   revocationTime - time_t (only if revoked)
    #   revocationReason - integer (only if revoked)
    #   revocationReason_str - reason as string (only if revoked)
}

To further speed up certificate revocation checking one can use a TLS extension to instruct the server to staple the OCSP response:

# set TLS extension before doing SSL_connect
Net::SSLeay::set_tlsext_status_type($ssl,
    Net::SSLeay::TLSEXT_STATUSTYPE_ocsp());

# setup callback to verify OCSP response
my $cert_valid = undef;
Net::SSLeay::CTX_set_tlsext_status_cb($context,sub {
    my ($ssl,$resp) = @_;
    if (!$resp) {
        # Lots of servers don't return an OCSP response.
        # In this case we must check the OCSP status outside the SSL
        # handshake.
        warn "server did not return stapled OCSP response\n";
        return 1;
    }
    # verify status
    my $status = Net::SSLeay::OCSP_response_status($resp);
    if ($status != Net::SSLeay::OCSP_RESPONSE_STATUS_SUCCESSFUL()) {
        warn "OCSP response failure: $status\n";
        return 1;
    }
    # verify signature - we have no OCSP_REQUEST here to check nonce
    if (!eval { Net::SSLeay::OCSP_response_verify($ssl,$resp) }) {
        warn "OCSP response verify failed\n";
        return 1;
    }
    # check if the certificate is valid
    # we should check here against the peer_certificate
    my $cert = Net::SSLeay::get_peer_certificate();
    my $certid = eval { Net::SSLeay::OCSP_cert2ids($ssl,$cert) } or do {
        warn "cannot get certid from cert: $@";
        $cert_valid = -1;
        return 1;
    };

    if ( $nextupd = eval {
        Net::SSLeay::OCSP_response_results($resp,$certid) }) {
        warn "certificate not revoked\n";
        $cert_valid = 1;
    } else {
        warn "certificate not valid: $@";
        $cert_valid = 0;
    }
});

# do SSL handshake here
# ....
# check if certificate revocation was checked already
if ( ! defined $cert_valid) {
    # check revocation outside of SSL handshake by asking OCSP responder
    ...
} elsif ( ! $cert_valid ) {
    die "certificate not valid - closing SSL connection";
} elsif ( $cert_valid<0 ) {
    die "cannot verify certificate revocation - self-signed ?";
} else {
    # everything fine
    ...
}

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 - it requires openssl-0.9.7 or newer. The implementation fully follows thread safety related requirements of openssl library(see https://www.openssl.org/docs/manmaster/man3/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). Always 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 safe you can load and init Net::SSLeay explicitly 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();

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();
}

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

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

Check openssl doc https://www.openssl.org/docs/manmaster/man3/pem.html

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

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

Check openssl doc related to RAND stuff https://www.openssl.org/docs/manmaster/man3/rand.html

Low level API: Server side Server Name Indication (SNI) support

NPN is being replaced with ALPN, a more recent TLS extension for application protocol negotiation that's in process of being adopted by IETF. Please look below for APLN API description.

Simple approach for using NPN support looks like this:

### client side
use Net::SSLeay;
use IO::Socket::INET;

Net::SSLeay::initialize();
my $sock = IO::Socket::INET->new(PeerAddr=>'encrypted.google.com:443') or die;
my $ctx = Net::SSLeay::CTX_tlsv1_new() or die;
Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL);
Net::SSLeay::CTX_set_next_proto_select_cb($ctx, ['http1.1','spdy/2']);
my $ssl = Net::SSLeay::new($ctx) or die;
Net::SSLeay::set_fd($ssl, fileno($sock)) or die;
Net::SSLeay::connect($ssl);

warn "client:negotiated=",Net::SSLeay::P_next_proto_negotiated($ssl), "\n";
warn "client:last_status=", Net::SSLeay::P_next_proto_last_status($ssl), "\n";

### server side
use Net::SSLeay;
use IO::Socket::INET;

Net::SSLeay::initialize();
my $ctx = Net::SSLeay::CTX_tlsv1_new() or die;
Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL);
Net::SSLeay::set_cert_and_key($ctx, "cert.pem", "key.pem");
Net::SSLeay::CTX_set_next_protos_advertised_cb($ctx, ['spdy/2','http1.1']);
my $sock = IO::Socket::INET->new(LocalAddr=>'localhost', LocalPort=>5443, Proto=>'tcp', Listen=>20) or die;

while (1) {
    my $ssl = Net::SSLeay::new($ctx);
    warn("server:waiting for incoming connection...\n");
    my $fd = $sock->accept();
    Net::SSLeay::set_fd($ssl, $fd->fileno);
    Net::SSLeay::accept($ssl);
    warn "server:negotiated=",Net::SSLeay::P_next_proto_negotiated($ssl),"\n";
    my $got = Net::SSLeay::read($ssl);
    Net::SSLeay::ssl_write_all($ssl, "length=".length($got));
    Net::SSLeay::free($ssl);
    $fd->close();
}
# check with: openssl s_client -connect localhost:5443 -nextprotoneg http/1.1,spdy/2

Please note that the selection (negotiation) is performed by client side, the server side simply advertise the list of supported protocols.

Advanced approach allows you to implement your own negotiation algorithm.

# see below documentation for:
Net::SSLeay::CTX_set_next_proto_select_cb($ctx, $perl_callback_function, $callback_data);
Net::SSLeay::CTX_set_next_protos_advertised_cb($ctx, $perl_callback_function, $callback_data);

Detection of NPN support (works even in older Net::SSLeay versions):

use Net::SSLeay;

if (exists &Net::SSLeay::P_next_proto_negotiated) {
    # do NPN stuff
}

Application protocol can be negotiated via two different mechanisms employing two different TLS extensions: NPN (obsolete) and ALPN (recommended).

The API is rather similar, with slight differences reflecting protocol specifics. In particular, with ALPN the protocol negotiation takes place on server, while with NPN the client implements the protocol negotiation logic.

With ALPN, the most basic implementation looks like this:

### client side
use Net::SSLeay;
use IO::Socket::INET;

Net::SSLeay::initialize();
my $sock = IO::Socket::INET->new(PeerAddr=>'encrypted.google.com:443') or die;
my $ctx = Net::SSLeay::CTX_tlsv1_new() or die;
Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL);
Net::SSLeay::CTX_set_alpn_protos($ctx, ['http/1.1', 'http/2.0', 'spdy/3']);
my $ssl = Net::SSLeay::new($ctx) or die;
Net::SSLeay::set_fd($ssl, fileno($sock)) or die;
Net::SSLeay::connect($ssl);

warn "client:selected=",Net::SSLeay::P_alpn_selected($ssl), "\n";

### server side
use Net::SSLeay;
use IO::Socket::INET;

Net::SSLeay::initialize();
my $ctx = Net::SSLeay::CTX_tlsv1_new() or die;
Net::SSLeay::CTX_set_options($ctx, &Net::SSLeay::OP_ALL);
Net::SSLeay::set_cert_and_key($ctx, "cert.pem", "key.pem");
Net::SSLeay::CTX_set_alpn_select_cb($ctx, ['http/1.1', 'http/2.0', 'spdy/3']);
my $sock = IO::Socket::INET->new(LocalAddr=>'localhost', LocalPort=>5443, Proto=>'tcp', Listen=>20) or die;

while (1) {
    my $ssl = Net::SSLeay::new($ctx);
    warn("server:waiting for incoming connection...\n");
    my $fd = $sock->accept();
    Net::SSLeay::set_fd($ssl, $fd->fileno);
    Net::SSLeay::accept($ssl);
    warn "server:selected=",Net::SSLeay::P_alpn_selected($ssl),"\n";
    my $got = Net::SSLeay::read($ssl);
    Net::SSLeay::ssl_write_all($ssl, "length=".length($got));
    Net::SSLeay::free($ssl);
    $fd->close();
}
# check with: openssl s_client -connect localhost:5443 -alpn spdy/3,http/1.1

Advanced approach allows you to implement your own negotiation algorithm.

# see below documentation for:
Net::SSLeay::CTX_set_alpn_select_cb($ctx, $perl_callback_function, $callback_data);

Detection of ALPN support (works even in older Net::SSLeay versions):

use Net::SSLeay;

if (exists &Net::SSLeay::P_alpn_selected) {
    # do ALPN stuff
}

Low level API: DANE Support

OpenSSL version 1.0.2 adds preliminary support RFC6698 Domain Authentication of Named Entities (DANE) Transport Layer Association within OpenSSL

Low level API: Other functions

COMPATIBILITY: not available in Net-SSLeay-1.92 and before. The TLSv1.3 specific functions require at least OpenSSL 1.1.1 and the others require at least OpenSSL 1.0.0. Not available in LibreSSL.

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 constants names are derived from openssl constants, however constants starting with SSL_ prefix have name with SSL_ part stripped - e.g. openssl's constant SSL_OP_ALL is available as Net::SSLeay::OP_ALL

The list of all available constant names:

The list below is automatically generated - do not manually modify it. To add or remove a constant, edit helper_script/constants.txt, then run helper_script/update-exported-constants.

AD_ACCESS_DENIED                        OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS
AD_BAD_CERTIFICATE                      OPENSSL_INIT_NO_LOAD_SSL_STRINGS
AD_BAD_CERTIFICATE_HASH_VALUE           OPENSSL_MODULES_DIR
AD_BAD_CERTIFICATE_STATUS_RESPONSE      OPENSSL_PLATFORM
AD_BAD_RECORD_MAC                       OPENSSL_VERSION
AD_CERTIFICATE_EXPIRED                  OPENSSL_VERSION_MAJOR
AD_CERTIFICATE_REQUIRED                 OPENSSL_VERSION_MINOR
AD_CERTIFICATE_REVOKED                  OPENSSL_VERSION_NUMBER
AD_CERTIFICATE_UNKNOWN                  OPENSSL_VERSION_PATCH
AD_CERTIFICATE_UNOBTAINABLE             OPENSSL_VERSION_STRING
AD_CLOSE_NOTIFY                         OP_ALL
AD_DECODE_ERROR                         OP_ALLOW_CLIENT_RENEGOTIATION
AD_DECOMPRESSION_FAILURE                OP_ALLOW_NO_DHE_KEX
AD_DECRYPTION_FAILED                    OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
AD_DECRYPT_ERROR                        OP_CIPHER_SERVER_PREFERENCE
AD_EXPORT_RESTRICTION                   OP_CISCO_ANYCONNECT
AD_HANDSHAKE_FAILURE                    OP_CLEANSE_PLAINTEXT
AD_ILLEGAL_PARAMETER                    OP_COOKIE_EXCHANGE
AD_INAPPROPRIATE_FALLBACK               OP_CRYPTOPRO_TLSEXT_BUG
AD_INSUFFICIENT_SECURITY                OP_DISABLE_TLSEXT_CA_NAMES
AD_INTERNAL_ERROR                       OP_DONT_INSERT_EMPTY_FRAGMENTS
AD_MISSING_EXTENSION                    OP_ENABLE_KTLS
AD_NO_APPLICATION_PROTOCOL              OP_ENABLE_MIDDLEBOX_COMPAT
AD_NO_CERTIFICATE                       OP_EPHEMERAL_RSA
AD_NO_RENEGOTIATION                     OP_IGNORE_UNEXPECTED_EOF
AD_PROTOCOL_VERSION                     OP_LEGACY_SERVER_CONNECT
AD_RECORD_OVERFLOW                      OP_MICROSOFT_BIG_SSLV3_BUFFER
AD_UNEXPECTED_MESSAGE                   OP_MICROSOFT_SESS_ID_BUG
AD_UNKNOWN_CA                           OP_MSIE_SSLV2_RSA_PADDING
AD_UNKNOWN_PSK_IDENTITY                 OP_NETSCAPE_CA_DN_BUG
AD_UNRECOGNIZED_NAME                    OP_NETSCAPE_CHALLENGE_BUG
AD_UNSUPPORTED_CERTIFICATE              OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
AD_UNSUPPORTED_EXTENSION                OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
AD_USER_CANCELLED                       OP_NON_EXPORT_FIRST
ASN1_STRFLGS_ESC_CTRL                   OP_NO_ANTI_REPLAY
ASN1_STRFLGS_ESC_MSB                    OP_NO_CLIENT_RENEGOTIATION
ASN1_STRFLGS_ESC_QUOTE                  OP_NO_COMPRESSION
ASN1_STRFLGS_RFC2253                    OP_NO_ENCRYPT_THEN_MAC
ASYNC_NO_JOBS                           OP_NO_EXTENDED_MASTER_SECRET
ASYNC_PAUSED                            OP_NO_QUERY_MTU
CB_ACCEPT_EXIT                          OP_NO_RENEGOTIATION
CB_ACCEPT_LOOP                          OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
CB_ALERT                                OP_NO_SSL_MASK
CB_CONNECT_EXIT                         OP_NO_SSLv2
CB_CONNECT_LOOP                         OP_NO_SSLv3
CB_EXIT                                 OP_NO_TICKET
CB_HANDSHAKE_DONE                       OP_NO_TLSv1
CB_HANDSHAKE_START                      OP_NO_TLSv1_1
CB_LOOP                                 OP_NO_TLSv1_2
CB_READ                                 OP_NO_TLSv1_3
CB_READ_ALERT                           OP_PKCS1_CHECK_1
CB_WRITE                                OP_PKCS1_CHECK_2
CB_WRITE_ALERT                          OP_PRIORITIZE_CHACHA
CLIENT_HELLO_CB                         OP_SAFARI_ECDHE_ECDSA_BUG
CLIENT_HELLO_ERROR                      OP_SINGLE_DH_USE
CLIENT_HELLO_RETRY                      OP_SINGLE_ECDH_USE
CLIENT_HELLO_SUCCESS                    OP_SSLEAY_080_CLIENT_DH_BUG
CONF_MFLAGS_DEFAULT_SECTION             OP_SSLREF2_REUSE_CERT_TYPE_BUG
CONF_MFLAGS_IGNORE_ERRORS               OP_TLSEXT_PADDING
CONF_MFLAGS_IGNORE_MISSING_FILE         OP_TLS_BLOCK_PADDING_BUG
CONF_MFLAGS_IGNORE_RETURN_CODES         OP_TLS_D5_BUG
CONF_MFLAGS_NO_DSO                      OP_TLS_ROLLBACK_BUG
CONF_MFLAGS_SILENT                      READING
ERROR_NONE                              RECEIVED_SHUTDOWN
ERROR_SSL                               RETRY_VERIFY
ERROR_SYSCALL                           RSA_3
ERROR_WANT_ACCEPT                       RSA_F4
ERROR_WANT_ASYNC                        R_BAD_AUTHENTICATION_TYPE
ERROR_WANT_ASYNC_JOB                    R_BAD_CHECKSUM
ERROR_WANT_CLIENT_HELLO_CB              R_BAD_MAC_DECODE
ERROR_WANT_CONNECT                      R_BAD_RESPONSE_ARGUMENT
ERROR_WANT_READ                         R_BAD_SSL_FILETYPE
ERROR_WANT_RETRY_VERIFY                 R_BAD_SSL_SESSION_ID_LENGTH
ERROR_WANT_WRITE                        R_BAD_STATE
ERROR_WANT_X509_LOOKUP                  R_BAD_WRITE_RETRY
ERROR_ZERO_RETURN                       R_CHALLENGE_IS_DIFFERENT
EVP_PKS_DSA                             R_CIPHER_TABLE_SRC_ERROR
EVP_PKS_EC                              R_INVALID_CHALLENGE_LENGTH
EVP_PKS_RSA                             R_NO_CERTIFICATE_SET
EVP_PKT_ENC                             R_NO_CERTIFICATE_SPECIFIED
EVP_PKT_EXCH                            R_NO_CIPHER_LIST
EVP_PKT_EXP                             R_NO_CIPHER_MATCH
EVP_PKT_SIGN                            R_NO_PRIVATEKEY
EVP_PK_DH                               R_NO_PUBLICKEY
EVP_PK_DSA                              R_NULL_SSL_CTX
EVP_PK_EC                               R_PEER_DID_NOT_RETURN_A_CERTIFICATE
EVP_PK_RSA                              R_PEER_ERROR
FILETYPE_ASN1                           R_PEER_ERROR_CERTIFICATE
FILETYPE_PEM                            R_PEER_ERROR_NO_CIPHER
F_CLIENT_CERTIFICATE                    R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE
F_CLIENT_HELLO                          R_PUBLIC_KEY_ENCRYPT_ERROR
F_CLIENT_MASTER_KEY                     R_PUBLIC_KEY_IS_NOT_RSA
F_D2I_SSL_SESSION                       R_READ_WRONG_PACKET_TYPE
F_GET_CLIENT_FINISHED                   R_SHORT_READ
F_GET_CLIENT_HELLO                      R_SSL_SESSION_ID_IS_DIFFERENT
F_GET_CLIENT_MASTER_KEY                 R_UNABLE_TO_EXTRACT_PUBLIC_KEY
F_GET_SERVER_FINISHED                   R_UNKNOWN_REMOTE_ERROR_TYPE
F_GET_SERVER_HELLO                      R_UNKNOWN_STATE
F_GET_SERVER_VERIFY                     R_X509_LIB
F_I2D_SSL_SESSION                       SENT_SHUTDOWN
F_READ_N                                SESSION_ASN1_VERSION
F_REQUEST_CERTIFICATE                   SESS_CACHE_BOTH
F_SERVER_HELLO                          SESS_CACHE_CLIENT
F_SSL_CERT_NEW                          SESS_CACHE_NO_AUTO_CLEAR
F_SSL_GET_NEW_SESSION                   SESS_CACHE_NO_INTERNAL
F_SSL_NEW                               SESS_CACHE_NO_INTERNAL_LOOKUP
F_SSL_READ                              SESS_CACHE_NO_INTERNAL_STORE
F_SSL_RSA_PRIVATE_DECRYPT               SESS_CACHE_OFF
F_SSL_RSA_PUBLIC_ENCRYPT                SESS_CACHE_SERVER
F_SSL_SESSION_NEW                       SESS_CACHE_UPDATE_TIME
F_SSL_SESSION_PRINT_FP                  SSL2_MT_CLIENT_CERTIFICATE
F_SSL_SET_FD                            SSL2_MT_CLIENT_FINISHED
F_SSL_SET_RFD                           SSL2_MT_CLIENT_HELLO
F_SSL_SET_WFD                           SSL2_MT_CLIENT_MASTER_KEY
F_SSL_USE_CERTIFICATE                   SSL2_MT_ERROR
F_SSL_USE_CERTIFICATE_ASN1              SSL2_MT_REQUEST_CERTIFICATE
F_SSL_USE_CERTIFICATE_FILE              SSL2_MT_SERVER_FINISHED
F_SSL_USE_PRIVATEKEY                    SSL2_MT_SERVER_HELLO
F_SSL_USE_PRIVATEKEY_ASN1               SSL2_MT_SERVER_VERIFY
F_SSL_USE_PRIVATEKEY_FILE               SSL2_VERSION
F_SSL_USE_RSAPRIVATEKEY                 SSL3_MT_CCS
F_SSL_USE_RSAPRIVATEKEY_ASN1            SSL3_MT_CERTIFICATE
F_SSL_USE_RSAPRIVATEKEY_FILE            SSL3_MT_CERTIFICATE_REQUEST
F_WRITE_PENDING                         SSL3_MT_CERTIFICATE_STATUS
GEN_DIRNAME                             SSL3_MT_CERTIFICATE_URL
GEN_DNS                                 SSL3_MT_CERTIFICATE_VERIFY
GEN_EDIPARTY                            SSL3_MT_CHANGE_CIPHER_SPEC
GEN_EMAIL                               SSL3_MT_CLIENT_HELLO
GEN_IPADD                               SSL3_MT_CLIENT_KEY_EXCHANGE
GEN_OTHERNAME                           SSL3_MT_ENCRYPTED_EXTENSIONS
GEN_RID                                 SSL3_MT_END_OF_EARLY_DATA
GEN_URI                                 SSL3_MT_FINISHED
GEN_X400                                SSL3_MT_HELLO_REQUEST
LIBRESSL_VERSION_NUMBER                 SSL3_MT_KEY_UPDATE
MBSTRING_ASC                            SSL3_MT_MESSAGE_HASH
MBSTRING_BMP                            SSL3_MT_NEWSESSION_TICKET
MBSTRING_FLAG                           SSL3_MT_NEXT_PROTO
MBSTRING_UNIV                           SSL3_MT_SERVER_DONE
MBSTRING_UTF8                           SSL3_MT_SERVER_HELLO
MIN_RSA_MODULUS_LENGTH_IN_BYTES         SSL3_MT_SERVER_KEY_EXCHANGE
MODE_ACCEPT_MOVING_WRITE_BUFFER         SSL3_MT_SUPPLEMENTAL_DATA
MODE_ASYNC                              SSL3_RT_ALERT
MODE_AUTO_RETRY                         SSL3_RT_APPLICATION_DATA
MODE_ENABLE_PARTIAL_WRITE               SSL3_RT_CHANGE_CIPHER_SPEC
MODE_NO_AUTO_CHAIN                      SSL3_RT_HANDSHAKE
MODE_RELEASE_BUFFERS                    SSL3_RT_HEADER
NID_OCSP_sign                           SSL3_RT_INNER_CONTENT_TYPE
NID_SMIMECapabilities                   SSL3_VERSION
NID_X500                                SSLEAY_BUILT_ON
NID_X509                                SSLEAY_CFLAGS
NID_ad_OCSP                             SSLEAY_DIR
NID_ad_ca_issuers                       SSLEAY_PLATFORM
NID_algorithm                           SSLEAY_VERSION
NID_authority_key_identifier            ST_ACCEPT
NID_basic_constraints                   ST_BEFORE
NID_bf_cbc                              ST_CONNECT
NID_bf_cfb64                            ST_INIT
NID_bf_ecb                              ST_OK
NID_bf_ofb64                            ST_READ_BODY
NID_cast5_cbc                           ST_READ_HEADER
NID_cast5_cfb64                         TLS1_1_VERSION
NID_cast5_ecb                           TLS1_2_VERSION
NID_cast5_ofb64                         TLS1_3_VERSION
NID_certBag                             TLS1_VERSION
NID_certificate_policies                TLSEXT_STATUSTYPE_ocsp
NID_client_auth                         TLSEXT_TYPE_application_layer_protocol_negotiation
NID_code_sign                           TLSEXT_TYPE_cert_type
NID_commonName                          TLSEXT_TYPE_certificate_authorities
NID_countryName                         TLSEXT_TYPE_client_authz
NID_crlBag                              TLSEXT_TYPE_client_cert_type
NID_crl_distribution_points             TLSEXT_TYPE_client_certificate_url
NID_crl_number                          TLSEXT_TYPE_compress_certificate
NID_crl_reason                          TLSEXT_TYPE_cookie
NID_delta_crl                           TLSEXT_TYPE_early_data
NID_des_cbc                             TLSEXT_TYPE_ec_point_formats
NID_des_cfb64                           TLSEXT_TYPE_elliptic_curves
NID_des_ecb                             TLSEXT_TYPE_encrypt_then_mac
NID_des_ede                             TLSEXT_TYPE_extended_master_secret
NID_des_ede3                            TLSEXT_TYPE_key_share
NID_des_ede3_cbc                        TLSEXT_TYPE_max_fragment_length
NID_des_ede3_cfb64                      TLSEXT_TYPE_next_proto_neg
NID_des_ede3_ofb64                      TLSEXT_TYPE_padding
NID_des_ede_cbc                         TLSEXT_TYPE_post_handshake_auth
NID_des_ede_cfb64                       TLSEXT_TYPE_psk
NID_des_ede_ofb64                       TLSEXT_TYPE_psk_kex_modes
NID_des_ofb64                           TLSEXT_TYPE_quic_transport_parameters
NID_description                         TLSEXT_TYPE_renegotiate
NID_desx_cbc                            TLSEXT_TYPE_server_authz
NID_dhKeyAgreement                      TLSEXT_TYPE_server_cert_type
NID_dnQualifier                         TLSEXT_TYPE_server_name
NID_dsa                                 TLSEXT_TYPE_session_ticket
NID_dsaWithSHA                          TLSEXT_TYPE_signature_algorithms
NID_dsaWithSHA1                         TLSEXT_TYPE_signature_algorithms_cert
NID_dsaWithSHA1_2                       TLSEXT_TYPE_signed_certificate_timestamp
NID_dsa_2                               TLSEXT_TYPE_srp
NID_email_protect                       TLSEXT_TYPE_status_request
NID_ext_key_usage                       TLSEXT_TYPE_supported_groups
NID_ext_req                             TLSEXT_TYPE_supported_versions
NID_friendlyName                        TLSEXT_TYPE_truncated_hmac
NID_givenName                           TLSEXT_TYPE_trusted_ca_keys
NID_hmacWithSHA1                        TLSEXT_TYPE_use_srtp
NID_id_ad                               TLSEXT_TYPE_user_mapping
NID_id_ce                               VERIFY_CLIENT_ONCE
NID_id_kp                               VERIFY_FAIL_IF_NO_PEER_CERT
NID_id_pbkdf2                           VERIFY_NONE
NID_id_pe                               VERIFY_PEER
NID_id_pkix                             VERIFY_POST_HANDSHAKE
NID_id_qt_cps                           V_OCSP_CERTSTATUS_GOOD
NID_id_qt_unotice                       V_OCSP_CERTSTATUS_REVOKED
NID_idea_cbc                            V_OCSP_CERTSTATUS_UNKNOWN
NID_idea_cfb64                          WRITING
NID_idea_ecb                            X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
NID_idea_ofb64                          X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
NID_info_access                         X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
NID_initials                            X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
NID_invalidity_date                     X509_CHECK_FLAG_NO_WILDCARDS
NID_issuer_alt_name                     X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
NID_keyBag                              X509_CRL_VERSION_1
NID_key_usage                           X509_CRL_VERSION_2
NID_localKeyID                          X509_FILETYPE_ASN1
NID_localityName                        X509_FILETYPE_DEFAULT
NID_md2                                 X509_FILETYPE_PEM
NID_md2WithRSAEncryption                X509_LOOKUP
NID_md5                                 X509_PURPOSE_ANY
NID_md5WithRSA                          X509_PURPOSE_CRL_SIGN
NID_md5WithRSAEncryption                X509_PURPOSE_NS_SSL_SERVER
NID_md5_sha1                            X509_PURPOSE_OCSP_HELPER
NID_mdc2                                X509_PURPOSE_SMIME_ENCRYPT
NID_mdc2WithRSA                         X509_PURPOSE_SMIME_SIGN
NID_ms_code_com                         X509_PURPOSE_SSL_CLIENT
NID_ms_code_ind                         X509_PURPOSE_SSL_SERVER
NID_ms_ctl_sign                         X509_PURPOSE_TIMESTAMP_SIGN
NID_ms_efs                              X509_REQ_VERSION_1
NID_ms_ext_req                          X509_REQ_VERSION_2
NID_ms_sgc                              X509_REQ_VERSION_3
NID_name                                X509_TRUST_COMPAT
NID_netscape                            X509_TRUST_DEFAULT
NID_netscape_base_url                   X509_TRUST_EMAIL
NID_netscape_ca_policy_url              X509_TRUST_OBJECT_SIGN
NID_netscape_ca_revocation_url          X509_TRUST_OCSP_REQUEST
NID_netscape_cert_extension             X509_TRUST_OCSP_SIGN
NID_netscape_cert_sequence              X509_TRUST_SSL_CLIENT
NID_netscape_cert_type                  X509_TRUST_SSL_SERVER
NID_netscape_comment                    X509_TRUST_TSA
NID_netscape_data_type                  X509_VERSION_1
NID_netscape_renewal_url                X509_VERSION_2
NID_netscape_revocation_url             X509_VERSION_3
NID_netscape_ssl_server_name            X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH
NID_ns_sgc                              X509_V_ERR_AKID_SKID_MISMATCH
NID_organizationName                    X509_V_ERR_APPLICATION_VERIFICATION
NID_organizationalUnitName              X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL
NID_pbeWithMD2AndDES_CBC                X509_V_ERR_CA_BCONS_NOT_CRITICAL
NID_pbeWithMD2AndRC2_CBC                X509_V_ERR_CA_CERT_MISSING_KEY_USAGE
NID_pbeWithMD5AndCast5_CBC              X509_V_ERR_CA_KEY_TOO_SMALL
NID_pbeWithMD5AndDES_CBC                X509_V_ERR_CA_MD_TOO_WEAK
NID_pbeWithMD5AndRC2_CBC                X509_V_ERR_CERT_CHAIN_TOO_LONG
NID_pbeWithSHA1AndDES_CBC               X509_V_ERR_CERT_HAS_EXPIRED
NID_pbeWithSHA1AndRC2_CBC               X509_V_ERR_CERT_NOT_YET_VALID
NID_pbe_WithSHA1And128BitRC2_CBC        X509_V_ERR_CERT_REJECTED
NID_pbe_WithSHA1And128BitRC4            X509_V_ERR_CERT_REVOKED
NID_pbe_WithSHA1And2_Key_TripleDES_CBC  X509_V_ERR_CERT_SIGNATURE_FAILURE
NID_pbe_WithSHA1And3_Key_TripleDES_CBC  X509_V_ERR_CERT_UNTRUSTED
NID_pbe_WithSHA1And40BitRC2_CBC         X509_V_ERR_CRL_HAS_EXPIRED
NID_pbe_WithSHA1And40BitRC4             X509_V_ERR_CRL_NOT_YET_VALID
NID_pbes2                               X509_V_ERR_CRL_PATH_VALIDATION_ERROR
NID_pbmac1                              X509_V_ERR_CRL_SIGNATURE_FAILURE
NID_pkcs                                X509_V_ERR_DANE_NO_MATCH
NID_pkcs3                               X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
NID_pkcs7                               X509_V_ERR_DIFFERENT_CRL_SCOPE
NID_pkcs7_data                          X509_V_ERR_EC_KEY_EXPLICIT_PARAMS
NID_pkcs7_digest                        X509_V_ERR_EE_KEY_TOO_SMALL
NID_pkcs7_encrypted                     X509_V_ERR_EMAIL_MISMATCH
NID_pkcs7_enveloped                     X509_V_ERR_EMPTY_SUBJECT_ALT_NAME
NID_pkcs7_signed                        X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL
NID_pkcs7_signedAndEnveloped            X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD
NID_pkcs8ShroudedKeyBag                 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD
NID_pkcs9                               X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD
NID_pkcs9_challengePassword             X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD
NID_pkcs9_contentType                   X509_V_ERR_EXCLUDED_VIOLATION
NID_pkcs9_countersignature              X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3
NID_pkcs9_emailAddress                  X509_V_ERR_HOSTNAME_MISMATCH
NID_pkcs9_extCertAttributes             X509_V_ERR_INVALID_CA
NID_pkcs9_messageDigest                 X509_V_ERR_INVALID_CALL
NID_pkcs9_signingTime                   X509_V_ERR_INVALID_EXTENSION
NID_pkcs9_unstructuredAddress           X509_V_ERR_INVALID_NON_CA
NID_pkcs9_unstructuredName              X509_V_ERR_INVALID_POLICY_EXTENSION
NID_private_key_usage_period            X509_V_ERR_INVALID_PURPOSE
NID_rc2_40_cbc                          X509_V_ERR_IP_ADDRESS_MISMATCH
NID_rc2_64_cbc                          X509_V_ERR_ISSUER_NAME_EMPTY
NID_rc2_cbc                             X509_V_ERR_KEYUSAGE_NO_CERTSIGN
NID_rc2_cfb64                           X509_V_ERR_KEYUSAGE_NO_CRL_SIGN
NID_rc2_ecb                             X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE
NID_rc2_ofb64                           X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA
NID_rc4                                 X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER
NID_rc4_40                              X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER
NID_rc5_cbc                             X509_V_ERR_NO_EXPLICIT_POLICY
NID_rc5_cfb64                           X509_V_ERR_NO_ISSUER_PUBLIC_KEY
NID_rc5_ecb                             X509_V_ERR_NO_VALID_SCTS
NID_rc5_ofb64                           X509_V_ERR_OCSP_CERT_UNKNOWN
NID_ripemd160                           X509_V_ERR_OCSP_VERIFY_FAILED
NID_ripemd160WithRSA                    X509_V_ERR_OCSP_VERIFY_NEEDED
NID_rle_compression                     X509_V_ERR_OUT_OF_MEM
NID_rsa                                 X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA
NID_rsaEncryption                       X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN
NID_rsadsi                              X509_V_ERR_PATH_LENGTH_EXCEEDED
NID_safeContentsBag                     X509_V_ERR_PATH_LOOP
NID_sdsiCertificate                     X509_V_ERR_PERMITTED_VIOLATION
NID_secretBag                           X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED
NID_serialNumber                        X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED
NID_server_auth                         X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION
NID_sha                                 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
NID_sha1                                X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY
NID_sha1WithRSA                         X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH
NID_sha1WithRSAEncryption               X509_V_ERR_STORE_LOOKUP
NID_sha224                              X509_V_ERR_SUBJECT_ISSUER_MISMATCH
NID_sha224WithRSAEncryption             X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL
NID_sha256                              X509_V_ERR_SUBJECT_NAME_EMPTY
NID_sha256WithRSAEncryption             X509_V_ERR_SUBTREE_MINMAX
NID_sha384                              X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256
NID_sha384WithRSAEncryption             X509_V_ERR_SUITE_B_INVALID_ALGORITHM
NID_sha3_224                            X509_V_ERR_SUITE_B_INVALID_CURVE
NID_sha3_256                            X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM
NID_sha3_384                            X509_V_ERR_SUITE_B_INVALID_VERSION
NID_sha3_512                            X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED
NID_sha512                              X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY
NID_sha512WithRSAEncryption             X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE
NID_sha512_224                          X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE
NID_sha512_224WithRSAEncryption         X509_V_ERR_UNABLE_TO_GET_CRL
NID_sha512_256                          X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
NID_sha512_256WithRSAEncryption         X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
NID_shaWithRSAEncryption                X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
NID_shake128                            X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE
NID_shake256                            X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION
NID_stateOrProvinceName                 X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION
NID_subject_alt_name                    X509_V_ERR_UNNESTED_RESOURCE
NID_subject_key_identifier              X509_V_ERR_UNSPECIFIED
NID_surname                             X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX
NID_sxnet                               X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE
NID_time_stamp                          X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE
NID_title                               X509_V_ERR_UNSUPPORTED_NAME_SYNTAX
NID_undef                               X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM
NID_uniqueIdentifier                    X509_V_FLAG_ALLOW_PROXY_CERTS
NID_x509Certificate                     X509_V_FLAG_CB_ISSUER_CHECK
NID_x509Crl                             X509_V_FLAG_CHECK_SS_SIGNATURE
NID_zlib_compression                    X509_V_FLAG_CRL_CHECK
NOTHING                                 X509_V_FLAG_CRL_CHECK_ALL
OCSP_RESPONSE_STATUS_INTERNALERROR      X509_V_FLAG_EXPLICIT_POLICY
OCSP_RESPONSE_STATUS_MALFORMEDREQUEST   X509_V_FLAG_EXTENDED_CRL_SUPPORT
OCSP_RESPONSE_STATUS_SIGREQUIRED        X509_V_FLAG_IGNORE_CRITICAL
OCSP_RESPONSE_STATUS_SUCCESSFUL         X509_V_FLAG_INHIBIT_ANY
OCSP_RESPONSE_STATUS_TRYLATER           X509_V_FLAG_INHIBIT_MAP
OCSP_RESPONSE_STATUS_UNAUTHORIZED       X509_V_FLAG_LEGACY_VERIFY
OPENSSL_BUILT_ON                        X509_V_FLAG_NOTIFY_POLICY
OPENSSL_CFLAGS                          X509_V_FLAG_NO_ALT_CHAINS
OPENSSL_CPU_INFO                        X509_V_FLAG_NO_CHECK_TIME
OPENSSL_DIR                             X509_V_FLAG_PARTIAL_CHAIN
OPENSSL_ENGINES_DIR                     X509_V_FLAG_POLICY_CHECK
OPENSSL_FULL_VERSION_STRING             X509_V_FLAG_POLICY_MASK
OPENSSL_INFO_CONFIG_DIR                 X509_V_FLAG_SUITEB_128_LOS
OPENSSL_INFO_CPU_SETTINGS               X509_V_FLAG_SUITEB_128_LOS_ONLY
OPENSSL_INFO_DIR_FILENAME_SEPARATOR     X509_V_FLAG_SUITEB_192_LOS
OPENSSL_INFO_DSO_EXTENSION              X509_V_FLAG_TRUSTED_FIRST
OPENSSL_INFO_ENGINES_DIR                X509_V_FLAG_USE_CHECK_TIME
OPENSSL_INFO_LIST_SEPARATOR             X509_V_FLAG_USE_DELTAS
OPENSSL_INFO_MODULES_DIR                X509_V_FLAG_X509_STRICT
OPENSSL_INFO_SEED_SOURCE                X509_V_OK
OPENSSL_INIT_ADD_ALL_CIPHERS            XN_FLAG_COMPAT
OPENSSL_INIT_ADD_ALL_DIGESTS            XN_FLAG_DN_REV
OPENSSL_INIT_ASYNC                      XN_FLAG_DUMP_UNKNOWN_FIELDS
OPENSSL_INIT_ATFORK                     XN_FLAG_FN_ALIGN
OPENSSL_INIT_ENGINE_AFALG               XN_FLAG_FN_LN
OPENSSL_INIT_ENGINE_CAPI                XN_FLAG_FN_MASK
OPENSSL_INIT_ENGINE_CRYPTODEV           XN_FLAG_FN_NONE
OPENSSL_INIT_ENGINE_DYNAMIC             XN_FLAG_FN_OID
OPENSSL_INIT_ENGINE_OPENSSL             XN_FLAG_FN_SN
OPENSSL_INIT_ENGINE_PADLOCK             XN_FLAG_MULTILINE
OPENSSL_INIT_ENGINE_RDRAND              XN_FLAG_ONELINE
OPENSSL_INIT_LOAD_CONFIG                XN_FLAG_RFC2253
OPENSSL_INIT_LOAD_CRYPTO_STRINGS        XN_FLAG_SEP_COMMA_PLUS
OPENSSL_INIT_LOAD_SSL_STRINGS           XN_FLAG_SEP_CPLUS_SPC
OPENSSL_INIT_NO_ADD_ALL_CIPHERS         XN_FLAG_SEP_MASK
OPENSSL_INIT_NO_ADD_ALL_DIGESTS         XN_FLAG_SEP_MULTILINE
OPENSSL_INIT_NO_ATEXIT                  XN_FLAG_SEP_SPLUS_SPC
OPENSSL_INIT_NO_LOAD_CONFIG             XN_FLAG_SPC_EQ

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/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)
     or 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/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)
     or 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/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)

INSTALLATION

See README and README.* in the distribution directory for installation guidance on a variety of platforms.

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

LibreSSL versions in the 3.1 - 3.3 series contain a TLS 1.3 implementation that is not fully compatible with the libssl API, but is still advertised during protocol auto-negotiation. If you encounter problems or unexpected behaviour with SSL or SSL_CTX objects whose protocol version was automatically negotiated and libssl is provided by any of these versions of LibreSSL, it could be because the peers negotiated to use TLS 1.3 - try setting the maximum protocol version to TLS 1.2 (via Net::SSLeay::set_max_proto_version() or Net::SSLeay::CTX_set_max_proto_version()) before establishing the connection. The first stable LibreSSL version with a fully libssl-compatible TLS 1.3 implementation is 3.4.1.

An OpenSSL bug CVE-2015-0290 "OpenSSL Multiblock Corrupted Pointer Issue" can cause POST requests of over 90kB to fail or crash. This bug is reported to be fixed in OpenSSL 1.0.2a.

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 https://egd.sourceforge.net/

  2. Pseudo-random number generating daemon (PRNGD) at https://prngd.sourceforge.net/

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)
    or 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/TLS 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
$Net::SSLeay::ssl_version = 11; # Insist on TLSv1.1
$Net::SSLeay::ssl_version = 12; # Insist on TLSv1.2
$Net::SSLeay::ssl_version = 13; # Insist on TLSv1.3

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). 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).

SECURITY

You can mitigate some of the security vulnerabilities that might be present in your SSL/TLS application:

BEAST Attack

The BEAST attack relies on a weakness in the way CBC mode is used in SSL/TLS. In OpenSSL versions 0.9.6d and later, the protocol-level mitigation is enabled by default, thus making it not vulnerable to the BEAST attack.

Solutions:

Net::SSLeay::set_cipher_list($ssl, 'RC4-SHA:HIGH:!ADH');

Session Resumption

The SSL Labs vulnerability test on your SSL server might report in red:

Session resumption No (IDs assigned but not accepted)

This report is not really bug or a vulnerability, since the server will not accept session resumption requests. However, you can prevent this noise in the report by disabling the session cache altogether:

Net::SSLeay::CTX_set_session_cache_mode($ssl_ctx, Net::SSLeay::SESS_CACHE_OFF());
# Use 0 if you don't have SESS_CACHE_OFF constant.

Secure Renegotiation and DoS Attack

This is not a "security flaw," it is more of a DoS vulnerability.

Solutions:

BUGS

If you encounter a problem with this module that you believe is a bug, please create a new issue in the Net-SSLeay GitHub repository. Please make sure your bug report includes the following information:

AUTHOR

Originally written by Sampo Kellomäki.

Maintained by Florian Ragwitz between November 2005 and January 2010.

Maintained by Mike McCauley between November 2005 and June 2018.

Maintained by Tuure Vartiainen between June 2018 and July 2018.

Maintained by Chris Novakovic and Heikki Vatiainen since June 2018.

COPYRIGHT

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

Copyright (c) 2005-2010 Florian Ragwitz <rafl@debian.org>

Copyright (c) 2005-2018 Mike McCauley <mikem@airspayce.com>

Copyright (c) 2018 Tuure Vartiainen <vartiait@radiatorsoftware.com>

Copyright (c) 2018- Chris Novakovic <chris@chrisn.me.uk>

Copyright (c) 2018- Heikki Vatiainen <hvn@radiatorsoftware.com>

All rights reserved.

LICENSE

This module is released under the terms of the Artistic License 2.0. For details, see the LICENSE file distributed with Net-SSLeay's source code.

SEE ALSO

Net::SSLeay::Handle                      - File handle interface
./examples                               - Example servers and a clients
<https://www.openssl.org/>               - OpenSSL source, documentation, etc
openssl-users-request@openssl.org        - General OpenSSL mailing list
<https://www.ietf.org/rfc/rfc2246.txt>   - TLS 1.0 specification
<https://www.w3c.org>                    - HTTP specifications
<https://www.ietf.org/rfc/rfc2617.txt>   - How to send password
<https://egd.sourceforge.net/>           - Entropy Gathering Daemon (EGD)
<https://prngd.sourceforge.net/>         - pseudo-random number generating daemon (PRNGD)
perl(1)
perlref(1)
perllol(1)
perldoc ~openssl/doc/ssl/SSL_CTX_set_verify.pod