SSL Certificates

Verifying your peer using SSL certificate

my $ctx = Net::SSLeay::CTX_new();
my $cert_file = "/usr/share/ssl/certs/ca-bundle.crt";
my $cert_path = "/usr/share/ssl/certs/";
Net::SSLeay::CTX_load_verify_locations( $ctx, $cert_file, $cert_path );
my $ssl = Net::SSLeay::new( $ctx );
Net::SSLeay::set_fd( $ssl, $fileno );
Net::SSLeay::set_verify ( $ssl, &Net::SSLeay::VERIFY_PEER, 0 );
Net::SSLeay::connect( $ssl );
my $cert_error = Net::SSLeay::get_verify_result( $ssl );
my $peer_cert = Net::SSLeay::get_peer_certificate( $ssl );
my $cert_subject_name = Net::SSLeay::X509_get_subject_name( $peer_cert );
my $cert_subject = Net::SSLeay::X509_NAME_oneline( $cert_subject_name );
my $peer_name = $cert_subject =~ m{CN=([^/]*)}sio;
Net::SSLEay::X509_free( $peer_cert );

If $cert_error != 0, the certificate did not authenticate properly against the trusted certificates in $cert_file and $cert_path. If $peer_name does not match the host you are trying to connect to, then the certificate may be valid but is not being used on the host it belongs to. You need to call X509_free() at the end, otherwise there will be a memory leak.

ca-bundle.crt is found in the mod_ssl package, though the version is rather old. A better way to get the certificates may be the ca-certificates Debian package from debian.org. To install on a non .deb system, you can download the tar.gz file, unpack it and run make (it requires the ruby interpreter). Then copy the files from the /mozilla directory into your $cert_path.