=encoding utf-8
=head1 NAME
Net::SSLeay - Perl bindings for OpenSSL and LibreSSL
=head1 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
=head1 DESCRIPTION
This module provides Perl bindings for libssl (an SSL/TLS API) and libcrypto (a
cryptography API).
=head1 COMPATIBILITY
Net::SSLeay supports the following libssl implementations:
=over
=item *
Any stable release of L in the 0.9.8 - 3.2
branches, except for OpenSSL 0.9.8 - 0.9.8b.
=item *
Any stable release of L in the 2.0 - 3.8
series, except for LibreSSL 3.2.2 and 3.2.3.
=back
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 B 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
L
and L 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(...);
}
=head1 OVERVIEW
L module basically comprise of:
=over
=item * High level functions for accessing web servers (by using HTTP/HTTPS)
=item * Low level API (mostly mapped 1:1 to openssl's C functions)
=item * Convenience functions (related to low level API but with more perl friendly interface)
=back
There is also a related module called L included in this
distribution that you might want to use instead. It has its own pod
documentation.
=head2 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 C 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.
=head3 Basic set of functions
=over
=item * get_https
=item * post_https
=item * put_https
=item * head_https
=item * do_https
=item * sslcat
=item * https_cat
=item * make_form
=item * make_headers
=back
B 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 L.
B demonstrates full fledged use of C. As can be seen,
C 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 C is used to insert some additional headers
in the request. C is a function that will convert a list or
hash to such headers. By default C supplies C (to make
virtual hosting easy) and C (reportedly needed by IIS) headers.
B demonstrates how to get a password protected page. Refer to
the HTTP protocol specifications for further details (e.g. RFC-2617).
B invokes C to submit a HTML/CGI form to a secure
server. The first four arguments are equal to C (note that
the empty string (C<''>) 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 C is used to do the formatting,
but you could pass any string. C automatically adds
C and C headers to the request.
B shows the fundamental C function (inspired in spirit by
the C 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 -
C is just a transport.
B is a full invocation of C which allows the return of errors
as well as the server (peer) certificate.
The C<$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.
=head3 Alternate versions of high-level API
=over
=item * get_https3
=item * post_https3
=item * put_https3
=item * get_https4
=item * post_https4
=item * put_https4
=back
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 L and L 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 C 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 C
for guidance on how to do this.
=head3 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
);
B demonstrates getting a password protected page that also requires
a client certificate, i.e. it is possible to use both authentication
methods simultaneously.
B 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 C on the
server:
Net::SSLeay::set_verify($ssl, Net::SSLeay::VERIFY_PEER, 0);
See C for a full description.
=head3 Working through a web proxy
=over
=item * set_proxy
=back
C can use a web proxy to make its connections. You need to
first set the proxy host and port using C 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
C<"joe"> and to the final web server as C<"susie">. Proxy authentication
requires the C module to work.
=head3 HTTP (without S) API
=over
=item * get_http
=item * post_http
=item * tcpcat
=item * get_httpx
=item * post_httpx
=item * tcpxcat
=back
Over the years it has become clear that it would be convenient to use
the light-weight flavour API of C for normal HTTP as well (see
C 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 C<"x"> family of APIs takes as the first argument a flag
which indicates whether SSL is used or not.
=head2 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 C 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 C<.r0>, C<.r1> etc. For example
C, C. 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).
=head2 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
...
}
=head2 Using Net::SSLeay in multi-threaded applications
B
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 L).
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:
=head3 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 C function (which is also aliased as
C, C and C)
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.
=head3 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.
=head3 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);
=head3 Using other perl modules based on Net::SSLeay
It should be fine to use any other module based on L (like L)
in multi-threaded applications. It is generally recommended to do any global initialization
of such a module in the main thread before calling C<< threads->new(..) >> or
C<< 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();
}
=head3 Combining Net::SSLeay with other modules linked with openssl
B
There are many other (XS) modules linked directly to openssl library (like L).
As it is expected that also "another" module will call C 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).
=head3 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.
=head2 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);
=over
=item * randomize
seeds the openssl PRNG with C (see the top of C
for how to change or configure this) and optionally with user provided
data. It is very important to properly seed your random numbers, so
do not forget to call this. The high level API functions automatically
call C so it is not needed with them. See also caveats.
=item * set_cert_and_key
takes two file names as arguments and sets
the certificate and private key to those. This can be used to
set either server certificates or client certificates.
=item * dump_peer_certificate
allows you to get a plaintext description of the
certificate the peer (usually the server) presented to us.
=item * ssl_read_all
see ssl_write_all (below)
=item * ssl_write_all
C and C provide true blocking semantics for
these operations (see limitation, below, for explanation). These are
much preferred to the low level API equivalents (which implement BSD
blocking semantics). The message argument to C can be
a reference. This is helpful to avoid unnecessary copying when writing
something big, e.g:
$data = 'A' x 1000000000;
Net::SSLeay::ssl_write_all($ssl, \$data) or die "ssl write failed";
=item * ssl_read_CRLF
uses C to read in a line terminated with a
carriage return followed by a linefeed (CRLF). The CRLF is included in
the returned scalar.
=item * ssl_read_until
uses C to read from the SSL input
stream until it encounters a programmer specified delimiter.
If the delimiter is undefined, C<$/> is used. If C<$/> is undefined,
C<\n> is used. One can optionally set a maximum length of bytes to read
from the SSL input stream.
=item * ssl_write_CRLF
writes C<$message> and appends CRLF to the SSL output stream.
=back
=head2 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();
=head2 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.
=over
=item * die_now
=item * die_if_ssl_error
C and C are used to conveniently print the SSLeay error
stack when something goes wrong:
Net::SSLeay::connect($ssl) or die_now("Failed SSL connect ($!)");
Net::SSLeay::write($ssl, "foo") or die_if_ssl_error("SSL write ($!)");
=item * print_errs
You can also use C to dump the error stack without
exiting the program. As can be seen, your code becomes much more readable
if you import the error reporting functions into your main name space.
=back
=head2 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 C to extract the underlying file descriptor:
Net::SSLeay::set_fd($ssl, fileno(S)); # Must use fileno
You should also set C<$|> 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 C