Crypt-MatrixSSL3

 view release on metacpan or  search on metacpan

lib/Crypt/MatrixSSL3.pm  view on Meta::CPAN


=item *

Perl array reference with file names of SCT binary structures that the
function will use to create the extension data.

=back

=back

Returns the number of files loaded (if this is 0 there was an error loading one of the files).

=head2 refresh_ALPN_data

    $num_protocols = refresh_ALPN_data( $server_index, $index, $protocols );

Used to refresh the application protocols for a default server or for a virtual host.

Parameters:

=over

=item $server_index and $index

Are the same as refresh_OCSP_staple above.

=item $protocols

=over

=item *

Perl array reference containing the new protocols.

=back

Returns the number of protocols you supplied (if this is 0 there was an error loading one of the files).

=back

Returns the number of files loaded in order to build extension data.

=head2 set_VHIndex_callback

    set_VHIndex_callback( \&VHIndexCallback );

More information about L</VHIndexCallback> in the L</CALLBACKS> section.

=head2 set_ALPN_callback

    set_ALPN_callback( \&ALPNCallback );

More information about L</ALPNCallback> in the L</CALLBACKS> section.

=head2 create_SSL_server

    $server_index = create_SSL_server();

Tells the XS module to allocate a new server structure. The returned index
must be saved and then used one time to initialize the server structure and then
each time a new client connection is accepted in order to set SNI/ALPN callbacks.

=head1 CLASSES

Constructors for all classes will throw exception on error instead of
returning error as matrixSslNew*() functions do. Exception will be
thrown using C< croak($return_code) >, so to get $return_code from $@
you should convert it back to number:

    eval { $client = Crypt::MatrixSSL3::Client->new(...) };
    $rc = 0+$@ if $@;


=head2 Crypt::MatrixSSL3::Keys

=head3 new

    $keys = Crypt::MatrixSSL3::Keys->new();

    matrixSslNewKeys( $keys )

Return new object $keys.
Throw exception if matrixSslNewKeys() doesn't return PS_SUCCESS.
When this object will be destroyed will call:

    matrixSslDeleteKeys( $keys )

=head3 load_rsa

    $rc = $keys->load_rsa( $certFile,
        $privFile, $privPass, $trustedCAcertFiles );

    matrixSslLoadRsaKeys( $keys, $certFile,
        $privFile, $privPass, $trustedCAcertFiles )

=head3 load_rsa_mem

    $rc = $keys->load_rsa_mem( $cert, $priv, $trustedCA );

    matrixSslLoadRsaKeysMem( $keys, $cert, length $cert,
        $priv, length $priv, $trustedCA, length $trustedCA )

=head3 load_ecc

    $rc = $keys->load_ecc( $certFile,
        $privFile, $privPass, $trustedCAcertFiles );

    matrixSslLoadEcKeys( $keys, $certFile,
        $privFile, $privPass, $trustedCAcertFiles )

=head3 load_rsa_mem

    $rc = $keys->load_ecc_mem( $cert, $priv, $trustedCA );

    matrixSslLoadEcKeysMem( $keys, $cert, length $cert,
        $priv, length $priv, $trustedCA, length $trustedCA )

=head3 load_pkcs12

    $rc = $keys->load_pkcs12( $p12File, $importPass, $macPass, $flags );

lib/Crypt/MatrixSSL3.pm  view on Meta::CPAN

        $haskkey, length $hashkey )

=head3 load_OCSP_response

    $rc = $keys->load_OCSP_response( $OCSP_file );

    matrixSslLoadOCSPResponse ( $keys, $OCSPResponse, $OCSPResponseLen )

=head3 load_SCT_response

    $rc = $keys->load_SCT_response( $SCT_params );

    matrixSslLoadSCTResponse ( $keys, $SCTResponse, $SCTResponseLen )


B<Server side.>


=head2 Crypt::MatrixSSL3::SessID

=head3 new

    $sessID = Crypt::MatrixSSL3::SessID->new();

Return new object $sessID representing (sslSessionId_t*) type.
Throw exception if failed to allocate memory.
When this object will be destroyed will free memory, so you should
keep this object while there are still Client/Server session
which use this $sessID.

=head3 clear

    $sessID->clear();

    matrixSslClearSessionId($sessID)


=head2 Crypt::MatrixSSL3::Client

=head3 new

    $ssl = Crypt::MatrixSSL3::Client->new(
        $keys, $sessID, \@cipherSuites,
        \&certValidator, $expectedName,
        $extensions, \&extensionCback,
    );

    matrixSslNewClientSession( $ssl,
        $keys, $sessID, \@cipherSuites,
        \&certValidator, $expectedName,
        $extensions, \&extensionCback,
    )

Return new object $ssl.
Throw exception if matrixSslNewClientSession() doesn't return
MATRIXSSL_REQUEST_SEND.
When this object will be destroyed will call:

    matrixSslDeleteSession( $ssl )

More information about callbacks L</certValidator> and L</extensionCback>
in the L</CALLBACKS> section.


=head2 Crypt::MatrixSSL3::Server

=head3 new

    $ssl = Crypt::MatrixSSL3::Server->new( $keys, \&certValidator );

    matrixSslNewServerSession( $ssl, $keys, \&certValidator )

Return new object $ssl.
Throw exception if matrixSslNewServerSession() doesn't return PS_SUCCESS.
When this object will be destroyed will call:

    matrixSslDeleteSession( $ssl )

More information about callback L</certValidator> in the L</CALLBACKS> section.

=head3 init_SNI

    $ssl->init_SNI( $sserver_index, $sni_params );

This function should be called only once when the server is initialized.

Parameters:

=over

=item $server_index

Server structure index returned by C<create_SSL_server()>

=item $sni_params [{...},...] or undef

This is a reference to an array that contains one or more array references:

    $sni_params = [                                                     # virtual hosts support - when a client sends a TLS SNI extension, the settings below will apply
                                                                        #                         based on the requested hostname
        # virtual host 0 (also referred in the code as SNI entry 0)
        {
            'hostname' => 'hostname',                                   # regular expression for matching the hostname
            'cert' => '/path/to/certificate;/path/to/CA-chain',         # KEY - certificate (the CA-chain is optional)
            'key' => '/path/to/private_key',                            # KEY - private key
            'DH_param' => /path/to/DH_params',                          # KEY - file containing the DH parameter used with DH ciphers
            'session_ticket_keys' => {                                  # session tickets setup
                'id' => '1234567890123456',                             # KEY - TLS session tickets - 16 bytes unique identifier
                'encrypt_key' => '12345678901234567890123456789012',    # KEY - TLS session tickets - 128/256 bit encryption key
                'hash_key' => '12345678901234567890123456789012',       # KEY - TLS session tickets - 256 bit hash key
            },
            'OCSP_staple' => '/path/to/OCSP_staple.der',                # SESSION - file containing a OCSP staple that gets sent when a client
                                                                        #           send a TLS status request extension
            'SCT_params' => [                                           # SESSION - Certificate Transparency SCT files used to build the
                                                                        #           'signed_certificate_timestamp' TLS extension data buffer
                '/path/to/SCT1.sct',
                '/path/to/SCT2.sct',
                ...
            ],
            # instead of the Certificate Transparency SCT files you can specify a scalar with a single file that contains multiple SCT files
            # note that this file is not just a concatenation of the SCT files, but a ready-to-use 'signed_certificate_timestamp' TLS extension data buffer
            # see ct-submit.pl for more info
            #'SCT_params' => '/path/to/CT_extension_data_buffer',
            'ALPN' => ['protocol1', 'protocol2']                        # SESSION - server supported protocols
        },
        # virtual host 1
        ...
    ]

=back

=head3 set_server_params

    $ssl->set_server_params( $server_index, $sv_params );

Used to set the server supported protocols used when a client send a TLS
ALPN extension.

Note that this function call only affects the B<default server>. Virtual
hosts are managed by using the $ssl->init_SNI(...).

See $ssl->init_SNI(...) for usage.

Parameters:

=over

=item $server_index

Server structure index returned by C<create_SSL_server()>

=item $sv_params {...} or undef

This is a reference to a hash with the following structure (all keys are optional):

    $sv_params = {
        'ALPN' => ['protocol1', 'protocol2']
    }

If you specify the 'ALPN' parameter, you should also provide
an ALPN callback. More information about callback L</ALPNCallback>
in the L</CALLBACKS> section.

=back

=head3 set_callbacks

    $ssl->set_callbacks( $server_index, $ssl_id );

Parameters:

=over

=item $server_index

Server structure index returned by C<create_SSL_server()>

=item $ssl_id

A 32 bit integer that uniquely identifies this session. This parameter
will be sent back when MatrixSSL calls the SNI callback defined in the XS
module when a client sends a SNI extension.
If the XS module is able to match the requested client hostname it will
call the Perl callback set with set_VHIndex_callback.

=back

=head2 Crypt::MatrixSSL3::Client and Crypt::MatrixSSL3::Server

=head3 get_outdata

    $rc = $ssl->get_outdata( $outBuf );

Unlike C API, it doesn't set $outBuf to memory location inside MatrixSSL,
but instead it append buffer returned by C API to the end of $outBuf.

    matrixSslGetOutdata( $ssl, $tmpBuf )
    $outBuf .= $tmpBuf

Throw exception if matrixSslGetOutdata() returns < 0.

=head3 sent_data

    $rc = $ssl->sent_data( $bytes );

    matrixSslSentData( $ssl, $bytes )

=head3 received_data

    $rc = $ssl->received_data( $inBuf, $ptBuf );

    $n = matrixSslGetReadbuf( $ssl, $buf )
    $n = min($n, length $inBuf)
    $buf = substr($inBuf, 0, $n, q{})
    matrixSslReceivedData( $ssl, $n, $ptBuf, $ptLen )

Combines two calls: matrixSslGetReadbuf() and matrixSslReceivedData().
It copy data from beginning of $inBuf into buffer returned by
matrixSslGetReadbuf() and cut copied data from beginning of $inBuf (it may
copy less bytes than $inBuf contain if size of buffer provided by
MatrixSSL will be smaller).
Then it calls matrixSslReceivedData() to get $rc and may fill $ptBuf with
received alert or application data.

It is safe to call it with empty $inBuf, but this isn't a good idea
performance-wise.

Throw exception if matrixSslGetReadbuf() returns <= 0.

lib/Crypt/MatrixSSL3.pm  view on Meta::CPAN

    matrixSslLoadHelloExtension( $extension, $ext, length $ext, $extType )


=head1 CALLBACKS

=head2 certValidator

Will be called with two scalar params: $certInfo and $alert
(unlike C callback which also have $ssl param).

Param $certInfo instead of (psX509Cert_t *) will contain reference to
array with certificates. Each certificate will be hash in this format:

    notBefore       => $notBefore,
    notAfter        => $notAfter,
    subjectAltName  => {
        dns             => $dns,
        uri             => $uri,
        email           => $email,
    },
    subject        => {
        country         => $country,
        state           => $state,
        locality        => $locality,
        organization    => $organization,
        orgUnit         => $orgUnit,
        commonName      => $commonName,
    },
    issuer         => {
        country         => $country,
        state           => $state,
        locality        => $locality,
        organization    => $organization,
        orgUnit         => $orgUnit,
        commonName      => $commonName,
    },
    authStatus     => $authStatus,

This callback must return single scalar with integer value (as described in
MatrixSSL documentation). If callback die(), then warning will be printed,
and execution will continue assuming callback returned -1.

=head2 extensionCback

Will be called with two scalar params: $type and $data
(unlike C callback which also have $ssl and length($data) params).

This callback must return single scalar with integer value (as described in
MatrixSSL documentation). If callback die(), then warning will be printed,
and execution will continue assuming callback returned -1.

=head2 ALPNCallback

Will be called when a client sends an ALPN extension and a successful
application protocol has been negotiated. If the server doesn't implement
any of the client's protocols the XS module will send an appropriate
response and the client will receive a SSL_ALERT_NO_APP_PROTOCOL alert.

Will be called with 2 parameters:

    $ssl_id - this is the $ssl_id used in the $ssl->set_callbacks(...) call
    $app_proto - scalar with the negociated protocol name

=head2 VHIndexCallback

Will be called whenever we have a successful match against the hostname
specified by the client in its SNI extension. This will inform the Perl
code which virtual host the current SSL session belongs to.

Will be called with 3 parameters:

    $ssl_id - this is the $ssl_id used in the $ssl->set_callbacks(...) call
    $index - a 0-based int specifying which virtual host matchd the client requested hostname
    $match - a scalar containing the hostname sent in the client's SNI TLS extension

Doesn't return anything.


=head1 HOWTO: Certificate Transparency

=head2 PREREQUISITES

For generating Certificate Transparency files you will need the following:

=head3 Certificates

=over

=item *

Server certificate (server.crt)

=item *

Issuer certificate (issuer.crt)

=item *

Certificate Authority chain (server-CA.crt) - this includes any number of
intermediate certificate and optionally ends with the root certificate.

=back

=head2 USING THE ct-submit.pl TOOL

=head3 Generate one file containing SCTs from all CT log servers

    ct-submit.pl --pem server.crt --pem issuer.crt --pem server-CA.pem \
        --extbuf /path/to/CT.sct

The resulted file can be used in your script like:

    # set or refresh CT response for a SSL session (default server)
    $sv_keys->load_SCT_response('/path/to/CT.sct');


=head3 Generate multiple SCT files containing binary representation of the responses received from the log servers

    ct-submit.pl --pem server.crt --pem issuer.crt --pem server-CA.pem \
        --individual /path/to/sct/

This will create in the /path/to/stc/ folder the following files
(considering that the requests to the log servers were successful):

    aviator.sct          # https://ct.googleapis.com/aviator
    certly.sct           # https://log.certly.io
    pilot.sct            # https://ct.googleapis.com/pilot
    rocketeer.sct        # https://ct.googleapis.com/rocketeer
    digicert.sct         # https://ct1.digicert-ct.com/log - disabled by default -
                         # accepts certificates only from select CAs
    izenpe.sct           # https://ct.izenpe.com - disabled by default -
                         # accepts certificates only from select CAs

lib/Crypt/MatrixSSL3.pm  view on Meta::CPAN

    $server_sock = ...

    # initialize default server keys - these will be shared by all server sessions
    my $sv_keys = Crypt::MatrixSSL3::Keys->new();

    # load key material (certificate, private key, etc)
    $sv_keys->load_rsa(...);

    # load OCSP response
    $sv_keys->load_OCSP_response(...);

    # load SCT response
    $sv_keys->load_SCT_response(...);

    ...

    # we assume when a client connects an accept_client sub will be called
    sub accept_client {
        # accept client socket
        my $client_sock = accept($server_sock, ...);

        # create server session reusing the keys
        my $cssl =  Crypt::MatrixSSL3::Server->new($sv_keys, undef);

        # create a unique SSL session ID
        # for example this can be the fileno of the client socket
        my $ssl_id = fileno($client_sock);

        # check if the server parameters are initialized
        if ($server_index == -1) {
            # tell the XS module to allocate a new SSL server structure
            $server_index = Crypt::MatrixSSL3::create_SSL_server();

            # set supported protocols for the default server.
            $ssl->set_server_params($server_index, {
                'ALPN' => [...]
            });

            # initialize virtual hosts:
            #   - allocates a SNI_entry structure for each virtual host and:
            #     - creates new server keys
            #     - sets up OCSP staple buffer (server keys - if needed)
            #     - sets up SCT buffer (server keys - if needed)
            #     - stores server implemented protocols if provided
            $ssl->init_SNI($server_index, [
                # see MatrixSSL.pm - init_SNI function
            ]);
        }

        # setup SNI/ALPN callback

        # sets up the matrixSSL SNI callback that will get called if the client sends a SNI TLS extension
        # in its CLIENT_HELLO message. When the XS SNI callback is called if any of the hostnames defined
        # for each virtual host matches againt the client requested hostname, the &VHIndexCallback setup
        # above will be called with the $ssl_id of the session and the 0-based index of the virtual host
        # the client sent its request

        # sets up the matrixSSL ALPN callback that will get called when the client sends an ALPN extension
        # the &ALPNCallback is called with the provided $ssl_id and the selected protocol

        $cssl->set_callbacks($server_index, $sll_id);

        # further initialization stuff after accepting the client
        ...
    }

    # secure communication with the client
    ...


=head1 SEE ALSO

http://www.MatrixSSL.org - the download from this site includes
simple yet comprehensive documentation in PDF format.


=head1 SUPPORT

=head2 Bugs / Feature Requests

Please report any bugs or feature requests through the issue tracker
at L<https://github.com/powerman/perl-Crypt-MatrixSSL3/issues>.
You will be notified automatically of any progress on your issue.

=head2 Source Code

This is open source software. The code repository is available for
public review and contribution under the terms of the license.
Feel free to fork the repository and submit pull requests.

L<https://github.com/powerman/perl-Crypt-MatrixSSL3>

    git clone https://github.com/powerman/perl-Crypt-MatrixSSL3.git

=head2 Resources

=over

=item * MetaCPAN Search

L<https://metacpan.org/search?q=Crypt-MatrixSSL3>

=item * CPAN Ratings

L<http://cpanratings.perl.org/dist/Crypt-MatrixSSL3>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Crypt-MatrixSSL3>

=item * CPAN Testers Matrix

L<http://matrix.cpantesters.org/?dist=Crypt-MatrixSSL3>

=item * CPANTS: A CPAN Testing Service (Kwalitee)

L<http://cpants.cpanauthors.org/dist/Crypt-MatrixSSL3>

=back




( run in 0.696 second using v1.01-cache-2.11-cpan-5b529ec07f3 )