How to verify DKIM signatures manually


October 2014.
Posted 2014-10-31.
Image Image Image

Situation


You're setting up DKIM on your SMTP servers. You'd like to be able to check if your emails are signed correctly.

Using perl


Use Mail::DKIM::Verifier.

As per the documentation:

use Mail::DKIM::Verifier;

# create a verifier object
my $dkim = Mail::DKIM::Verifier->new();

# read an email from a file handle
#$dkim->load(*STDIN);

# or read an email and pass it into the verifier, incrementally
while ()
{
# remove local line terminators
chomp;
s/\015$//;

# use SMTP line terminators
$dkim->PRINT("$_\015\012");
}
$dkim->CLOSE;

# what is the result of the verify?
my $result = $dkim->result;

# there might be multiple signatures, what is the result per signature?
foreach my $signature ($dkim->signatures)
{
print "signature identity: " . $signature->identity . "\n";
print "verify result: " . $signature->result_detail . "\n";
}

# the alleged author of the email may specify how to handle email
foreach my $policy ($dkim->policies)
{
die "fraudulent message" if ($policy->apply($dkim) eq "reject");
}

Usage:

perl dkim_checker.pl < good_email.eml
signature identity: @example.com
verify result: pass

perl test.pl < bad_email.eml
signature identity: @example.com
verify result: fail (bad RSA signature)

Using PHP


Download php-dkim and phpseclib into the same folder.

Write a sample code to use the classes:


set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
require_once("DKIM/Verify.php");

$email = file_get_contents('php://stdin');
$dkim_verify = new DKIM_Verify($email);
$r = $dkim_verify->validate();
print_r($r);

Usage:

php dkim_checker.php < good_email.eml
Array
(
[0] => Array
(
[0] => Array
(
[status] => pass
[reason] => Success!
)

)

)

php dkim_checker.php < bad_email.eml
Notice: Invalid signature in /root/dkim/php-dkim-master/phpseclib/Crypt/RSA.php on line 2757
Array
(
[0] => Array
(
[0] => Array
(
[status] => permfail
[reason] => signature did not verify (example.com key #0)
)

)

)

Using python


Install pydkim.

cd dkimpy-0.5.4 && python setup.py install

Usage:

/usr/local/bin/dkimverify.py < good_email.eml
signature ok

/usr/local/bin/dkimverify.py < bad_email.eml
signature verification failed