smime.c 49.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2001,2002 Oliver Ehli <[email protected]>
3
 * Copyright (C) 2002 Mike Schiraldi <[email protected]>
4
 * Copyright (C) 2004 g10 Code GmbH
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 *     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
18
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 20
 */

21 22 23 24
#if HAVE_CONFIG_H
# include "config.h"
#endif

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "mutt.h"
#include "mutt_curses.h"
#include "mutt_menu.h"
#include "smime.h"
#include "mime.h"
#include "copy.h"

#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <ctype.h>

#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif

#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif

#ifdef HAVE_SYS_RESOURCE_H
# include <sys/resource.h>
#endif

52
#ifdef CRYPT_BACKEND_CLASSIC_SMIME
53

54
#include "mutt_crypt.h"
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

struct smime_command_context {
  const char *key;		    /* %k */
  const char *cryptalg;		    /* %a */
  const char *fname;		    /* %f */
  const char *sig_fname;	    /* %s */
  const char *certificates;	    /* %c */
  const char *intermediates;        /* %i */
};


char SmimePass[STRING];
time_t SmimeExptime = 0; /* when does the cached passphrase expire? */


70
static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
71 72 73 74
static char SmimeCertToUse[_POSIX_PATH_MAX];
static char SmimeIntermediateToUse[_POSIX_PATH_MAX];


75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
void smime_free_key (smime_key_t **keylist)
{
  smime_key_t *key;

  if (!keylist)
    return;

  while (*keylist)
  {
    key = *keylist;
    *keylist = (*keylist)->next;

    FREE (&key->email);
    FREE (&key->hash);
    FREE (&key->label);
    FREE (&key->issuer);
    FREE (&key);
  }
}

static smime_key_t *smime_copy_key (smime_key_t *key)
{
  smime_key_t *copy;

  if (!key)
    return NULL;

  copy = safe_calloc (sizeof (smime_key_t), 1);
  copy->email  = safe_strdup(key->email);
  copy->hash   = safe_strdup(key->hash);
  copy->label  = safe_strdup(key->label);
  copy->issuer = safe_strdup(key->issuer);
  copy->trust  = key->trust;
  copy->flags  = key->flags;

  return copy;
}


114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
/*
 *     Queries and passphrase handling.
 */




/* these are copies from pgp.c */


void smime_void_passphrase (void)
{
  memset (SmimePass, 0, sizeof (SmimePass));
  SmimeExptime = 0;
}

130 131 132
int smime_valid_passphrase (void)
{
  time_t now = time (NULL);
133

134 135 136
  if (now < SmimeExptime)
    /* Use cached copy.  */
    return 1;
137

138 139
  smime_void_passphrase();
  
140
  if (mutt_get_password (_("Enter S/MIME passphrase:"), SmimePass, sizeof (SmimePass)) == 0)
141 142 143 144 145 146
    {
      SmimeExptime = time (NULL) + SmimeTimeout;
      return (1);
    }
  else
    SmimeExptime = 0;
147

148 149
  return 0;
}
150 151 152 153 154 155 156 157 158 159


/*
 *     The OpenSSL interface
 */

/* This is almost identical to ppgp's invoking interface. */

static const char *_mutt_fmt_smime_command (char *dest,
					    size_t destlen,
160
					    size_t col,
161 162 163 164 165 166 167 168 169 170 171 172 173 174
					    char op,
					    const char *src,
					    const char *prefix,
					    const char *ifstring,
					    const char *elsestring,
					    unsigned long data,
					    format_flag flags)
{
  char fmt[16];
  struct smime_command_context *cctx = (struct smime_command_context *) data;
  int optional = (flags & M_FORMAT_OPTIONAL);
  
  switch (op)
  {
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
    case 'C':
    {
      if (!optional)
      {
	char path[_POSIX_PATH_MAX];
	char buf1[LONG_STRING], buf2[LONG_STRING];
	struct stat sb;

	strfcpy (path, NONULL (SmimeCALocation), sizeof (path));
	mutt_expand_path (path, sizeof (path));
	mutt_quote_filename (buf1, sizeof (buf1), path);

	if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
	  snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
	else
	  snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
	
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, buf2);
      }
      else if (!SmimeCALocation)
	optional = 0;
      break;
    }
    
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    case 'c':
    {           /* certificate (list) */
      if (!optional) {
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, NONULL(cctx->certificates));
      }
      else if (!cctx->certificates)
	optional = 0;
      break;
    }
    
    case 'i':
    {           /* intermediate certificates  */
      if (!optional) {
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, NONULL(cctx->intermediates));
      }
      else if (!cctx->intermediates)
	optional = 0;
      break;
    }
    
    case 's':
    {           /* detached signature */
      if (!optional)
      {
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
      }
      else if (!cctx->sig_fname)
	optional = 0;
      break;
    }
    
    case 'k':
    {           /* private key */
      if (!optional)
      {
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, NONULL (cctx->key));
      }
      else if (!cctx->key)
	optional = 0;
      break;
    }
    
    case 'a':
    {           /* algorithm for encryption */
      if (!optional) {
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
      }
      else if (!cctx->key)
	optional = 0;
      break;
    }
    
    case 'f':
    {           /* file to process */
      if (!optional)
      {
	snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
	snprintf (dest, destlen, fmt, NONULL (cctx->fname));
      }
      else if (!cctx->fname)
	optional = 0;
      break;
    }
    
    default:
      *dest = '\0';
      break;
  }

  if (optional)
275
    mutt_FormatString (dest, destlen, col, ifstring, _mutt_fmt_smime_command,
276 277
		       data, 0);
  else if (flags & M_FORMAT_OPTIONAL)
278
    mutt_FormatString (dest, destlen, col, elsestring, _mutt_fmt_smime_command,
279 280 281 282 283 284 285 286 287 288
		       data, 0);

  return (src);
}



static void mutt_smime_command (char *d, size_t dlen,
				struct smime_command_context *cctx, const char *fmt)
{
289
  mutt_FormatString (d, dlen, 0, NONULL(fmt), _mutt_fmt_smime_command,
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
		    (unsigned long) cctx, 0);
  dprint (2,(debugfile, "mutt_smime_command: %s\n", d));
}




static pid_t smime_invoke (FILE **smimein, FILE **smimeout, FILE **smimeerr,
			   int smimeinfd, int smimeoutfd, int smimeerrfd,
			   const char *fname,
			   const char *sig_fname,
			   const char *cryptalg,
			   const char *key,
			   const char *certificates,
			   const char *intermediates,
			   const char *format)
{
  struct smime_command_context cctx;
  char cmd[HUGE_STRING];
  
  memset (&cctx, 0, sizeof (cctx));

  if (!format || !*format)
    return (pid_t) -1;
  
  cctx.fname	       = fname;
  cctx.sig_fname       = sig_fname;
  cctx.key	       = key;
  cctx.cryptalg	       = cryptalg;
  cctx.certificates    = certificates;
  cctx.intermediates   = intermediates;
  
  mutt_smime_command (cmd, sizeof (cmd), &cctx, format);

  return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
				smimeinfd, smimeoutfd, smimeerrfd);
}






/*
 *    Key and certificate handling.
 */


338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
static char *smime_key_flags (int flags)
{
  static char buff[3];

  if (!(flags & KEYFLAG_CANENCRYPT))
    buff[0] = '-';
  else
    buff[0] = 'e';

  if (!(flags & KEYFLAG_CANSIGN))
    buff[1] = '-';
  else
    buff[1] = 's';

  buff[2] = '\0';

  return buff;
}
356 357 358 359


static void smime_entry (char *s, size_t l, MUTTMENU * menu, int num)
{
360 361
  smime_key_t **Table = (smime_key_t **) menu->data;
  smime_key_t *this = Table[num];
362
  char* truststate;
363
  switch(this->trust) {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    case 't':
      truststate = N_("Trusted   ");
      break;
    case 'v':
      truststate = N_("Verified  ");
      break;
    case 'u':
      truststate = N_("Unverified");
      break;
    case 'e':
      truststate = N_("Expired   ");
      break;
    case 'r':
      truststate = N_("Revoked   ");
      break;
    case 'i':
      truststate = N_("Invalid   ");
      break;
    default:
      truststate = N_("Unknown   ");
  }
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
  snprintf(s, l, " 0x%s %s %s %-35.35s %s", this->hash,
           smime_key_flags (this->flags), truststate, this->email, this->label);
}


static smime_key_t *smime_select_key (smime_key_t *keys, char *query)
{
  smime_key_t **table = NULL;
  int table_size = 0;
  int table_index = 0;
  smime_key_t *key = NULL;
  smime_key_t *selected_key = NULL;
  char helpstr[LONG_STRING];
  char buf[LONG_STRING];
  char title[256];
  MUTTMENU* menu;
  char *s = "";
  int done = 0;

  for (table_index = 0, key = keys; key; key = key->next)
  {
    if (table_index == table_size)
    {
      table_size += 5;
      safe_realloc (&table, sizeof (smime_key_t *) * table_size);
    }

    table[table_index++] = key;
  }

  snprintf(title, sizeof(title), _("S/MIME certificates matching \"%s\"."),
    query);

  /* Make Helpstring */
  helpstr[0] = 0;
  mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_SMIME, OP_EXIT);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */
  mutt_make_help (buf, sizeof (buf), _("Select  "), MENU_SMIME,
      OP_GENERIC_SELECT_ENTRY);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */
  mutt_make_help (buf, sizeof(buf), _("Help"), MENU_SMIME, OP_HELP);
  strcat (helpstr, buf);	/* __STRCAT_CHECKED__ */

  /* Create the menu */
  menu = mutt_new_menu(MENU_SMIME);
  menu->max = table_index;
  menu->make_entry = smime_entry;
  menu->help = helpstr;
  menu->data = table;
  menu->title = title;
  /* sorting keys might be done later - TODO */

  mutt_clear_error();

  done = 0;
  while (!done)
  {
    switch (mutt_menuLoop (menu))
    {
      case OP_GENERIC_SELECT_ENTRY:
        if (table[menu->current]->trust != 't')
        {
          switch (table[menu->current]->trust)
          {
            case 'i':
            case 'r':
            case 'e':
              s = N_("ID is expired/disabled/revoked.");
              break;
            case 'u':
              s = N_("ID has undefined validity.");
              break;
            case 'v':
              s = N_("ID is not trusted.");
              break;
          }

          snprintf (buf, sizeof (buf), _("%s Do you really want to use the key?"),
                    _(s));

          if (mutt_yesorno (buf, M_NO) != M_YES)
          {
            mutt_clear_error ();
            break;
          }
        }

        selected_key = table[menu->current];
        done = 1;
        break;
      case OP_EXIT:
        done = 1;
        break;
    }
  }

  mutt_menuDestroy (&menu);
  FREE (&table);
  set_option (OPTNEEDREDRAW);

  return selected_key;
486 487
}

488 489 490 491 492 493 494
static smime_key_t *smime_parse_key(char *buf)
{
  smime_key_t *key;
  char *pend, *p;
  int field = 0;

  key = safe_calloc (sizeof (smime_key_t), 1);
495

496 497 498 499
  for (p = buf; p; p = pend)
  {
    if ((pend = strchr (p, ' ')) || (pend = strchr (p, '\n')))
      *pend++ = 0;
500

501 502 503 504 505
    /* For backward compatibility, don't count consecutive delimiters
     * as an empty field.
     */
    if (!*p)
      continue;
506

507
    field++;
508

509 510 511 512 513 514 515 516 517 518 519 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 560 561 562 563 564
    switch (field)
    {
      case 1:                   /* mailbox */
        key->email = safe_strdup (p);
        break;
      case 2:                   /* hash */
        key->hash = safe_strdup (p);
        break;
      case 3:                   /* label */
        key->label = safe_strdup (p);
        break;
      case 4:                   /* issuer */
        key->issuer = safe_strdup (p);
        break;
      case 5:                   /* trust */
        key->trust = *p;
        break;
      case 6:                   /* purpose */
        while (*p)
        {
          switch (*p++)
          {
            case 'e':
              key->flags |= KEYFLAG_CANENCRYPT;
              break;

            case 's':
              key->flags |= KEYFLAG_CANSIGN;
              break;
          }
        }
        break;
    }
  }

  /* Old index files could be missing issuer, trust, and purpose,
   * but anything less than that is an error. */
  if (field < 3)
  {
    smime_free_key (&key);
    return NULL;
  }

  if (field < 4)
    key->issuer = safe_strdup ("?");

  if (field < 5)
    key->trust = 't';

  if (field < 6)
    key->flags = (KEYFLAG_CANENCRYPT | KEYFLAG_CANSIGN);

  return key;
}

static smime_key_t *smime_get_candidates(char *search, short public)
565 566
{
  char index_file[_POSIX_PATH_MAX];
567
  FILE *fp;
568
  char buf[LONG_STRING];
569 570 571 572
  smime_key_t *key, *results, **results_end;

  results = NULL;
  results_end = &results;
573 574 575

  snprintf(index_file, sizeof (index_file), "%s/.index",
    public ? NONULL(SmimeCertificates) : NONULL(SmimeKeys));
576 577

  if ((fp = safe_fopen (index_file, "r")) == NULL)
578
  {
579 580 581
    mutt_perror (index_file);
    return NULL;
  }
582

583 584 585
  while (fgets (buf, sizeof (buf), fp))
  {
    if ((! *search) || mutt_stristr (buf, search))
586
    {
587 588 589 590 591
      key = smime_parse_key (buf);
      if (key)
      {
        *results_end = key;
        results_end = &key->next;
592 593 594 595
      }
    }
  }

596
  safe_fclose (&fp);
597

598 599
  return results;
}
600

601 602 603 604
/* Returns the first matching key record, without prompting or checking of
 * abilities or trust.
 */
static smime_key_t *smime_get_key_by_hash(char *hash, short public)
605
{
606 607
  smime_key_t *results, *result;
  smime_key_t *match = NULL;
608

609 610 611 612 613 614 615 616 617
  results = smime_get_candidates(hash, public);
  for (result = results; result; result = result->next)
  {
    if (mutt_strcasecmp (hash, result->hash) == 0)
    {
      match = smime_copy_key (result);
      break;
    }
  }
618

619
  smime_free_key (&results);
620

621 622
  return match;
}
623

624 625 626 627 628 629 630 631 632 633 634 635 636
static smime_key_t *smime_get_key_by_addr(char *mailbox, short abilities, short public, short may_ask)
{
  smime_key_t *results, *result;
  smime_key_t *matches = NULL;
  smime_key_t **matches_end = &matches;
  smime_key_t *match;
  smime_key_t *trusted_match = NULL;
  smime_key_t *valid_match = NULL;
  smime_key_t *return_key = NULL;
  int multi_trusted_matches = 0;

  if (! mailbox)
    return NULL;
637

638 639
  results = smime_get_candidates(mailbox, public);
  for (result = results; result; result = result->next)
640
  {
641
    if (abilities && !(result->flags & abilities))
642
    {
643
      continue;
644 645
    }

646 647 648 649 650 651 652
    if (mutt_strcasecmp (mailbox, result->email) == 0)
    {
      match = smime_copy_key (result);
      *matches_end = match;
      matches_end = &match->next;

      if (match->trust == 't')
653
      {
654 655 656 657 658 659
        if (trusted_match &&
            (mutt_strcasecmp (match->hash, trusted_match->hash) != 0))
        {
          multi_trusted_matches = 1;
        }
        trusted_match = match;
660
      }
661
      else if ((match->trust == 'u') || (match->trust == 'v'))
662
      {
663
        valid_match = match;
664
      }
665 666
    }
  }
667

668
  smime_free_key (&results);
669

670 671 672
  if (matches)
  {
    if (! may_ask)
673
    {
674 675 676 677
      if (trusted_match)
        return_key = smime_copy_key (trusted_match);
      else if (valid_match)
        return_key = smime_copy_key (valid_match);
678
      else
679
        return_key = NULL;
680
    }
681
    else if (trusted_match && !multi_trusted_matches)
682
    {
683 684 685 686 687
      return_key = smime_copy_key (trusted_match);
    }
    else
    {
      return_key = smime_copy_key (smime_select_key (matches, mailbox));
688 689
    }

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    smime_free_key (&matches);
  }

  return return_key;
}

static smime_key_t *smime_get_key_by_str(char *str, short abilities, short public)
{
  smime_key_t *results, *result;
  smime_key_t *matches = NULL;
  smime_key_t **matches_end = &matches;
  smime_key_t *match;
  smime_key_t *return_key = NULL;

  if (! str)
    return NULL;

  results = smime_get_candidates(str, public);
  for (result = results; result; result = result->next)
  {
    if (abilities && !(result->flags & abilities))
    {
      continue;
    }

    if ((mutt_strcasecmp (str, result->hash) == 0) ||
        mutt_stristr(result->email, str) ||
        mutt_stristr(result->label, str))
    {
      match = smime_copy_key (result);
      *matches_end = match;
      matches_end = &match->next;
    }
  }

  smime_free_key (&results);

  if (matches)
  {
    return_key = smime_copy_key (smime_select_key (matches, str));
    smime_free_key (&matches);
731 732
  }

733
  return return_key;
734 735 736
}


737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
smime_key_t *smime_ask_for_key(char *prompt, short abilities, short public)
{
  smime_key_t *key;
  char resp[SHORT_STRING];

  if (!prompt) prompt = _("Enter keyID: ");

  mutt_clear_error ();

  FOREVER
  {
    resp[0] = 0;
    if (mutt_get_field (prompt, resp, sizeof (resp), M_CLEAR) != 0)
      return NULL;

    if ((key = smime_get_key_by_str (resp, abilities, public)))
      return key;

    BEEP ();
  }
}

759 760 761 762


/* 
   This sets the '*ToUse' variables for an upcoming decryption, where
Ondřej Bílka's avatar
Ondřej Bílka committed
763
   the required key is different from SmimeDefaultKey.
764 765
*/

766
void _smime_getkeys (char *mailbox)
767
{
768
  smime_key_t *key = NULL;
769
  char *k = NULL;
770 771
  char buf[STRING];

772
  key = smime_get_key_by_addr (mailbox, KEYFLAG_CANENCRYPT, 0, 1);
773

774
  if (!key)
775
  {
776
    snprintf(buf, sizeof(buf), _("Enter keyID for %s: "),
777
	     mailbox);
778
    key = smime_ask_for_key (buf, KEYFLAG_CANENCRYPT, 0);
779 780
  }

781
  if (key)
782
  {
783 784
    k = key->hash;

785
    /* the key used last time. */
786 787
    if (*SmimeKeyToUse && 
        !mutt_strcasecmp (k, SmimeKeyToUse + mutt_strlen (SmimeKeys)+1))
788
    {
789
      smime_free_key (&key);
790 791 792 793 794 795 796 797 798 799
      return;
    }
    else smime_void_passphrase ();

    snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s", 
	      NONULL(SmimeKeys), k);
    
    snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
	      NONULL(SmimeCertificates), k);

800
    if (mutt_strcasecmp (k, SmimeDefaultKey))
801 802
      smime_void_passphrase ();

803
    smime_free_key (&key);
804 805 806
    return;
  }

807 808
  if (*SmimeKeyToUse)
  {
809
    if (!mutt_strcasecmp (SmimeDefaultKey, 
810 811 812 813 814 815
                          SmimeKeyToUse + mutt_strlen (SmimeKeys)+1))
      return;

    smime_void_passphrase ();
  }

816
  snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s", 
817
	    NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
818 819
  
  snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
820
	    NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
821 822
}

823 824 825 826
void smime_getkeys (ENVELOPE *env)
{
  ADDRESS *t;
  int found = 0;
827

828 829 830 831 832 833 834 835 836 837 838
  if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey)
  {
    snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s", 
	      NONULL (SmimeKeys), SmimeDefaultKey);
    
    snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
	      NONULL(SmimeCertificates), SmimeDefaultKey);

    return;
  }

839 840 841 842
  for (t = env->to; !found && t; t = t->next)
    if (mutt_addr_is_user (t))
    {
      found = 1;
Thomas Roessler's avatar
ups  
Thomas Roessler committed
843 844
      _smime_getkeys (t->mailbox);
    }
845 846 847 848
  for (t = env->cc; !found && t; t = t->next)
    if (mutt_addr_is_user (t))
    {
      found = 1;
Thomas Roessler's avatar
ups  
Thomas Roessler committed
849
      _smime_getkeys (t->mailbox);
850 851 852 853 854 855 856
    }
  if (!found && (t = mutt_default_from()))
  {
    _smime_getkeys (t->mailbox);
    rfc822_free_address (&t);
  }
}
857 858 859

/* This routine attempts to find the keyids of the recipients of a message.
 * It returns NULL if any of the keys can not be found.
860 861
 * If oppenc_mode is true, only keys that can be determined without
 * prompting will be used.
862 863
 */

864
char *smime_findKeys (ADDRESS *adrlist, int oppenc_mode)
865
{
866
  smime_key_t *key = NULL;
867 868 869 870 871
  char *keyID, *keylist = NULL;
  size_t keylist_size = 0;
  size_t keylist_used = 0;
  ADDRESS *p, *q;

872
  for (p = adrlist; p ; p = p->next)
873 874 875 876 877
  {
    char buf[LONG_STRING];

    q = p;

878 879
    key = smime_get_key_by_addr (q->mailbox, KEYFLAG_CANENCRYPT, 1, !oppenc_mode);
    if ((key == NULL) && (! oppenc_mode))
880 881
    {
      snprintf(buf, sizeof(buf),
882
	       _("Enter keyID for %s: "),
883
	       q->mailbox);
884
      key = smime_ask_for_key (buf, KEYFLAG_CANENCRYPT, 1);
885
    }
886
    if (!key)
887
    {
888 889
      if (! oppenc_mode)
        mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
890
      FREE (&keylist);
891 892 893
      return NULL;
    }
    
894
    keyID = key->hash;
895
    keylist_size += mutt_strlen (keyID) + 2;
896
    safe_realloc (&keylist, keylist_size);
897
    sprintf (keylist + keylist_used, "%s\n", keyID);	/* __SPRINTF_CHECKED__ */
898 899
    keylist_used = mutt_strlen (keylist);

900
    smime_free_key (&key);
901 902 903 904 905 906
  }
  return (keylist);
}



907 908 909



910 911
static int smime_handle_cert_email (char *certificate, char *mailbox,
				   int copy, char ***buffer, int *num)
912 913 914
{
  FILE *fpout = NULL, *fperr = NULL;
  char tmpfname[_POSIX_PATH_MAX];
915
  char email[STRING];
916
  int ret = -1, count = 0;
917
  pid_t thepid;
918
  size_t len = 0;
919

920
  mutt_mktemp (tmpfname, sizeof (tmpfname));
921 922 923 924 925 926 927
  if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
  {
    mutt_perror (tmpfname);
    return 1;
  }
  mutt_unlink (tmpfname);

928
  mutt_mktemp (tmpfname, sizeof (tmpfname));
929 930
  if ((fpout = safe_fopen (tmpfname, "w+")) == NULL)
  {
931
    safe_fclose (&fperr);
932 933 934 935 936
    mutt_perror (tmpfname);
    return 1;
  }
  mutt_unlink (tmpfname);

937
  if ((thepid =  smime_invoke (NULL, NULL, NULL,
938 939 940 941 942
			       -1, fileno (fpout), fileno (fperr),
			       certificate, NULL, NULL, NULL, NULL, NULL,
			       SmimeGetCertEmailCommand))== -1)
  {
    mutt_message (_("Error: unable to create OpenSSL subprocess!"));
943 944
    safe_fclose (&fperr);
    safe_fclose (&fpout);
945 946 947 948 949 950 951 952
    return 1;
  }

  mutt_wait_filter (thepid);

  fflush (fpout);
  rewind (fpout);
  fflush (fperr);
953
  rewind (fperr);
954

955

956 957
  while ((fgets (email, sizeof (email), fpout)))
  {
958 959 960
    len = mutt_strlen (email);
    if (len)
      *(email + len - 1) = '\0';
961 962 963 964 965
    if(mutt_strncasecmp (email, mailbox, mutt_strlen (mailbox)) == 0)
      ret=1;

    ret = ret < 0 ? 0 : ret;
    count++;
966
  }
967

968
  if (ret == -1)
969 970
  {
    mutt_endwin(NULL);
Thomas Roessler's avatar
Thomas Roessler committed
971 972
    mutt_copy_stream (fperr, stdout);
    mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
973
    ret = 1;
974
  }
975
  else if (!ret)
976
    ret = 1;
977 978 979 980 981 982 983 984 985 986 987
  else ret = 0;

  if(copy && buffer && num)
  {
    (*num) = count;
    *buffer =  safe_calloc(sizeof(char*), count);
    count = 0;

    rewind (fpout);
    while ((fgets (email, sizeof (email), fpout)))
    {
988 989 990
      len = mutt_strlen (email);
      if (len)
        *(email + len - 1) = '\0';
991 992 993 994 995 996
      (*buffer)[count] = safe_calloc(1, mutt_strlen (email) + 1);
      strncpy((*buffer)[count], email, mutt_strlen (email));
      count++;
    }
  }
  else if(copy) ret = 2;
997

998 999
  safe_fclose (&fpout);
  safe_fclose (&fperr);
1000

1001
  return ret;
1002 1003 1004 1005
}



1006
static char *smime_extract_certificate (char *infile)
1007 1008 1009 1010 1011 1012 1013 1014
{
  FILE *fpout = NULL, *fperr = NULL;
  char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
  char tmpfname[_POSIX_PATH_MAX];
  pid_t thepid;
  int empty;


1015
  mutt_mktemp (tmpfname, sizeof (tmpfname));
1016 1017 1018 1019 1020 1021 1022
  if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
  {
    mutt_perror (tmpfname);
    return NULL;
  }
  mutt_unlink (tmpfname);

1023
  mutt_mktemp (pk7out, sizeof (pk7out));
1024 1025
  if ((fpout = safe_fopen (pk7out, "w+")) == NULL)
  {
1026
    safe_fclose (&fperr);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    mutt_perror (pk7out);
    return NULL;
  }

  /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
     extract the full set of certificates directly.
  */
  if ((thepid =  smime_invoke (NULL, NULL, NULL,
			       -1, fileno (fpout), fileno (fperr),
			       infile, NULL, NULL, NULL, NULL, NULL,
			       SmimePk7outCommand))== -1)
  {
    mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
1040 1041
    safe_fclose (&fperr);
    safe_fclose (&fpout);
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    mutt_unlink (pk7out);
    return NULL;
  }

  mutt_wait_filter (thepid);


  fflush (fpout);
  rewind (fpout);
  fflush (fperr);
1052
  rewind (fperr);
1053 1054 1055 1056 1057
  empty = (fgetc (fpout) == EOF);
  if (empty)
  {
    mutt_perror (pk7out);
    mutt_copy_stream (fperr, stdout);
1058 1059
    safe_fclose (&fpout);
    safe_fclose (&fperr);
1060 1061 1062 1063 1064 1065
    mutt_unlink (pk7out);
    return NULL;
    
  }


1066
  safe_fclose (&fpout);
1067
  mutt_mktemp (certfile, sizeof (certfile));
1068 1069
  if ((fpout = safe_fopen (certfile, "w+")) == NULL)
  {
1070
    safe_fclose (&fperr);
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    mutt_unlink (pk7out);
    mutt_perror (certfile);
    return NULL;
  }
  
  /* Step 2: Extract the certificates from a PKCS#7 structure.
   */
  if ((thepid =  smime_invoke (NULL, NULL, NULL,
			       -1, fileno (fpout), fileno (fperr),
			       pk7out, NULL, NULL, NULL, NULL, NULL,
			       SmimeGetCertCommand))== -1)
  {
    mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
1084 1085
    safe_fclose (&fperr);
    safe_fclose (&fpout);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    mutt_unlink (pk7out);
    mutt_unlink (certfile);
    return NULL;
  }

  mutt_wait_filter (thepid);

  mutt_unlink (pk7out);

  fflush (fpout);
  rewind (fpout);
  fflush (fperr);
1098
  rewind (fperr);
1099 1100 1101 1102
  empty =  (fgetc (fpout) == EOF);
  if (empty)
  {
    mutt_copy_stream (fperr, stdout);
1103 1104
    safe_fclose (&fpout);
    safe_fclose (&fperr);
1105 1106 1107 1108
    mutt_unlink (certfile);
    return NULL;
  }

1109 1110
  safe_fclose (&fpout);
  safe_fclose (&fperr);
1111 1112 1113 1114

  return safe_strdup (certfile);
}

1115
static char *smime_extract_signer_certificate (char *infile)
1116 1117 1118 1119 1120 1121 1122 1123
{
  FILE *fpout = NULL, *fperr = NULL;
  char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
  char tmpfname[_POSIX_PATH_MAX];
  pid_t thepid;
  int empty;


1124
  mutt_mktemp (tmpfname, sizeof (tmpfname));
1125 1126 1127 1128 1129 1130 1131 1132
  if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
  {
    mutt_perror (tmpfname);
    return NULL;
  }
  mutt_unlink (tmpfname);


1133
  mutt_mktemp (certfile, sizeof (certfile));
1134 1135
  if ((fpout = safe_fopen (certfile, "w+")) == NULL)
  {
1136
    safe_fclose (&fperr);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    mutt_perror (certfile);
    return NULL;
  }
  
  /* Extract signer's certificate
   */
  if ((thepid =  smime_invoke (NULL, NULL, NULL,
			       -1, -1, fileno (fperr),
			       infile, NULL, NULL, NULL, certfile, NULL,
			       SmimeGetSignerCertCommand))== -1)
  {
    mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
1149 1150
    safe_fclose (&fperr);
    safe_fclose (&fpout);
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
    mutt_unlink (pk7out);
    mutt_unlink (certfile);
    return NULL;
  }

  mutt_wait_filter (thepid);

  fflush (fpout);
  rewind (fpout);
  fflush (fperr);
1161
  rewind (fperr);
1162 1163 1164
  empty =  (fgetc (fpout) == EOF);
  if (empty)
  {
1165
    mutt_endwin (NULL);
1166
    mutt_copy_stream (fperr, stdout);
1167
    mutt_any_key_to_continue (NULL);
1168 1169
    safe_fclose (&fpout);
    safe_fclose (&fperr);
1170 1171 1172 1173
    mutt_unlink (certfile);
    return NULL;
  }

1174 1175
  safe_fclose (&fpout);
  safe_fclose (&fperr);
1176 1177 1178 1179 1180

  return safe_strdup (certfile);
}


1181

Thomas Roessler's avatar
Thomas Roessler committed
1182 1183 1184 1185

/* Add a certificate and update index file (externally). */

void smime_invoke_import (char *infile, char *mailbox)
1186
{
Thomas Roessler's avatar
Thomas Roessler committed
1187 1188 1189
  char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
  FILE *smimein=NULL, *fpout = NULL, *fperr = NULL;
  pid_t thepid=-1;
1190

1191
  mutt_mktemp (tmpfname, sizeof (tmpfname));
1192 1193 1194
  if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
  {
    mutt_perror (tmpfname);
Thomas Roessler's avatar
Thomas Roessler committed
1195
    return;
1196 1197 1198
  }
  mutt_unlink (tmpfname);

1199
  mutt_mktemp (tmpfname, sizeof (tmpfname));
1200 1201
  if ((fpout = safe_fopen (tmpfname, "w+")) == NULL)
  {
1202
    safe_fclose (&fperr);
1203
    mutt_perror (tmpfname);
Thomas Roessler's avatar
Thomas Roessler committed
1204
    return;
1205 1206 1207 1208
  }
  mutt_unlink (tmpfname);


Thomas Roessler's avatar
Thomas Roessler committed
1209 1210 1211
  buf[0] = '\0';
  if (option (OPTASKCERTLABEL))
    mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1212

Thomas Roessler's avatar
Thomas Roessler committed
1213 1214
  mutt_endwin (NULL);
  if ((certfile = smime_extract_certificate(infile)))
1215
  {
Thomas Roessler's avatar
Thomas Roessler committed
1216
    mutt_endwin (NULL);
1217
  
Thomas Roessler's avatar
Thomas Roessler committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    if ((thepid =  smime_invoke (&smimein, NULL, NULL,
				 -1, fileno(fpout), fileno(fperr),
				 certfile, NULL, NULL, NULL, NULL, NULL,
				 SmimeImportCertCommand))== -1)
    {
      mutt_message (_("Error: unable to create OpenSSL subprocess!"));
      return;
    }
    fputs (buf, smimein);
    fputc ('\n', smimein);
1228
    safe_fclose (&smimein);
1229

Thomas Roessler's avatar
Thomas Roessler committed
1230
    mutt_wait_filter (thepid);
1231
  
Thomas Roessler's avatar
Thomas Roessler committed
1232
    mutt_unlink (certfile);
1233
    FREE (&certfile);
1234 1235 1236 1237 1238
  }

  fflush (fpout);
  rewind (fpout);
  fflush (fperr);
1239
  rewind (fperr);
1240

Thomas Roessler's avatar
Thomas Roessler committed
1241 1242 1243
  mutt_copy_stream (fpout, stdout);
  mutt_copy_stream (fperr, stdout);

1244 1245
  safe_fclose (&fpout);
  safe_fclose (&fperr);
1246

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
}



int smime_verify_sender(HEADER *h)
{
  char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
  FILE *fpout;
  int retval=1;

1257
  mutt_mktemp (tempfname, sizeof (tempfname));
1258 1259 1260 1261 1262 1263 1264 1265 1266
  if (!(fpout = safe_fopen (tempfname, "w")))
  {
    mutt_perror (tempfname);
    return 1;
  }

  if(h->security & ENCRYPT)
    mutt_copy_message (fpout, Context, h,
		       M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1267
		       CH_MIME|CH_WEED|CH_NONEWLINE);
1268 1269 1270 1271
  else
    mutt_copy_message (fpout, Context, h, 0, 0);

  fflush(fpout);
1272
  safe_fclose (&fpout);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

  if (h->env->from)
  {
    h->env->from = mutt_expand_aliases (h->env->from); 
    mbox = h->env->from->mailbox; 
  }
  else if (h->env->sender)
  {
    h->env->sender = mutt_expand_aliases (h->env->sender); 
    mbox = h->env->sender->mailbox; 
  }

  if (mbox)
  {
1287
    if ((certfile = smime_extract_signer_certificate(tempfname)))
1288 1289
    {
      mutt_unlink(tempfname);
1290
      if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL))
Thomas Roessler's avatar
Thomas Roessler committed
1291 1292 1293 1294
      {
	if(isendwin())
         mutt_any_key_to_continue(NULL);
      }
1295 1296 1297
      else
	retval = 0;
      mutt_unlink(certfile);
1298
      FREE (&certfile);
1299 1300
    }
  else 
1301
	mutt_any_key_to_continue(_("no certfile"));
1302 1303
  }
  else 
1304
	mutt_any_key_to_continue(_("no mbox"));
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361

  mutt_unlink(tempfname);
  return retval;
}









/*
 *    Creating S/MIME - bodies.
 */




static
pid_t smime_invoke_encrypt (FILE **smimein, FILE **smimeout, FILE **smimeerr,
			    int smimeinfd, int smimeoutfd, int smimeerrfd,
			    const char *fname, const char *uids)
{
  return smime_invoke (smimein, smimeout, smimeerr,
		       smimeinfd, smimeoutfd, smimeerrfd,
		       fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
		       SmimeEncryptCommand);
}


static
pid_t smime_invoke_sign (FILE **smimein, FILE **smimeout, FILE **smimeerr,
			 int smimeinfd, int smimeoutfd, int smimeerrfd, 
			 const char *fname)
{
  return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
		       smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
		       SmimeCertToUse, SmimeIntermediateToUse,
		       SmimeSignCommand);
}




BODY *smime_build_smime_entity (BODY *a, char *certlist)
{
  char buf[LONG_STRING], certfile[LONG_STRING];
  char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
  char smimeinfile[_POSIX_PATH_MAX];
  char *cert_start = certlist, *cert_end = certlist;
  FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
  BODY *t;
  int err = 0, empty;
  pid_t thepid;
  
1362
  mutt_mktemp (tempfile, sizeof (tempfile));
1363 1364 1365 1366 1367 1368
  if ((fpout = safe_fopen (tempfile, "w+")) == NULL)
  {
    mutt_perror (tempfile);
    return (NULL);
  }

1369
  mutt_mktemp (smimeerrfile, sizeof (smimeerrfile));
1370 1371 1372
  if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL)
  {
    mutt_perror (smimeerrfile);
1373
    safe_fclose (&fpout);
1374 1375 1376 1377 1378
    mutt_unlink (tempfile);
    return NULL;
  }
  mutt_unlink (smimeerrfile);
  
1379
  mutt_mktemp (smimeinfile, sizeof (smimeinfile));
1380 1381 1382 1383
  if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL)
  {
    mutt_perror (smimeinfile);
    mutt_unlink (tempfile);
1384 1385
    safe_fclose (&fpout);
    safe_fclose (&smimeerr);
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    return NULL;
  }

  *certfile = '\0';
  while (1)
  {
    int off = mutt_strlen (certfile);
    while (*++cert_end && *cert_end != '\n');
    if (!*cert_end) break;
    *cert_end = '\0';
    snprintf (certfile+off, sizeof (certfile)-off, " %s/%s",
	      NONULL(SmimeCertificates), cert_start);
    *cert_end = '\n';
    cert_start = cert_end;
    cert_start++;
  }

  /* write a MIME entity */
  mutt_write_mime_header (a, fptmp);
  fputc ('\n', fptmp);
  mutt_write_mime_body (a, fptmp);
1407
  safe_fclose (&fptmp);
1408 1409 1410 1411 1412 1413

  if ((thepid =
       smime_invoke_encrypt (&smimein, NULL, NULL, -1,
			     fileno (fpout), fileno (smimeerr),
			     smimeinfile, certfile)) == -1)
  {
1414
    safe_fclose (&smimeerr);
1415 1416 1417 1418 1419
    mutt_unlink (smimeinfile);
    mutt_unlink (certfile);
    return (NULL);
  }

1420
  safe_fclose (&smimein);
1421 1422 1423 1424 1425 1426 1427 1428
  
  mutt_wait_filter (thepid);
  mutt_unlink (smimeinfile);
  mutt_unlink (certfile);
  
  fflush (fpout);
  rewind (fpout);
  empty = (fgetc (fpout) == EOF);
1429
  safe_fclose (&fpout);
1430
 
1431 1432 1433 1434 1435 1436 1437
  fflush (smimeerr);
  rewind (smimeerr);
  while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL)
  {
    err = 1;
    fputs (buf, stdout);
  }
1438
  safe_fclose (&smimeerr);
1439 1440 1441 1442 1443 1444 1445 1446

  /* pause if there is any error output from SMIME */
  if (err)
    mutt_any_key_to_continue (NULL);

  if (empty)
  {
    /* fatal error while trying to encrypt message */
Benno Schulenberg's avatar
Benno Schulenberg committed
1447
    if (!err) mutt_any_key_to_continue _("No output from OpenSSL...");
1448 1449 1450 1451 1452 1453 1454 1455 <