smime_keys.pl 25.7 KB
Newer Older
1
#! /usr/bin/perl -w
2

3
# Copyright (C) 2001,2002 Oliver Ehli <elmy@acm.org>
4
# Copyright (C) 2001 Mike Schiraldi <raldi@research.netsol.com>
5
# Copyright (C) 2003 Bjoern Jacke <bjoern@j3e.de>
6 7 8 9 10 11 12 13 14 15 16 17 18
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
# 
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
# 
#     You should have received a copy of the GNU General Public License
#     along with this program; if not, write to the Free Software
19
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 21

use strict;
22
use File::Copy;
23
use File::Glob ':glob';
24

25 26
umask 077;

27
use Time::Local;
28 29

sub usage ();
30
sub newfile ($;$$);
31
sub mutt_Q ($ );
32
sub mycopy ($$);
33 34

#  directory setup routines
35
sub mkdir_recursive ($ );
36 37 38 39 40
sub init_paths ();

# key/certificate management methods
sub list_certs ();
sub query_label ();
41
sub add_entry ($$$$$ );
42 43
sub add_certificate ($$$$;$ );
sub add_key ($$$$);
44
sub add_root_cert ($ );
45 46 47 48 49
sub parse_pem (@ );
sub handle_pem (@ );
sub modify_entry ($$$;$ );
sub remove_pair ($ );
sub change_label ($ );
50 51
sub verify_cert($$);
sub do_verify($$$ );
52
              
53 54
# Get the directories mutt uses for certificate/key storage.

55
my $mutt = $ENV{MUTT_CMDLINE} || 'mutt';
56
my $opensslbin = "/usr/bin/openssl";
57 58
my @tempfiles = ();
my @cert_tmp_file = ();
59

60
my $tmpdir;
61
my $private_keys_path = mutt_Q 'smime_keys';
62 63 64
die "smime_keys is not set in mutt's configuration file"
	if length $private_keys_path == 0;

65
my $certificates_path = mutt_Q 'smime_certificates';
66 67
die "smime_certificates is not set in mutt's configuration file"
	if length $certificates_path == 0;
68
my $root_certs_path   = mutt_Q 'smime_ca_location';
69 70 71
die "smime_ca_location is not set in mutt's configuration file"
	if length $root_certs_path == 0;

72 73 74 75 76 77
my $root_certs_switch;
if ( -d $root_certs_path) {
	$root_certs_switch = -CApath;
} else {
	$root_certs_switch = -CAfile;
}
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93


#
# OPS
#

if(@ARGV == 1 and $ARGV[0] eq "init") {
    init_paths;
}
elsif(@ARGV == 1 and $ARGV[0] eq "list") {
    list_certs;
}
elsif(@ARGV == 2 and $ARGV[0] eq "label") {
    change_label($ARGV[1]);
}
elsif(@ARGV == 2 and $ARGV[0] eq "add_cert") {
94
    my $format = -B $ARGV[1] ? 'DER' : 'PEM'; 
95
    my $cmd = "$opensslbin x509 -noout -hash -in $ARGV[1] -inform $format";
96 97 98 99
    my $cert_hash = `$cmd`;
    $? and die "'$cmd' returned $?";
    chomp($cert_hash); 
    my $label = query_label;
Thomas Roessler's avatar
Thomas Roessler committed
100
    &add_certificate($ARGV[1], \$cert_hash, 1, $label, '?');
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
}
elsif(@ARGV == 2 and $ARGV[0] eq "add_pem") {
    -e $ARGV[1] and -s $ARGV[1] or die("$ARGV[1] is nonexistent or empty.");
    open(PEM_FILE, "<$ARGV[1]") or die("Can't open $ARGV[1]: $!");
    my @pem = <PEM_FILE>;
    close(PEM_FILE);
    handle_pem(@pem);
}
elsif( @ARGV == 2 and $ARGV[0] eq "add_p12") {
    -e $ARGV[1] and -s $ARGV[1] or die("$ARGV[1] is nonexistent or empty.");

    print "\nNOTE: This will ask you for two passphrases:\n";
    print "       1. The passphrase you used for exporting\n";
    print "       2. The passphrase you wish to secure your private key with.\n\n";

    my $pem_file = "$ARGV[1].pem";
    
118
    my $cmd = "$opensslbin pkcs12 -in $ARGV[1] -out $pem_file";
119 120 121 122 123 124
    system $cmd and die "'$cmd' returned $?";
    
    -e $pem_file and -s $pem_file or die("Conversion of $ARGV[1] failed.");
    open(PEM_FILE, $pem_file) or die("Can't open $pem_file: $!");
    my @pem = <PEM_FILE>;
    close(PEM_FILE);
125
    unlink $pem_file;
126 127 128
    handle_pem(@pem);
}
elsif(@ARGV == 4 and $ARGV[0] eq "add_chain") {
129
    my $mailbox;
130
    my $format = -B $ARGV[2] ? 'DER' : 'PEM'; 
131
    my $cmd = "$opensslbin x509 -noout -hash -in $ARGV[2] -inform $format";
132
    my $cert_hash = `$cmd`;
133

134
    $? and die "'$cmd' returned $?";
135 136 137

    $format = -B $ARGV[3] ? 'DER' : 'PEM'; 

138
    $cmd = "$opensslbin x509 -noout -hash -in $ARGV[3] -inform $format";
139 140 141 142 143 144 145 146 147
    my $issuer_hash = `$cmd`;
    $? and die "'$cmd' returned $?";
    
    chomp($cert_hash); 
    chomp($issuer_hash);

    my $label = query_label;
    
    add_certificate($ARGV[3], \$issuer_hash, 0, $label); 
148
    my @mailbox = &add_certificate($ARGV[2], \$cert_hash, 1, $label, $issuer_hash);
149
    
150 151 152 153
    foreach $mailbox (@mailbox) {
      chomp($mailbox);
      add_key($ARGV[1], $cert_hash, $mailbox, $label);
    }
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}
elsif((@ARGV == 2 or @ARGV == 3) and $ARGV[0] eq "verify") {
    verify_cert($ARGV[1], $ARGV[2]);
}
elsif(@ARGV == 2 and $ARGV[0] eq "remove") {
    remove_pair($ARGV[1]);
}
elsif(@ARGV == 2 and $ARGV[0] eq "add_root") {
    add_root_cert($ARGV[1]);
}
else {    
    usage;
    exit(1);
}

exit(0);





##############  sub-routines  ########################

sub usage () {
    print <<EOF;

Usage: smime_keys <operation>  [file(s) | keyID [file(s)]]

        with operation being one of:

        init      : no files needed, inits directory structure.

        list      : lists the certificates stored in database.
        label     : keyID required. changes/removes/adds label.
        remove    : keyID required.
        verify    : 1=keyID and optionally 2=CRL
                    Verifies the certificate chain, and optionally wether
                    this certificate is included in supplied CRL (PEM format).
                    Note: to verify all certificates at the same time,
                    replace keyID with "all"

        add_cert  : certificate required.
        add_chain : three files reqd: 1=Key, 2=certificate
                    plus 3=intermediate certificate(s).
        add_p12   : one file reqd. Adds keypair to database.
                    file is PKCS12 (e.g. export from netscape).
        add_pem   : one file reqd. Adds keypair to database.
                    (file was converted from e.g. PKCS12).

        add_root  : one file reqd. Adds PEM root certificate to the location
                    specified within muttrc (smime_verify_* command)

EOF
}

209 210
sub mutt_Q ($) {
    my $var = shift or die;
211

212 213 214 215 216 217 218 219 220
    my $cmd = "$mutt -v >/dev/null 2>/dev/null";
    system ($cmd) == 0 
        or die<<EOF;
Couldn't launch mutt. I attempted to do so by running the command "$mutt".
If that's not the right command, you can override it by setting the 
environment variable \$MUTT_CMDLINE
EOF

    $cmd = "$mutt -Q $var 2>/dev/null";
221 222 223 224 225 226 227 228
    my $answer = `$cmd`;

    $? and die<<EOF;
Couldn't look up the value of the mutt variable "$var". 
You must set this in your mutt config file. See contrib/smime.rc for an example.
EOF
#'

229
    $answer =~ /\"(.*?)\"/ and return bsd_glob($1, GLOB_TILDE | GLOB_NOCHECK);
230
    
231 232 233 234 235
    $answer =~ /^Mutt (.*?) / and die<<EOF;
This script requires mutt 1.5.0 or later. You are using mutt $1.
EOF
    
    die "Value of $var is weird\n";
236 237
}

238 239 240 241 242 243
sub mycopy ($$) {
    my $source = shift or die;
    my $dest = shift or die;

    copy $source, $dest or die "Problem copying $source to $dest: $!\n";
}
244

245 246 247 248 249
#
#  directory setup routines
#


250 251
sub mkdir_recursive ($) {
    my $path = shift or die;
252 253 254 255 256 257
    my $tmp_path;
    
    for my $dir (split /\//, $path) {
        $tmp_path .= "$dir/";

        -d $tmp_path 
258
            or mkdir $tmp_path, 0700
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
                or die "Can't mkdir $tmp_path: $!";
    }
}

sub init_paths () {
    mkdir_recursive($certificates_path);
    mkdir_recursive($private_keys_path);

    my $file;

    $file = $certificates_path . "/.index";
    -f $file or open(TMP_FILE, ">$file") and close(TMP_FILE)
        or die "Can't touch $file: $!";

    $file = $private_keys_path . "/.index";
    -f $file or open(TMP_FILE, ">$file") and close(TMP_FILE)
        or die "Can't touch $file: $!";
}



#
# certificate management methods
#

sub list_certs () {
  my %keyflags = ( 'i', '(Invalid)',  'r', '(Revoked)', 'e', '(Expired)',
		   'u', '(Unverified)', 'v', '(Valid)', 't', '(Trusted)');

  open(INDEX, "<$certificates_path/.index") or 
    die "Couldn't open $certificates_path/.index: $!";
  
  print "\n";
  while(<INDEX>) {
    my $tmp;
    my @tmp;
    my $tab = "            ";
    my @fields = split;

    if($fields[2] eq '-') {
      print "$fields[1]: Issued for: $fields[0] $keyflags{$fields[4]}\n";
    } else {
      print "$fields[1]: Issued for: $fields[0] \"$fields[2]\" $keyflags{$fields[4]}\n";
    }

304 305 306 307 308 309 310
    my $certfile = "$certificates_path/$fields[1]";
    my $cert;
    {
        open F, $certfile or
            die "Couldn't open $certfile: $!";
        local $/;
        $cert = <F>;
311
	close F;
312 313 314 315 316 317 318
    }

    my $subject_in;
    my $issuer_in;
    my $date1_in;
    my $date2_in;

319 320 321 322
    my $format = -B $certfile ? 'DER' : 'PEM'; 
    my $cmd = "$opensslbin x509 -subject -issuer -dates -noout -in $certfile -inform $format";
    ($subject_in, $issuer_in, $date1_in, $date2_in) = `$cmd`;
    $? and print "ERROR: '$cmd' returned $?\n\n" and next;
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

    my @subject = split(/\//, $subject_in);
    while(@subject) {
      $tmp = shift @subject;
      ($tmp =~ /^CN\=/) and last;
      undef $tmp;
    }
    defined $tmp and @tmp = split (/\=/, $tmp) and
      print $tab."Subject: $tmp[1]\n";

    my @issuer = split(/\//, $issuer_in);
    while(@issuer) {
      $tmp = shift @issuer;
      ($tmp =~ /^CN\=/) and last;
      undef $tmp;
    }
    defined $tmp and @tmp = split (/\=/, $tmp) and
      print $tab."Issued by: $tmp[1]";

    if ( defined $date1_in and defined $date2_in ) {
      @tmp = split (/\=/, $date1_in);
      $tmp = $tmp[1];
      @tmp = split (/\=/, $date2_in);
      print $tab."Certificate is not valid before $tmp".
	$tab."                      or after  ".$tmp[1];
    }

    -e "$private_keys_path/$fields[1]" and
      print "$tab - Matching private key installed -\n";

354 355
    $format = -B "$certificates_path/$fields[1]" ? 'DER' : 'PEM'; 
    $cmd = "$opensslbin x509 -purpose -noout -in $certfile -inform $format";
356 357 358
    my $purpose_in = `$cmd`;
    $? and die "'$cmd' returned $?";

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    my @purpose = split (/\n/, $purpose_in);
    print "$tab$purpose[0] (displays S/MIME options only)\n";
    while(@purpose) {
      $tmp = shift @purpose;
      ($tmp =~ /^S\/MIME/ and $tmp =~ /Yes/) or next;
      my @tmptmp = split (/:/, $tmp);
      print "$tab  $tmptmp[0]\n";
    }

    print "\n";
  }
  
  close(INDEX);
}



sub query_label () {
    my @words;
    my $input;

    print "\nYou may assign a label to this key, so you don't have to remember\n";
    print "the key ID. This has to be _one_ word (no whitespaces).\n\n";

    print "Enter label: ";
    chomp($input = <STDIN>);

    my ($label, $junk) = split(/\s/, $input, 2);     
    
    defined $junk 
        and print "\nUsing '$label' as label; ignoring '$junk'\n";

    defined $label || ($label =  "-");

    return $label;
}



398 399 400
sub add_entry ($$$$$) {
    my $mailbox = shift or die;
    my $hashvalue = shift or die;
401
    my $use_cert = shift;
402
    my $label = shift or die;
403
    my $issuer_hash = shift;
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

    my @fields;

    if ($use_cert) {
        open(INDEX, "+<$certificates_path/.index") or 
            die "Couldn't open $certificates_path/.index: $!";
    }
    else {
        open(INDEX, "+<$private_keys_path/.index") or 
            die "Couldn't open $private_keys_path/.index: $!";
    }

    while(<INDEX>) {
        @fields = split;
        return if ($fields[0] eq $mailbox && $fields[1] eq $hashvalue);
    }

    if ($use_cert) {
        print INDEX "$mailbox $hashvalue $label $issuer_hash u\n";
    }
    else {
        print INDEX "$mailbox $hashvalue $label \n";
    }

    close(INDEX);
}


sub add_certificate ($$$$;$) {
433 434
    my $filename = shift or die;
    my $hashvalue = shift or die;
Thomas Roessler's avatar
Thomas Roessler committed
435
    my $add_to_index = shift;
436
    my $label = shift or die;
437 438 439
    my $issuer_hash = shift;

    my $iter = 0;
440
    my @mailbox;
441 442 443 444
    my $mailbox;

    while(-e "$certificates_path/$$hashvalue.$iter") {
        my ($t1, $t2);
445
        my $format = -B $filename ? 'DER' : 'PEM'; 
446
        my $cmd = "$opensslbin x509 -in $filename -inform $format -fingerprint -noout";
447 448 449
        $t1 = `$cmd`;
        $? and die "'$cmd' returned $?";

450
        $format = -B "$certificates_path/$$hashvalue.$iter" ? 'DER' : 'PEM'; 
451
        $cmd = "$opensslbin x509 -in $certificates_path/$$hashvalue.$iter -inform $format -fingerprint -noout";
452 453 454 455 456 457 458 459 460
        $t2 = `$cmd`;
        $? and die "'$cmd' returned $?";
        
        $t1 eq $t2 and last;

        $iter++;
    }
    $$hashvalue .= ".$iter";
    
Thomas Roessler's avatar
Thomas Roessler committed
461 462 463 464
    if (-e "$certificates_path/$$hashvalue") {
            print "\nCertificate: $certificates_path/$$hashvalue already installed.\n";
    }
    else {
465
        mycopy $filename, "$certificates_path/$$hashvalue";
466 467

        if ($add_to_index) {
468
            my $format = -B $filename ? 'DER' : 'PEM'; 
469
	    my $cmd = "$opensslbin x509 -in $filename -inform $format -email -noout";
470
	    @mailbox = `$cmd`;
471 472
	    $? and die "'$cmd' returned $?";

473 474 475
	    foreach $mailbox (@mailbox) {
	      chomp($mailbox);
	      add_entry($mailbox, $$hashvalue, 1, $label, $issuer_hash);
476

Thomas Roessler's avatar
Thomas Roessler committed
477
	      print "\ncertificate $$hashvalue ($label) for $mailbox added.\n";
478
	    }
Thomas Roessler's avatar
Thomas Roessler committed
479
	    verify_cert($$hashvalue, undef);
480 481 482 483 484 485
        }
        else {
            print "added certificate: $certificates_path/$$hashvalue.\n";
        }
    }

486
    return @mailbox;
487 488 489 490
}


sub add_key ($$$$) {
491 492 493 494
    my $file = shift or die;
    my $hashvalue = shift or die;
    my $mailbox = shift or die;
    my $label = shift or die;
495 496

    unless (-e "$private_keys_path/$hashvalue") {
497
        mycopy $file, "$private_keys_path/$hashvalue";
498
    }    
499 500 501 502

    add_entry($mailbox, $hashvalue, 0, $label, "");
    print "added private key: " .
      "$private_keys_path/$hashvalue for $mailbox\n";
503 504 505 506 507 508 509 510 511 512 513 514 515
} 






sub parse_pem (@) {
    my $state = 0;
    my $cert_iter = 0;
    my @bag_attribs;
    my $numBags = 0;

516 517 518 519
    $cert_tmp_file[$cert_iter] = newfile("cert_tmp.$cert_iter","temp");
    my $cert_tmp_iter = $cert_tmp_file[$cert_iter];
    open(CERT_FILE, ">$cert_tmp_iter") 
        or die "Couldn't open $cert_tmp_iter: $!";
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

    while($_ = shift(@_)) {
        if(/^Bag Attributes/) {
            $numBags++;
            $state == 0 or  die("PEM-parse error at: $.");
	    $state = 1;
            $bag_attribs[$cert_iter*4+1] = "";
            $bag_attribs[$cert_iter*4+2] = "";
            $bag_attribs[$cert_iter*4+3] = "";
        }

        ($state == 1) and /localKeyID:\s*(.*)/ 
            and ($bag_attribs[$cert_iter*4+1] = $1);

        ($state == 1) and /subject=\s*(.*)/    
            and ($bag_attribs[$cert_iter*4+2] = $1);

        ($state == 1) and /issuer=\s*(.*)/     
            and ($bag_attribs[$cert_iter*4+3] = $1);
        
        if(/^-----/) {
            if(/BEGIN/) {
                print CERT_FILE;
                $state = 2;

                if(/PRIVATE/) {
                    $bag_attribs[$cert_iter*4] = "K";
                    next;
                }
                if(/CERTIFICATE/) {
                    $bag_attribs[$cert_iter*4] = "C";
                    next;
                }
                die("What's this: $_");
            }
            if(/END/) {
                $state = 0;
                print CERT_FILE;
                close(CERT_FILE);
                $cert_iter++;
560 561 562 563
	        $cert_tmp_file[$cert_iter] = newfile("cert_tmp.$cert_iter","temp");
	        $cert_tmp_iter = $cert_tmp_file[$cert_iter];
                open(CERT_FILE, ">$cert_tmp_iter")
                    or die "Couldn't open $cert_tmp_iter: $!";
564 565 566 567 568 569 570 571 572 573 574
                next;
            }
        }
        print CERT_FILE;
    }
    close(CERT_FILE);

    # I'll add support for unbagged cetificates, in case this is needed.
    $numBags == $cert_iter or 
        die("Not all contents were bagged. can't continue.");

575
    return @bag_attribs;
576 577 578 579 580 581 582 583 584 585 586
}


# This requires the Bag Attributes to be set
sub handle_pem (@) {

    my @pem_contents;
    my $iter=0;
    my $root_cert;
    my $key;
    my $certificate;
587 588
    my $intermediate;
    my @mailbox;
589 590 591 592 593
    my $mailbox;

    @pem_contents = &parse_pem(@_);

    # private key and certificate use the same 'localKeyID'
594 595
    while($iter <= $#pem_contents / 4) {
        if($pem_contents[$iter * 4] eq "K") {
596 597 598 599 600
            $key = $iter;
            last;
        }
        $iter++;
    }
601
    ($iter > $#pem_contents / 2) and die("Couldn't find private key!");
602

603
    $pem_contents[($key * 4)+1] or die("Attribute 'localKeyID' wasn't set.");
604 605

    $iter = 0;
606
    while($iter <= $#pem_contents / 4) {
607
        $iter == $key and ($iter++) and next;
608
        if($pem_contents[($iter * 4)+1] eq $pem_contents[($key * 4)+1]) {
609 610 611 612 613
            $certificate = $iter;
            last;
        }
        $iter++;
    }
614
    ($iter > $#pem_contents / 4) and die("Couldn't find matching certificate!");
615

616 617 618 619
    my $tmp_key = newfile("tmp_key","temp");
    mycopy $cert_tmp_file[$key], $tmp_key;
    my $tmp_certificate = newfile("tmp_certificate","temp");
    mycopy $cert_tmp_file[$certificate], $tmp_certificate;
620 621 622 623

    # root certificate is self signed
    $iter = 0;

624
    while($iter <= $#pem_contents / 4) {
625 626 627 628 629
        if ($iter == $key or $iter == $certificate) {
            $iter++; 
            next;
        }

630
        if($pem_contents[($iter * 4)+2] eq $pem_contents[($iter * 4)+3]) {
631 632 633 634 635
            $root_cert = $iter;
            last;
        }
        $iter++;
    }
Thomas Roessler's avatar
Thomas Roessler committed
636 637 638 639
    if ($iter > $#pem_contents / 4) {
      print "Couldn't identify root certificate!\n";
      $root_cert = -1;      
    }
640 641 642 643

    # what's left are intermediate certificates.
    $iter = 0;

644 645
    # needs to be set, so we can check it later
    $intermediate = $root_cert;
646
    my $tmp_issuer_cert = newfile("tmp_issuer_cert","temp");
647
    while($iter <= $#pem_contents / 4) {
648 649 650 651 652
        if ($iter == $key or $iter == $certificate or $iter == $root_cert) {
            $iter++; 
            next;
        }

653 654 655
	open (IC, ">> $tmp_issuer_cert") or die "can't open $tmp_issuer_cert: $?";
	my $cert_tmp_iter = $cert_tmp_file[$iter];
	open (CERT, "< $cert_tmp_iter") or die "can't open $cert_tmp_iter: $?";
656 657 658
	print IC while (<CERT>);
	close IC;
	close CERT;
659

660 661 662
	# although there may be many, just need to know if there was any
	$intermediate = $iter;

663 664 665
        $iter++;
    }

Thomas Roessler's avatar
Thomas Roessler committed
666
    # no intermediate certificates ? use root-cert instead (if that was found...)
667
    if($intermediate == $root_cert) {
668
        if ($root_cert == -1) {
Thomas Roessler's avatar
Thomas Roessler committed
669
	  die("No root and no intermediate certificates. Can't continue.");
670 671
	}
        mycopy $cert_tmp_file[$root_cert], $tmp_issuer_cert;
672 673
    }

674 675
    my $label = query_label;

676 677
    my $format = -B $tmp_certificate ? 'DER' : 'PEM'; 
    my $cmd = "$opensslbin x509 -noout -hash -in $tmp_certificate -inform $format";
678 679 680
    my $cert_hash = `$cmd`;
    $? and die "'$cmd' returned $?";

681 682
    $format = -B $tmp_issuer_cert ? 'DER' : 'PEM'; 
    $cmd = "$opensslbin x509 -noout -hash -in $tmp_issuer_cert -inform $format";
683 684 685 686 687 688 689
    my $issuer_hash = `$cmd`;
    $? and die "'$cmd' returned $?";

    chomp($cert_hash); chomp($issuer_hash);

    # Note: $cert_hash will be changed to reflect the correct filename
    #       within add_cert() ONLY, so these _have_ to get called first..
690 691
    add_certificate($tmp_issuer_cert, \$issuer_hash, 0, $label);
    @mailbox = &add_certificate("$tmp_certificate", \$cert_hash, 1, $label, $issuer_hash); 
692 693
    foreach $mailbox (@mailbox) {
      chomp($mailbox);
694
      add_key($tmp_key, $cert_hash, $mailbox, $label);
695
    }
696 697 698 699 700 701 702 703
}






sub modify_entry ($$$;$ ) {
704 705
    my $op = shift or die;
    my $hashvalue = shift or die;
706
    my $use_cert = shift;
707 708 709 710 711
    my $crl;
    my $label;
    my $path;
    my @fields;

712
    $op eq 'L' and ($label = shift or die);
713
    $op eq 'V' and ($crl = shift);
714 715 716 717 718 719 720 721 722 723 724


    if ($use_cert) {
        $path = $certificates_path;
    }
    else {
        $path = $private_keys_path;
    }

    open(INDEX, "<$path/.index") or  
      die "Couldn't open $path/.index: $!";
725 726 727
    my $newindex = newfile("$path/.index.tmp");
    open(NEW_INDEX, ">$newindex") or 
      die "Couldn't create $newindex: $!";
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754

    while(<INDEX>) {
        @fields = split;
        if($fields[1] eq $hashvalue or $hashvalue eq 'all') {
	  $op eq 'R' and next;
	  print NEW_INDEX "$fields[0] $fields[1]";
	  if($op eq 'L') {
	    if($use_cert) {
	      print NEW_INDEX " $label $fields[3] $fields[4]";
	    }
	    else {
	      print NEW_INDEX " $label";
	    }
	  }
	  if ($op eq 'V') {
	    print "\n==> about to verify certificate of $fields[0]\n";
	    my $flag = &do_verify($fields[1], $fields[3], $crl);
	    print NEW_INDEX " $fields[2] $fields[3] $flag";
	  }
	  print NEW_INDEX "\n";
	  next;
	}
	print NEW_INDEX;
    }
    close(INDEX);
    close(NEW_INDEX);

755 756
    rename $newindex, "$path/.index" 
        or die "Couldn't rename $newindex to $path/.index: $!\n";
757 758 759 760 761 762 763 764

    print "\n";
}




sub remove_pair ($ ) {
765
  my $keyid = shift or die;
766 767

  if (-e "$certificates_path/$keyid") {
768
    unlink "$certificates_path/$keyid";
769 770 771 772 773 774 775 776
    modify_entry('R', $keyid, 1);
    print "Removed certificate $keyid.\n";
  }
  else {
    die "No such certificate: $keyid";
  }

  if (-e "$private_keys_path/$keyid") {
777
    unlink "$private_keys_path/$keyid";
778 779 780 781 782 783 784 785
    modify_entry('R', $keyid, 0);
    print "Removed private key $keyid.\n";
  }
}



sub change_label ($ ) {
786
  my $keyid = shift or die;
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
  
  my $label = query_label;

  if (-e "$certificates_path/$keyid") {
    modify_entry('L', $keyid, 1, $label);
    print "Changed label for certificate $keyid.\n";
  }
  else {
    die "No such certificate: $keyid";
  }

  if (-e "$private_keys_path/$keyid") {
    modify_entry('L', $keyid, 0, $label);
    print "Changed label for private key $keyid.\n";
  }

}




808 809
sub verify_cert ($$) {
  my $keyid = shift or die;
810 811 812 813 814 815 816 817 818 819
  my $crl = shift;

  -e "$certificates_path/$keyid" or $keyid eq 'all'
    or die "No such certificate: $keyid";
  modify_entry('V', $keyid, 1, $crl);
}




820
sub do_verify($$$) {
821

822 823
  my $cert = shift or die;
  my $issuerid = shift or die;
824 825 826 827 828 829 830 831 832 833 834 835 836
  my $crl = shift;

  my $result = 'i';
  my $trust_q;
  my $issuer_path;
  my $cert_path = "$certificates_path/$cert";

  if($issuerid eq '?') {
    $issuer_path = "$certificates_path/$cert";
  } else {
    $issuer_path = "$certificates_path/$issuerid";
  }

837
  my $cmd = "$opensslbin verify $root_certs_switch $root_certs_path -purpose smimesign -purpose smimeencrypt -untrusted $issuer_path $cert_path";
838 839
  my $output = `$cmd`;
  $? and die "'$cmd' returned $?";
840 841 842 843 844 845 846
  chop $output;
  print "\n$output\n";

  ($output =~ /OK/) and ($result = 'v');

  $result eq 'i' and return $result;

847
  my $format = -B $cert_path ? 'DER' : 'PEM'; 
848
  $cmd = "$opensslbin x509 -dates -serial -noout -in $cert_path -inform $format";
849 850
  (my $date1_in, my $date2_in, my $serial_in) = `$cmd`;
  $? and die "'$cmd' returned $?";
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

  if ( defined $date1_in and defined $date2_in ) {
    my @tmp = split (/\=/, $date1_in);
    my $tmp = $tmp[1];
    @tmp = split (/\=/, $date2_in);
    my %months = ('Jan', '00', 'Feb', '01', 'Mar', '02', 'Apr', '03',
		  'May', '04', 'Jun', '05', 'Jul', '06', 'Aug', '07',
		  'Sep', '08', 'Oct', '09', 'Nov', '10', 'Dec', '11');

    my @fields =
      $tmp =~ /(\w+)\s*(\d+)\s*(\d+):(\d+):(\d+)\s*(\d+)\s*GMT/;

    $#fields != 5 and print "Expiration Date: Parse Error :  $tmp\n\n" or
      timegm($fields[4], $fields[3], $fields[2], $fields[1],
	     $months{$fields[0]}, $fields[5]) > time and $result = 'e';
    $result eq 'e' and print "Certificate is not yet valid.\n" and return $result;

    @fields =
      $tmp[1] =~ /(\w+)\s*(\d+)\s*(\d+):(\d+):(\d+)\s*(\d+)\s*GMT/;

    $#fields != 5 and print "Expiration Date: Parse Error :  $tmp[1]\n\n" or
      timegm($fields[4], $fields[3], $fields[2], $fields[1],
	     $months{$fields[0]}, $fields[5]) < time and $result = 'e';
    $result eq 'e' and print "Certificate has expired.\n" and return $result;

  }
    
  if ( defined $crl ) {
    my @serial = split (/\=/, $serial_in);
880
    my $cmd = "$opensslbin crl -text -noout -in $crl | grep -A1 $serial[1]";
881 882
    (my $l1, my $l2) = `$cmd`;
    $? and die "'$cmd' returned $?";
883 884 885 886 887 888 889 890 891 892
    
    if ( defined $l2 ) {
      my @revoke_date = split (/:\s/, $l2);
      print "FAILURE: Certificate $cert has been revoked on $revoke_date[1]\n";
      $result = 'r';
    }
  }    
  print "\n";

  if ($result eq 'v') {
Thomas Roessler's avatar
Thomas Roessler committed
893
    return 't';
894 895 896 897 898 899 900 901
  }

  return $result;
}



sub add_root_cert ($) {
902
  my $root_cert = shift or die;
903

904 905
  my $format = -B $root_cert ? 'DER' : 'PEM'; 

906
  my $cmd = "$opensslbin x509 -noout -hash -in $root_cert -inform $format";
907 908 909 910 911
  my $root_hash = `$cmd`;
  $? and die "'$cmd' returned $?";

  if (-d $root_certs_path) {
    -e "$root_certs_path/$root_hash" or
912
        mycopy $root_cert, "$root_certs_path/$root_hash";
913 914 915 916 917
  }
  else {
    open(ROOT_CERTS, ">>$root_certs_path") or 
      die ("Couldn't open $root_certs_path for writing");

918
    $cmd = "$opensslbin x509 -in $root_cert -inform $format -fingerprint -noout";
919 920 921
    $? and die "'$cmd' returned $?";
    chomp(my $md5fp = `$cmd`);

922
    $cmd = "$opensslbin x509 -in $root_cert -inform $format -text -noout";
923 924 925 926 927 928 929 930 931
    $? and die "'$cmd' returned $?";
    my @cert_text = `$cmd`;

    print "Enter a label, name or description for this certificate: ";
    my $input = <STDIN>;

    my $line = "=======================================\n";
    print ROOT_CERTS "\n$input$line$md5fp\nPEM-Data:\n";

932
    $cmd = "$opensslbin x509 -in $root_cert -inform $format";
933 934 935
    my $cert = `$cmd`;
    $? and die "'$cmd' returned $?";
    print ROOT_CERTS $cert;
936 937 938 939 940 941
    print ROOT_CERTS @cert_text;
    close (ROOT_CERTS);
  }
  
}

942 943 944 945
sub newfile ($;$$) {
	# returns a file name which does not exist for tmp file creation
	my $filename = shift;
	my $option = shift;
Christoph Ludwig's avatar
Christoph Ludwig committed
946
	$option = "notemp" if (not defined($option));
947 948 949
	if (! $tmpdir and $option eq "temp") {
		$tmpdir = mutt_Q 'tmpdir';
		$tmpdir = newfile("$tmpdir/smime");
950
		mkdir $tmpdir, 0700 || die "Can't create $tmpdir: $!\n";
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
	}
	$filename = "$tmpdir/$filename" if ($option eq "temp");
	my $newfilename = $filename;
	my $count = 0;
	while (-e $newfilename) {
		$newfilename = "$filename.$count";
		$count++;
	}
	unshift(@tempfiles,$newfilename);
	return $newfilename;
}


END {
	# remove all our temporary files in the end:
	for (@tempfiles){
		if (-f) {
			unlink;
		} elsif (-d) { 
			rmdir;
		}
	}
}