sub get_smime_result()

in smime-signature-validator/handler.pl [42:95]


sub get_smime_result {
    my $signed_mime = shift;
    my $smime = Crypt::SMIME->new();
    my %result = ();
    
    # is the message even signed
    $result{signed} = ($smime->isSigned($signed_mime) ? "true" : "false");
    $result{encrypted} = ($smime->isEncrypted($signed_mime) ? "true" : "false");
    return \%result if ( $result{signed} ne 'true' );
    
    # check the S/MIME signature to see if it looks parsable
    eval{ return $smime->check($signed_mime, Crypt::SMIME::NO_CHECK_CERTIFICATE) };
    $result{check} = $@ ? $@ : "ok";
    return \%result if ( $result{check} ne 'ok' );
    
    # check the S/MIME signature chain
    # CA certificates stored in S3 and managed by you - whomever you choose to trust
    if ( ! -e '/tmp/keystore' and $ENV{CACERT_BUCKET} and $ENV{CACERT_KEY} ) {
        my $cacert = get_s3_object($ENV{CACERT_BUCKET}, $ENV{CACERT_KEY});
        if ( $cacert ) {
            open my $fh, '>', '/tmp/keystore' or die $!;
            print $fh $cacert;
            close $fh;
            warn "Loaded CA keystore from s3://$ENV{CACERT_BUCKET}/$ENV{CACERT_KEY}\n";
        }
    }
    if ( -e '/tmp/keystore' ) {
        eval { $smime->setPublicKeyStore('/tmp/keystore') };
        if ( $@ ) {
            warn "failed to setPublicKeyStore: $@\n";
        }
    }
    else {
        warn "No CA keystore available\n";
    }
    eval{ return $smime->check($signed_mime) };
    $result{check_chain} = $@ ? $@ : "ok";
    
    # get the S/MIME signer details
    my @signers = eval { @{Crypt::SMIME::getSigners($signed_mime)} };
    unless ( $@ ) {
        for ( @signers ) {
            my $i = 0;
            my $x509 = Crypt::OpenSSL::X509->new_from_string($_);
            for my $attribute ( qw(pubkey subject hash email issuer issuer_hash notBefore notAfter modulus exponent fingerprint_md5 fingerprint_sha256 as_string) ) {
                $result{signers}[$i]{$attribute} = $x509->$attribute();
            }
            $i++;
        }
    }
    
    # return the S/MIME details collected
    return \%result;
}