2 * Copyright (C) 2001,2002 Oliver Ehli <elmy@acm.org>
3 * Copyright (C) 2002 Mike Schiraldi <raldi@research.netsol.com>
4 * Copyright (C) 2004 g10 Code GmbH
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
26 #include "mutt_curses.h"
27 #include "mutt_menu.h"
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
48 #ifdef HAVE_SYS_RESOURCE_H
49 # include <sys/resource.h>
52 #ifdef CRYPT_BACKEND_CLASSIC_SMIME
54 #include "mutt_crypt.h"
56 struct smime_command_context {
57 const char *key; /* %k */
58 const char *cryptalg; /* %a */
59 const char *fname; /* %f */
60 const char *sig_fname; /* %s */
61 const char *certificates; /* %c */
62 const char *intermediates; /* %i */
71 char trust; /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
72 short public; /* 1=public 0=private */
76 char SmimePass[STRING];
77 time_t SmimeExptime = 0; /* when does the cached passphrase expire? */
80 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
81 static char SmimeCertToUse[_POSIX_PATH_MAX];
82 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
86 * Queries and passphrase handling.
92 /* these are copies from pgp.c */
95 void smime_void_passphrase (void)
97 memset (SmimePass, 0, sizeof (SmimePass));
101 int smime_valid_passphrase (void)
103 time_t now = time (NULL);
105 if (now < SmimeExptime)
106 /* Use cached copy. */
109 smime_void_passphrase();
111 if (mutt_get_password (_("Enter SMIME passphrase:"), SmimePass, sizeof (SmimePass)) == 0)
113 SmimeExptime = time (NULL) + SmimeTimeout;
124 * The OpenSSL interface
127 /* This is almost identical to ppgp's invoking interface. */
129 static const char *_mutt_fmt_smime_command (char *dest,
134 const char *ifstring,
135 const char *elsestring,
140 struct smime_command_context *cctx = (struct smime_command_context *) data;
141 int optional = (flags & M_FORMAT_OPTIONAL);
149 char path[_POSIX_PATH_MAX];
150 char buf1[LONG_STRING], buf2[LONG_STRING];
153 strfcpy (path, NONULL (SmimeCALocation), sizeof (path));
154 mutt_expand_path (path, sizeof (path));
155 mutt_quote_filename (buf1, sizeof (buf1), path);
157 if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
158 snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
160 snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
162 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
163 snprintf (dest, destlen, fmt, buf2);
165 else if (!SmimeCALocation)
171 { /* certificate (list) */
173 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
174 snprintf (dest, destlen, fmt, NONULL(cctx->certificates));
176 else if (!cctx->certificates)
182 { /* intermediate certificates */
184 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
185 snprintf (dest, destlen, fmt, NONULL(cctx->intermediates));
187 else if (!cctx->intermediates)
193 { /* detached signature */
196 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
197 snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
199 else if (!cctx->sig_fname)
208 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
209 snprintf (dest, destlen, fmt, NONULL (cctx->key));
217 { /* algorithm for encryption */
219 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
220 snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
228 { /* file to process */
231 snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
232 snprintf (dest, destlen, fmt, NONULL (cctx->fname));
234 else if (!cctx->fname)
245 mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
247 else if (flags & M_FORMAT_OPTIONAL)
248 mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
256 static void mutt_smime_command (char *d, size_t dlen,
257 struct smime_command_context *cctx, const char *fmt)
259 mutt_FormatString (d, dlen, NONULL(fmt), _mutt_fmt_smime_command,
260 (unsigned long) cctx, 0);
261 dprint (2,(debugfile, "mutt_smime_command: %s\n", d));
267 static pid_t smime_invoke (FILE **smimein, FILE **smimeout, FILE **smimeerr,
268 int smimeinfd, int smimeoutfd, int smimeerrfd,
270 const char *sig_fname,
271 const char *cryptalg,
273 const char *certificates,
274 const char *intermediates,
277 struct smime_command_context cctx;
278 char cmd[HUGE_STRING];
280 memset (&cctx, 0, sizeof (cctx));
282 if (!format || !*format)
286 cctx.sig_fname = sig_fname;
288 cctx.cryptalg = cryptalg;
289 cctx.certificates = certificates;
290 cctx.intermediates = intermediates;
292 mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
294 return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
295 smimeinfd, smimeoutfd, smimeerrfd);
304 * Key and certificate handling.
310 Search the certificate index for given mailbox.
311 return certificate file name.
314 static void smime_entry (char *s, size_t l, MUTTMENU * menu, int num)
316 smime_id *Table = (smime_id*) menu->data;
317 smime_id this = Table[num];
321 truststate = N_("Trusted ");
324 truststate = N_("Verified ");
327 truststate = N_("Unverified");
330 truststate = N_("Expired ");
333 truststate = N_("Revoked ");
336 truststate = N_("Invalid ");
339 truststate = N_("Unknown ");
342 snprintf(s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix, truststate, this.email, this.nick);
344 snprintf(s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix, this.email, this.nick);
351 char* smime_ask_for_key (char *prompt, char *mailbox, short public)
355 long cert_num; /* Will contain the number of certificates.
356 * To be able to get it, the .index file will be read twice... */
357 char index_file[_POSIX_PATH_MAX];
359 char buf[LONG_STRING];
360 char fields[5][STRING];
361 int numFields, hash_suffix, done, cur; /* The current entry */
364 char helpstr[HUGE_STRING*3];
368 if (!prompt) prompt = _("Enter keyID: ");
369 snprintf(index_file, sizeof (index_file), "%s/.index",
370 public ? NONULL(SmimeCertificates) : NONULL(SmimeKeys));
372 index = fopen(index_file, "r");
375 mutt_perror (index_file);
380 while (!feof(index)) {
381 if (fgets(buf, sizeof(buf), index)) cert_num++;
388 if (mutt_get_field(prompt,
389 qry, sizeof(qry), 0))
391 snprintf(title, sizeof(title), _("S/MIME certificates matching \"%s\"."),
395 index = fopen(index_file, "r");
398 mutt_perror (index_file);
403 Table = safe_calloc(cert_num, sizeof (smime_id));
404 while (!feof(index)) {
405 numFields = fscanf (index, MUTT_FORMAT(STRING) " %x.%i " MUTT_FORMAT(STRING), fields[0], &hash,
406 &hash_suffix, fields[2]);
408 fscanf (index, MUTT_FORMAT(STRING) " " MUTT_FORMAT(STRING) "\n", fields[3], fields[4]);
410 /* 0=email 1=name 2=nick 3=intermediate 4=trust */
411 if (numFields < 2) continue;
413 /* Check if query matches this certificate */
414 if (!mutt_stristr(fields[0], qry) &&
415 !mutt_stristr(fields[2], qry))
418 Table[cur].hash = hash;
419 Table[cur].suffix = hash_suffix;
420 strncpy(Table[cur].email, fields[0], sizeof(Table[cur].email));
421 strncpy(Table[cur].nick, fields[2], sizeof(Table[cur].nick));
422 Table[cur].trust = *fields[4];
423 Table[cur].public = public;
429 /* Make Helpstring */
431 mutt_make_help (buf, sizeof (buf), _("Exit "), MENU_SMIME, OP_EXIT);
432 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
433 mutt_make_help (buf, sizeof (buf), _("Select "), MENU_SMIME,
434 OP_GENERIC_SELECT_ENTRY);
435 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
436 mutt_make_help (buf, sizeof(buf), _("Help"), MENU_SMIME, OP_HELP);
437 strcat (helpstr, buf); /* __STRCAT_CHECKED__ */
439 /* Create the menu */
440 menu = mutt_new_menu();
442 menu->make_entry = smime_entry;
443 menu->menu = MENU_SMIME;
444 menu->help = helpstr;
447 /* sorting keys might be done later - TODO */
454 switch (mutt_menuLoop (menu)) {
455 case OP_GENERIC_SELECT_ENTRY:
467 fname = safe_malloc(14); /* Hash + '.' + Suffix + \n + \0 */
468 sprintf(fname, "%.8x.%i\n", Table[cur].hash, Table[cur].suffix);
472 mutt_menuDestroy (&menu);
474 set_option (OPTNEEDREDRAW);
476 if (fname) return fname;
482 char *smime_get_field_from_db (char *mailbox, char *query, short public, short may_ask)
484 int addr_len, query_len, found = 0, ask = 0, choice = 0;
485 char cert_path[_POSIX_PATH_MAX];
486 char buf[LONG_STRING], prompt[STRING];
487 char fields[5][STRING];
491 char key_trust_level = 0;
494 if(!mailbox && !query) return(NULL);
496 addr_len = mailbox ? mutt_strlen (mailbox) : 0;
497 query_len = query ? mutt_strlen (query) : 0;
501 /* index-file format:
502 mailbox certfile label issuer_certfile trust_flags\n
504 certfile is a hash value generated by openssl.
505 Note that this was done according to the OpenSSL
506 specs on their CA-directory.
509 snprintf (cert_path, sizeof (cert_path), "%s/.index",
510 (public ? NONULL(SmimeCertificates) : NONULL(SmimeKeys)));
512 if (!stat (cert_path, &info))
514 if ((fp = safe_fopen (cert_path, "r")) == NULL)
516 mutt_perror (cert_path);
520 while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
521 if (mailbox && !(mutt_strncasecmp (mailbox, buf, addr_len)))
523 numFields = sscanf (buf,
524 MUTT_FORMAT(STRING) " " MUTT_FORMAT(STRING) " "
525 MUTT_FORMAT(STRING) " " MUTT_FORMAT(STRING) " "
526 MUTT_FORMAT(STRING) "\n",
527 fields[0], fields[1],
528 fields[2], fields[3],
532 if (mailbox && public &&
534 *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
539 if (public && *fields[4] == 'u' )
540 snprintf (prompt, sizeof (prompt),
541 _("ID %s is unverified. Do you want to use it for %s ?"),
543 else if (public && *fields[4] == 'v' )
544 snprintf (prompt, sizeof (prompt),
545 _("Use (untrusted!) ID %s for %s ?"),
548 snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
552 if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1)
559 else if (choice == M_NO)
564 else if (choice == M_YES)
566 strfcpy (key, fields[1], sizeof (key));
574 key_trust_level = *fields[4];
575 strfcpy (key, fields[1], sizeof (key));
581 numFields = sscanf (buf,
582 MUTT_FORMAT(STRING) " " MUTT_FORMAT(STRING) " "
583 MUTT_FORMAT(STRING) " " MUTT_FORMAT(STRING) " "
584 MUTT_FORMAT(STRING) "\n",
585 fields[0], fields[1],
586 fields[2], fields[3],
589 /* query = label: return certificate. */
590 if (numFields >= 3 &&
591 !(mutt_strncasecmp (query, fields[2], query_len)))
594 strfcpy (key, fields[1], sizeof (key));
596 /* query = certificate: return intermediate certificate. */
597 else if (numFields >= 4 &&
598 !(mutt_strncasecmp (query, fields[1], query_len)))
601 strfcpy (key, fields[3], sizeof (key));
609 if (public && *fields[4] == 'u' )
610 snprintf (prompt, sizeof (prompt),
611 _("ID %s is unverified. Do you want to use it for %s ?"),
613 else if (public && *fields[4] == 'v' )
614 snprintf (prompt, sizeof (prompt),
615 _("Use (untrusted!) ID %s for %s ?"),
618 snprintf (prompt, sizeof(prompt), _("Use ID %s for %s ?"), key,
620 choice = mutt_yesorno (prompt, M_NO);
621 if (choice == -1 || choice == M_NO)
624 else if (key_trust_level && may_ask)
626 if (key_trust_level == 'u' )
628 snprintf (prompt, sizeof (prompt),
629 _("ID %s is unverified. Do you want to use it for %s ?"),
631 choice = mutt_yesorno (prompt, M_NO);
635 else if (key_trust_level == 'v' )
637 mutt_error (_("Warning: You have not yet decided to trust ID %s. (any key to continue)"), key);
644 /* Note: safe_strdup ("") returns NULL. */
645 return safe_strdup (key);
652 This sets the '*ToUse' variables for an upcoming decryption, where
653 the reuquired key is different from SmimeDefaultKey.
656 void _smime_getkeys (char *mailbox)
661 k = smime_get_field_from_db (mailbox, NULL, 0, 1);
665 snprintf(buf, sizeof(buf), _("Enter keyID for %s: "),
667 k = smime_ask_for_key(buf, mailbox, 0);
672 /* the key used last time. */
673 if (*SmimeKeyToUse &&
674 !mutt_strcasecmp (k, SmimeKeyToUse + mutt_strlen (SmimeKeys)+1))
679 else smime_void_passphrase ();
681 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
682 NONULL(SmimeKeys), k);
684 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
685 NONULL(SmimeCertificates), k);
687 if (mutt_strcasecmp (k, SmimeDefaultKey))
688 smime_void_passphrase ();
696 if (!mutt_strcasecmp (SmimeDefaultKey,
697 SmimeKeyToUse + mutt_strlen (SmimeKeys)+1))
700 smime_void_passphrase ();
703 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
704 NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
706 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
707 NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
710 void smime_getkeys (ENVELOPE *env)
715 if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey)
717 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
718 NONULL (SmimeKeys), SmimeDefaultKey);
720 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
721 NONULL(SmimeCertificates), SmimeDefaultKey);
726 for (t = env->to; !found && t; t = t->next)
727 if (mutt_addr_is_user (t))
730 _smime_getkeys (t->mailbox);
732 for (t = env->cc; !found && t; t = t->next)
733 if (mutt_addr_is_user (t))
736 _smime_getkeys (t->mailbox);
738 if (!found && (t = mutt_default_from()))
740 _smime_getkeys (t->mailbox);
741 rfc822_free_address (&t);
745 /* This routine attempts to find the keyids of the recipients of a message.
746 * It returns NULL if any of the keys can not be found.
749 char *smime_findKeys (ADDRESS *to, ADDRESS *cc, ADDRESS *bcc)
751 char *keyID, *keylist = NULL;
752 size_t keylist_size = 0;
753 size_t keylist_used = 0;
754 ADDRESS *tmp = NULL, *addr = NULL;
755 ADDRESS **last = &tmp;
759 const char *fqdn = mutt_fqdn (1);
761 for (i = 0; i < 3; i++)
765 case 0: p = to; break;
766 case 1: p = cc; break;
767 case 2: p = bcc; break;
771 *last = rfc822_cpy_adr (p);
773 last = &((*last)->next);
777 rfc822_qualify (tmp, fqdn);
779 tmp = mutt_remove_duplicates (tmp);
781 for (p = tmp; p ; p = p->next)
783 char buf[LONG_STRING];
787 if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL)
789 snprintf(buf, sizeof(buf),
790 _("Enter keyID for %s: "),
792 keyID = smime_ask_for_key(buf, q->mailbox, 1);
796 mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
798 rfc822_free_address (&tmp);
799 rfc822_free_address (&addr);
803 keylist_size += mutt_strlen (keyID) + 2;
804 safe_realloc (&keylist, keylist_size);
805 sprintf (keylist + keylist_used, "%s\n", keyID); /* __SPRINTF_CHECKED__ */
806 keylist_used = mutt_strlen (keylist);
808 rfc822_free_address (&addr);
811 rfc822_free_address (&tmp);
820 static int smime_handle_cert_email (char *certificate, char *mailbox,
821 int copy, char ***buffer, int *num)
823 FILE *fpout = NULL, *fperr = NULL;
824 char tmpfname[_POSIX_PATH_MAX];
826 int ret = -1, count = 0;
829 mutt_mktemp (tmpfname);
830 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
832 mutt_perror (tmpfname);
835 mutt_unlink (tmpfname);
837 mutt_mktemp (tmpfname);
838 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL)
841 mutt_perror (tmpfname);
844 mutt_unlink (tmpfname);
846 if ((thepid = smime_invoke (NULL, NULL, NULL,
847 -1, fileno (fpout), fileno (fperr),
848 certificate, NULL, NULL, NULL, NULL, NULL,
849 SmimeGetCertEmailCommand))== -1)
851 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
857 mutt_wait_filter (thepid);
865 while ((fgets (email, sizeof (email), fpout)))
867 *(email + mutt_strlen (email)-1) = '\0';
868 if(mutt_strncasecmp (email, mailbox, mutt_strlen (mailbox)) == 0)
871 ret = ret < 0 ? 0 : ret;
878 mutt_copy_stream (fperr, stdout);
879 mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
886 if(copy && buffer && num)
889 *buffer = safe_calloc(sizeof(char*), count);
893 while ((fgets (email, sizeof (email), fpout)))
895 *(email + mutt_strlen (email) - 1) = '\0';
896 (*buffer)[count] = safe_calloc(1, mutt_strlen (email) + 1);
897 strncpy((*buffer)[count], email, mutt_strlen (email));
901 else if(copy) ret = 2;
911 static char *smime_extract_certificate (char *infile)
913 FILE *fpout = NULL, *fperr = NULL;
914 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
915 char tmpfname[_POSIX_PATH_MAX];
920 mutt_mktemp (tmpfname);
921 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
923 mutt_perror (tmpfname);
926 mutt_unlink (tmpfname);
928 mutt_mktemp (pk7out);
929 if ((fpout = safe_fopen (pk7out, "w+")) == NULL)
932 mutt_perror (pk7out);
936 /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
937 extract the full set of certificates directly.
939 if ((thepid = smime_invoke (NULL, NULL, NULL,
940 -1, fileno (fpout), fileno (fperr),
941 infile, NULL, NULL, NULL, NULL, NULL,
942 SmimePk7outCommand))== -1)
944 mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
947 mutt_unlink (pk7out);
951 mutt_wait_filter (thepid);
958 empty = (fgetc (fpout) == EOF);
961 mutt_perror (pk7out);
962 mutt_copy_stream (fperr, stdout);
965 mutt_unlink (pk7out);
972 mutt_mktemp (certfile);
973 if ((fpout = safe_fopen (certfile, "w+")) == NULL)
976 mutt_unlink (pk7out);
977 mutt_perror (certfile);
981 /* Step 2: Extract the certificates from a PKCS#7 structure.
983 if ((thepid = smime_invoke (NULL, NULL, NULL,
984 -1, fileno (fpout), fileno (fperr),
985 pk7out, NULL, NULL, NULL, NULL, NULL,
986 SmimeGetCertCommand))== -1)
988 mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
991 mutt_unlink (pk7out);
992 mutt_unlink (certfile);
996 mutt_wait_filter (thepid);
998 mutt_unlink (pk7out);
1004 empty = (fgetc (fpout) == EOF);
1007 mutt_copy_stream (fperr, stdout);
1010 mutt_unlink (certfile);
1017 return safe_strdup (certfile);
1020 static char *smime_extract_signer_certificate (char *infile)
1022 FILE *fpout = NULL, *fperr = NULL;
1023 char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
1024 char tmpfname[_POSIX_PATH_MAX];
1029 mutt_mktemp (tmpfname);
1030 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
1032 mutt_perror (tmpfname);
1035 mutt_unlink (tmpfname);
1038 mutt_mktemp (certfile);
1039 if ((fpout = safe_fopen (certfile, "w+")) == NULL)
1042 mutt_perror (certfile);
1046 /* Extract signer's certificate
1048 if ((thepid = smime_invoke (NULL, NULL, NULL,
1049 -1, -1, fileno (fperr),
1050 infile, NULL, NULL, NULL, certfile, NULL,
1051 SmimeGetSignerCertCommand))== -1)
1053 mutt_any_key_to_continue (_("Error: unable to create OpenSSL subprocess!"));
1056 mutt_unlink (pk7out);
1057 mutt_unlink (certfile);
1061 mutt_wait_filter (thepid);
1067 empty = (fgetc (fpout) == EOF);
1071 mutt_copy_stream (fperr, stdout);
1072 mutt_any_key_to_continue (NULL);
1075 mutt_unlink (certfile);
1082 return safe_strdup (certfile);
1088 /* Add a certificate and update index file (externally). */
1090 void smime_invoke_import (char *infile, char *mailbox)
1092 char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1093 FILE *smimein=NULL, *fpout = NULL, *fperr = NULL;
1096 mutt_mktemp (tmpfname);
1097 if ((fperr = safe_fopen (tmpfname, "w+")) == NULL)
1099 mutt_perror (tmpfname);
1102 mutt_unlink (tmpfname);
1104 mutt_mktemp (tmpfname);
1105 if ((fpout = safe_fopen (tmpfname, "w+")) == NULL)
1108 mutt_perror (tmpfname);
1111 mutt_unlink (tmpfname);
1115 if (option (OPTASKCERTLABEL))
1116 mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1119 if ((certfile = smime_extract_certificate(infile)))
1123 if ((thepid = smime_invoke (&smimein, NULL, NULL,
1124 -1, fileno(fpout), fileno(fperr),
1125 certfile, NULL, NULL, NULL, NULL, NULL,
1126 SmimeImportCertCommand))== -1)
1128 mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1131 fputs (buf, smimein);
1132 fputc ('\n', smimein);
1135 mutt_wait_filter (thepid);
1137 mutt_unlink (certfile);
1146 mutt_copy_stream (fpout, stdout);
1147 mutt_copy_stream (fperr, stdout);
1156 int smime_verify_sender(HEADER *h)
1158 char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1162 mutt_mktemp (tempfname);
1163 if (!(fpout = safe_fopen (tempfname, "w")))
1165 mutt_perror (tempfname);
1169 if(h->security & ENCRYPT)
1170 mutt_copy_message (fpout, Context, h,
1171 M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1172 CH_MIME|CH_WEED|CH_NONEWLINE);
1174 mutt_copy_message (fpout, Context, h, 0, 0);
1181 h->env->from = mutt_expand_aliases (h->env->from);
1182 mbox = h->env->from->mailbox;
1184 else if (h->env->sender)
1186 h->env->sender = mutt_expand_aliases (h->env->sender);
1187 mbox = h->env->sender->mailbox;
1192 if ((certfile = smime_extract_signer_certificate(tempfname)))
1194 mutt_unlink(tempfname);
1195 if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL))
1198 mutt_any_key_to_continue(NULL);
1202 mutt_unlink(certfile);
1206 mutt_any_key_to_continue(_("no certfile"));
1209 mutt_any_key_to_continue(_("no mbox"));
1211 mutt_unlink(tempfname);
1224 * Creating S/MIME - bodies.
1231 pid_t smime_invoke_encrypt (FILE **smimein, FILE **smimeout, FILE **smimeerr,
1232 int smimeinfd, int smimeoutfd, int smimeerrfd,
1233 const char *fname, const char *uids)
1235 return smime_invoke (smimein, smimeout, smimeerr,
1236 smimeinfd, smimeoutfd, smimeerrfd,
1237 fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1238 SmimeEncryptCommand);
1243 pid_t smime_invoke_sign (FILE **smimein, FILE **smimeout, FILE **smimeerr,
1244 int smimeinfd, int smimeoutfd, int smimeerrfd,
1247 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1248 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1249 SmimeCertToUse, SmimeIntermediateToUse,
1256 BODY *smime_build_smime_entity (BODY *a, char *certlist)
1258 char buf[LONG_STRING], certfile[LONG_STRING];
1259 char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1260 char smimeinfile[_POSIX_PATH_MAX];
1261 char *cert_start = certlist, *cert_end = certlist;
1262 FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1267 mutt_mktemp (tempfile);
1268 if ((fpout = safe_fopen (tempfile, "w+")) == NULL)
1270 mutt_perror (tempfile);
1274 mutt_mktemp (smimeerrfile);
1275 if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL)
1277 mutt_perror (smimeerrfile);
1279 mutt_unlink (tempfile);
1282 mutt_unlink (smimeerrfile);
1284 mutt_mktemp (smimeinfile);
1285 if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL)
1287 mutt_perror (smimeinfile);
1288 mutt_unlink (tempfile);
1297 int off = mutt_strlen (certfile);
1298 while (*++cert_end && *cert_end != '\n');
1299 if (!*cert_end) break;
1301 snprintf (certfile+off, sizeof (certfile)-off, " %s/%s",
1302 NONULL(SmimeCertificates), cert_start);
1304 cert_start = cert_end;
1308 /* write a MIME entity */
1309 mutt_write_mime_header (a, fptmp);
1310 fputc ('\n', fptmp);
1311 mutt_write_mime_body (a, fptmp);
1315 smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1316 fileno (fpout), fileno (smimeerr),
1317 smimeinfile, certfile)) == -1)
1320 mutt_unlink (smimeinfile);
1321 mutt_unlink (certfile);
1327 mutt_wait_filter (thepid);
1328 mutt_unlink (smimeinfile);
1329 mutt_unlink (certfile);
1333 empty = (fgetc (fpout) == EOF);
1338 while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL)
1341 fputs (buf, stdout);
1345 /* pause if there is any error output from SMIME */
1347 mutt_any_key_to_continue (NULL);
1351 /* fatal error while trying to encrypt message */
1352 if (!err) mutt_any_key_to_continue _("No output from OpenSSL..");
1353 mutt_unlink (tempfile);
1357 t = mutt_new_body ();
1358 t->type = TYPEAPPLICATION;
1359 t->subtype = safe_strdup ("x-pkcs7-mime");
1360 mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1361 mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1362 t->encoding = ENCBASE64; /* The output of OpenSSL SHOULD be binary */
1364 t->disposition = DISPATTACH;
1365 t->d_filename = safe_strdup ("smime.p7m");
1366 t->filename = safe_strdup (tempfile);
1367 t->unlink = 1; /*delete after sending the message */
1377 BODY *smime_sign_message (BODY *a )
1380 char buffer[LONG_STRING];
1381 char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1382 FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1386 char *intermediates = smime_get_field_from_db(NULL, SmimeDefaultKey, 1, 1);
1390 mutt_message(_("Warning: Intermediate certificate not found."));
1391 intermediates = SmimeDefaultKey; /* so openssl won't complain in any case */
1394 convert_to_7bit (a); /* Signed data _must_ be in 7-bit format. */
1396 mutt_mktemp (filetosign);
1397 if ((sfp = safe_fopen (filetosign, "w+")) == NULL)
1399 mutt_perror (filetosign);
1403 mutt_mktemp (signedfile);
1404 if ((smimeout = safe_fopen (signedfile, "w+")) == NULL)
1406 mutt_perror (signedfile);
1408 mutt_unlink (filetosign);
1412 mutt_write_mime_header (a, sfp);
1414 mutt_write_mime_body (a, sfp);
1419 snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1420 NONULL(SmimeKeys), SmimeDefaultKey);
1422 snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1423 NONULL(SmimeCertificates), SmimeDefaultKey);
1425 snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1426 NONULL(SmimeCertificates), intermediates);
1430 if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1431 -1, fileno (smimeout), -1, filetosign)) == -1)
1433 mutt_perror _("Can't open OpenSSL subprocess!");
1435 mutt_unlink (signedfile);
1436 mutt_unlink (filetosign);
1439 fputs (SmimePass, smimein);
1440 fputc ('\n', smimein);
1444 mutt_wait_filter (thepid);
1446 /* check for errors from OpenSSL */
1450 while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL)
1453 fputs (buffer, stdout);
1460 empty = (fgetc (smimeout) == EOF);
1463 mutt_unlink (filetosign);
1467 mutt_any_key_to_continue (NULL);
1471 mutt_any_key_to_continue _("No output from OpenSSL...");
1472 mutt_unlink (signedfile);
1473 return (NULL); /* fatal error while signing */
1476 t = mutt_new_body ();
1477 t->type = TYPEMULTIPART;
1478 t->subtype = safe_strdup ("signed");
1479 t->encoding = ENC7BIT;
1481 t->disposition = DISPINLINE;
1483 mutt_generate_boundary (&t->parameter);
1484 /* check if this can be extracted from private key somehow.... */
1485 mutt_set_parameter ("micalg", "sha1", &t->parameter);
1486 mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1492 t->parts->next = mutt_new_body ();
1494 t->type = TYPEAPPLICATION;
1495 t->subtype = safe_strdup ("x-pkcs7-signature");
1496 t->filename = safe_strdup (signedfile);
1497 t->d_filename = safe_strdup ("smime.p7s");
1499 t->disposition = DISPATTACH;
1500 t->encoding = ENCBASE64;
1501 t->unlink = 1; /* ok to remove this file after sending. */
1513 * Handling S/MIME - bodies.
1522 pid_t smime_invoke_verify (FILE **smimein, FILE **smimeout, FILE **smimeerr,
1523 int smimeinfd, int smimeoutfd, int smimeerrfd,
1524 const char *fname, const char *sig_fname, int opaque)
1526 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1527 smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1528 (opaque ? SmimeVerifyOpaqueCommand : SmimeVerifyCommand));
1533 pid_t smime_invoke_decrypt (FILE **smimein, FILE **smimeout, FILE **smimeerr,
1534 int smimeinfd, int smimeoutfd, int smimeerrfd,
1537 return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1538 smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1539 SmimeCertToUse, NULL, SmimeDecryptCommand);
1544 int smime_verify_one (BODY *sigbdy, STATE *s, const char *tempfile)
1546 char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1547 FILE *fp=NULL, *smimeout=NULL, *smimeerr=NULL;
1552 size_t tmplength = 0;
1553 int origType = sigbdy->type;
1554 char *savePrefix = NULL;
1557 snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1559 /* decode to a tempfile, saving the original destination */
1561 if ((s->fpout = safe_fopen (signedfile, "w")) == NULL)
1563 mutt_perror (signedfile);
1566 /* decoding the attachment changes the size and offset, so save a copy
1567 * of the "real" values now, and restore them after processing
1569 tmplength = sigbdy->length;
1570 tmpoffset = sigbdy->offset;
1572 /* if we are decoding binary bodies, we don't want to prefix each
1573 * line with the prefix or else the data will get corrupted.
1575 savePrefix = s->prefix;
1578 mutt_decode_attachment (sigbdy, s);
1580 sigbdy->length = ftell (s->fpout);
1584 /* restore final destination and substitute the tempfile for input */
1587 s->fpin = fopen (signedfile, "r");
1589 /* restore the prefix */
1590 s->prefix = savePrefix;
1592 sigbdy->type = origType;
1595 mutt_mktemp (smimeerrfile);
1596 if (!(smimeerr = safe_fopen (smimeerrfile, "w+")))
1598 mutt_perror (smimeerrfile);
1599 mutt_unlink (signedfile);
1603 crypt_current_time (s, "OpenSSL");
1605 if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1606 -1, -1, fileno (smimeerr),
1607 tempfile, signedfile, 0)) != -1)
1612 if (mutt_wait_filter (thepid))
1623 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1624 if (linelen && !mutt_strcasecmp (line, "verification successful"))
1633 mutt_copy_stream (smimeerr, s->fpout);
1636 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1638 mutt_unlink (signedfile);
1639 mutt_unlink (smimeerrfile);
1641 sigbdy->length = tmplength;
1642 sigbdy->offset = tmpoffset;
1644 /* restore the original source stream */
1657 This handles application/pkcs7-mime which can either be a signed
1658 or an encrypted message.
1661 static BODY *smime_handle_entity (BODY *m, STATE *s, FILE *outFile)
1666 char buf[HUGE_STRING];
1667 char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1668 char tmpfname[_POSIX_PATH_MAX];
1669 char tmptmpfname[_POSIX_PATH_MAX];
1670 FILE *smimeout = NULL, *smimein=NULL, *smimeerr=NULL;
1671 FILE *tmpfp=NULL, *tmpfp_buffer=NULL, *fpout=NULL;
1675 unsigned int type = mutt_is_application_smime (m);
1677 if (!(type & APPLICATION_SMIME)) return NULL;
1679 mutt_mktemp (outfile);
1680 if ((smimeout = safe_fopen (outfile, "w+")) == NULL)
1682 mutt_perror (outfile);
1686 mutt_mktemp (errfile);
1687 if ((smimeerr = safe_fopen (errfile, "w+")) == NULL)
1689 mutt_perror (errfile);
1690 fclose (smimeout); smimeout = NULL;
1693 mutt_unlink (errfile);
1696 mutt_mktemp (tmpfname);
1697 if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL)
1699 mutt_perror (tmpfname);
1700 fclose (smimeout); smimeout = NULL;
1701 fclose (smimeerr); smimeerr = NULL;
1705 fseek (s->fpin, m->offset, 0);
1706 last_pos = m->offset;
1708 mutt_copy_bytes (s->fpin, tmpfp, m->length);
1713 if ((type & ENCRYPT) &&
1714 (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1715 fileno (smimeout), fileno (smimeerr), tmpfname)) == -1)
1717 fclose (smimeout); smimeout = NULL;
1718 mutt_unlink (tmpfname);
1719 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1722 else if ((type & SIGNOPAQUE) &&
1723 (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1724 fileno (smimeout), fileno (smimeerr), NULL,
1725 tmpfname, SIGNOPAQUE)) == -1)
1727 fclose (smimeout); smimeout = NULL;
1728 mutt_unlink (tmpfname);
1729 state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1736 if (!smime_valid_passphrase ())
1737 smime_void_passphrase ();
1738 fputs (SmimePass, smimein);
1739 fputc ('\n', smimein);
1744 mutt_wait_filter (thepid);
1745 mutt_unlink (tmpfname);
1748 if (s->flags & M_DISPLAY)
1752 if ((c = fgetc (smimeerr)) != EOF)
1754 ungetc (c, smimeerr);
1756 crypt_current_time (s, "OpenSSL");
1757 mutt_copy_stream (smimeerr, s->fpout);
1758 state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1762 state_attach_puts (_("[-- The following data is S/MIME"
1763 " encrypted --]\n"), s);
1765 state_attach_puts (_("[-- The following data is S/MIME signed --]\n"), s);
1773 if (outFile) fpout = outFile;
1776 mutt_mktemp (tmptmpfname);
1777 if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL)
1779 mutt_perror(tmptmpfname);
1780 fclose (smimeout); smimeout = NULL;
1784 while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL)
1786 len = mutt_strlen (buf);
1787 if (len > 1 && buf[len - 2] == '\r')
1798 if ((p = mutt_read_mime_header (fpout, 0)) != NULL)
1800 fstat (fileno (fpout), &info);
1801 p->length = info.st_size - p->offset;
1803 mutt_parse_part (fpout, p);
1807 tmpfp_buffer = s->fpin;
1809 mutt_body_handler (p, s);
1810 s->fpin = tmpfp_buffer;
1816 mutt_unlink (outfile);
1821 mutt_unlink (tmptmpfname);
1826 if (s->flags & M_DISPLAY)
1829 state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1831 state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1834 if (type & SIGNOPAQUE)
1842 line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1843 if (linelen && !mutt_strcasecmp (line, "verification successful"))
1849 m->goodsig = p->goodsig;
1850 m->badsig = p->badsig;
1861 int smime_decrypt_mime (FILE *fpin, FILE **fpout, BODY *b, BODY **cur)
1865 char tempfile[_POSIX_PATH_MAX];
1867 long tmpoffset = b->offset;
1868 size_t tmplength = b->length;
1869 int origType = b->type;
1872 if (!mutt_is_application_smime (b))
1878 memset (&s, 0, sizeof (s));
1880 fseek (s.fpin, b->offset, 0);
1882 mutt_mktemp (tempfile);
1883 if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL)
1885 mutt_perror (tempfile);
1889 mutt_unlink (tempfile);
1891 mutt_decode_attachment (b, &s);
1893 b->length = ftell (s.fpout);
1899 mutt_mktemp (tempfile);
1900 if ((*fpout = safe_fopen (tempfile, "w+")) == NULL)
1902 mutt_perror (tempfile);
1905 mutt_unlink (tempfile);
1907 *cur = smime_handle_entity (b, &s, *fpout);
1908 (*cur)->goodsig = b->goodsig;
1909 (*cur)->badsig = b->badsig;
1911 b->length = tmplength;
1912 b->offset = tmpoffset;
1921 void smime_application_smime_handler (BODY *m, STATE *s)
1924 smime_handle_entity (m, s, NULL);
1928 int smime_send_menu (HEADER *msg, int *redraw)
1932 if (!(WithCrypto & APPLICATION_SMIME))
1933 return msg->security;
1935 switch (mutt_multi_choice (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1938 case 1: /* (e)ncrypt */
1939 msg->security |= ENCRYPT;
1940 msg->security &= ~SIGN;
1943 case 3: /* encrypt (w)ith */
1944 msg->security |= ENCRYPT;
1945 switch (mutt_multi_choice (_("1: DES, 2: Triple-DES, 3: RC2-40,"
1946 " 4: RC2-64, 5: RC2-128, or (f)orget it? "),
1949 mutt_str_replace (&SmimeCryptAlg, "des");
1952 mutt_str_replace (&SmimeCryptAlg, "des3");
1955 mutt_str_replace (&SmimeCryptAlg, "rc2-40");
1958 mutt_str_replace (&SmimeCryptAlg, "rc2-64");
1961 mutt_str_replace (&SmimeCryptAlg, "rc2-128");
1963 case 6: /* forget it */
1968 case 2: /* (s)ign */
1970 if(!SmimeDefaultKey)
1971 mutt_message _("Can't sign: No key specified. Use Sign As.");
1974 msg->security |= SIGN;
1975 msg->security &= ~ENCRYPT;
1979 case 4: /* sign (a)s */
1981 if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0)))
1983 p[mutt_strlen (p)-1] = '\0';
1984 mutt_str_replace (&SmimeDefaultKey, p);
1986 msg->security |= SIGN;
1988 /* probably need a different passphrase */
1989 crypt_smime_void_passphrase ();
1993 msg->security &= ~SIGN;
1996 *redraw = REDRAW_FULL;
1999 case 5: /* (b)oth */
2000 msg->security |= (ENCRYPT | SIGN);
2003 case 6: /* (f)orget it */
2004 case 7: /* (c)lear */
2009 if (msg->security && msg->security != APPLICATION_SMIME)
2010 msg->security |= APPLICATION_SMIME;
2014 return (msg->security);
2018 #endif /* CRYPT_BACKEND_CLASSIC_SMIME */