5e9fae06d1ce85a937987c61edd3524b65157859
[apps/madmutt.git] / lib-crypt / smime.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 2001,2002 Oliver Ehli <elmy@acm.org>
4  * Copyright (C) 2002 Mike Schiraldi <raldi@research.netsol.com>
5  * Copyright (C) 2004 g10 Code GmbH
6  *
7  * This file is part of mutt-ng, see http://www.muttng.org/.
8  * It's licensed under the GNU General Public License,
9  * please see the file GPL in the top level source directory.
10  */
11
12 #if HAVE_CONFIG_H
13 # include "config.h"
14 #endif
15
16 #include <lib-lib/mem.h>
17 #include <lib-lib/str.h>
18 #include <lib-lib/macros.h>
19 #include <lib-lib/file.h>
20 #include <lib-lib/debug.h>
21
22 #include <lib-mime/mime.h>
23
24 #include <lib-ui/curses.h>
25 #include <lib-ui/enter.h>
26 #include <lib-ui/menu.h>
27
28 #include "mutt.h"
29 #include "handler.h"
30 #include "copy.h"
31
32
33 #include <sys/wait.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <sys/stat.h>
38 #include <errno.h>
39 #include <ctype.h>
40
41 #ifdef HAVE_LOCALE_H
42 #include <locale.h>
43 #endif
44
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48
49 #ifdef HAVE_SYS_RESOURCE_H
50 # include <sys/resource.h>
51 #endif
52
53 #include "crypt.h"
54
55 struct smime_command_context {
56   const char *key;              /* %k */
57   const char *cryptalg;         /* %a */
58   const char *fname;            /* %f */
59   const char *sig_fname;        /* %s */
60   const char *certificates;     /* %c */
61   const char *intermediates;    /* %i */
62 };
63
64
65 typedef struct {
66   unsigned int hash;
67   char suffix;
68   char email[256];
69   char nick[256];
70   char trust;                   /* i=Invalid r=revoked e=expired u=unverified v=verified t=trusted */
71   short public;                 /* 1=public 0=private */
72 } smime_id;
73
74
75 char SmimePass[STRING];
76 time_t SmimeExptime = 0;        /* when does the cached passphrase expire? */
77
78
79 static char SmimeKeyToUse[_POSIX_PATH_MAX] = { 0 };
80 static char SmimeCertToUse[_POSIX_PATH_MAX];
81 static char SmimeIntermediateToUse[_POSIX_PATH_MAX];
82
83
84 /*
85  * Create a format string to be used with scanf.
86  * To use it, write, for instance, MUTT_FORMAT(HUGE_STRING).
87  * 
88  * See K&R 2nd ed, p. 231 for an explanation.
89  */
90 #define _MUTT_FORMAT_2(a,b)     "%" a  b
91 #define _MUTT_FORMAT_1(a, b)    _MUTT_FORMAT_2(#a, b)
92 #define MUTT_FORMAT(a)          _MUTT_FORMAT_1(a, "s")
93
94
95 /*
96  *     Queries and passphrase handling.
97  */
98
99
100 /* these are copies from pgp.c */
101
102
103 void smime_void_passphrase (void)
104 {
105   p_clear(SmimePass, countof(SmimePass));
106   SmimeExptime = 0;
107 }
108
109 int smime_valid_passphrase (void)
110 {
111   time_t now = time (NULL);
112
113   if (now < SmimeExptime)
114     /* Use cached copy.  */
115     return 1;
116
117   smime_void_passphrase ();
118
119   if (mutt_get_field_unbuffered (_("Enter S/MIME passphrase:"), SmimePass,
120                                  sizeof (SmimePass), M_PASS) == 0) {
121     SmimeExptime = time (NULL) + SmimeTimeout;
122     return (1);
123   }
124   else
125     SmimeExptime = 0;
126
127   return 0;
128 }
129
130
131 /*
132  *     The OpenSSL interface
133  */
134
135 /* This is almost identical to ppgp's invoking interface. */
136
137 static const char *
138 _mutt_fmt_smime_command (char *dest, ssize_t destlen, char op,
139                          const char *src, const char *prefix,
140                          const char *ifstring, const char *elsestring,
141                          unsigned long data, format_flag flags)
142 {
143   char fmt[16];
144   struct smime_command_context *cctx = (struct smime_command_context *) data;
145   int optional = (flags & M_FORMAT_OPTIONAL);
146
147   switch (op) {
148   case 'C':
149     {
150       if (!optional) {
151         char path[_POSIX_PATH_MAX];
152         char buf1[LONG_STRING], buf2[LONG_STRING];
153         struct stat sb;
154
155         m_strcpy(path, sizeof(path), NONULL(SmimeCALocation));
156         mutt_expand_path (path, sizeof (path));
157         mutt_quote_filename (buf1, sizeof (buf1), path);
158
159         if (stat (path, &sb) != 0 || !S_ISDIR (sb.st_mode))
160           snprintf (buf2, sizeof (buf2), "-CAfile %s", buf1);
161         else
162           snprintf (buf2, sizeof (buf2), "-CApath %s", buf1);
163
164         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
165         snprintf (dest, destlen, fmt, buf2);
166       }
167       else if (!SmimeCALocation)
168         optional = 0;
169       break;
170     }
171
172   case 'c':
173     {                           /* certificate (list) */
174       if (!optional) {
175         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
176         snprintf (dest, destlen, fmt, NONULL (cctx->certificates));
177       }
178       else if (!cctx->certificates)
179         optional = 0;
180       break;
181     }
182
183   case 'i':
184     {                           /* intermediate certificates  */
185       if (!optional) {
186         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
187         snprintf (dest, destlen, fmt, NONULL (cctx->intermediates));
188       }
189       else if (!cctx->intermediates)
190         optional = 0;
191       break;
192     }
193
194   case 's':
195     {                           /* detached signature */
196       if (!optional) {
197         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
198         snprintf (dest, destlen, fmt, NONULL (cctx->sig_fname));
199       }
200       else if (!cctx->sig_fname)
201         optional = 0;
202       break;
203     }
204
205   case 'k':
206     {                           /* private key */
207       if (!optional) {
208         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
209         snprintf (dest, destlen, fmt, NONULL (cctx->key));
210       }
211       else if (!cctx->key)
212         optional = 0;
213       break;
214     }
215
216   case 'a':
217     {                           /* algorithm for encryption */
218       if (!optional) {
219         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
220         snprintf (dest, destlen, fmt, NONULL (cctx->cryptalg));
221       }
222       else if (!cctx->key)
223         optional = 0;
224       break;
225     }
226
227   case 'f':
228     {                           /* file to process */
229       if (!optional) {
230         snprintf (fmt, sizeof (fmt), "%%%ss", prefix);
231         snprintf (dest, destlen, fmt, NONULL (cctx->fname));
232       }
233       else if (!cctx->fname)
234         optional = 0;
235       break;
236     }
237
238   default:
239     *dest = '\0';
240     break;
241   }
242
243   if (optional)
244     mutt_FormatString (dest, destlen, ifstring, _mutt_fmt_smime_command,
245                        data, 0);
246   else if (flags & M_FORMAT_OPTIONAL)
247     mutt_FormatString (dest, destlen, elsestring, _mutt_fmt_smime_command,
248                        data, 0);
249
250   return (src);
251 }
252
253
254
255 static void mutt_smime_command (char *d, ssize_t dlen,
256                                 struct smime_command_context *cctx,
257                                 const char *fmt)
258 {
259   mutt_FormatString (d, dlen, NONULL (fmt), _mutt_fmt_smime_command,
260                      (unsigned long) cctx, 0);
261   debug_print (2, ("%s\n", d));
262 }
263
264 static pid_t smime_invoke (FILE ** smimein, FILE ** smimeout,
265                            FILE ** smimeerr, int smimeinfd, int smimeoutfd,
266                            int smimeerrfd, const char *fname,
267                            const char *sig_fname, const char *cryptalg,
268                            const char *key, const char *certificates,
269                            const char *intermediates, const char *format)
270 {
271   struct smime_command_context cctx;
272   char cmd[HUGE_STRING];
273
274   p_clear(&cctx, 1);
275
276   if (!format || !*format)
277     return (pid_t) - 1;
278
279   cctx.fname = fname;
280   cctx.sig_fname = sig_fname;
281   cctx.key = key;
282   cctx.cryptalg = cryptalg;
283   cctx.certificates = certificates;
284   cctx.intermediates = intermediates;
285
286   mutt_smime_command (cmd, sizeof (cmd), &cctx, format);
287
288   return mutt_create_filter_fd (cmd, smimein, smimeout, smimeerr,
289                                 smimeinfd, smimeoutfd, smimeerrfd);
290 }
291
292
293
294
295
296
297 /*
298  *    Key and certificate handling.
299  */
300
301
302
303 /* 
304    Search the certificate index for given mailbox.
305    return certificate file name.
306 */
307
308 static void smime_entry (char *s, ssize_t l, MUTTMENU * menu, int num)
309 {
310   smime_id *Table = (smime_id *) menu->data;
311   smime_id this = Table[num];
312   const char *truststate;
313
314   switch (this.trust) {
315   case 't':
316     truststate = N_("Trusted   ");
317     break;
318   case 'v':
319     truststate = N_("Verified  ");
320     break;
321   case 'u':
322     truststate = N_("Unverified");
323     break;
324   case 'e':
325     truststate = N_("Expired   ");
326     break;
327   case 'r':
328     truststate = N_("Revoked   ");
329     break;
330   case 'i':
331     truststate = N_("Invalid   ");
332     break;
333   default:
334     truststate = N_("Unknown   ");
335   }
336   if (this.public)
337     snprintf (s, l, " 0x%.8X.%i %s %-35.35s %s", this.hash, this.suffix,
338               truststate, this.email, this.nick);
339   else
340     snprintf (s, l, " 0x%.8X.%i %-35.35s %s", this.hash, this.suffix,
341               this.email, this.nick);
342 }
343
344
345
346
347
348 char *smime_ask_for_key (char *prompt, char *mailbox __attribute__((unused)),
349                          short public)
350 {
351   char *fname;
352   smime_id *Table;
353   long cert_num;                /* Will contain the number of certificates.
354                                  * To be able to get it, the .index file will be read twice... */
355   char index_file[_POSIX_PATH_MAX];
356   FILE *idx;
357   char buf[LONG_STRING];
358   char fields[5][STRING];
359   int numFields, hash_suffix, done, cur;        /* The current entry */
360   MUTTMENU *menu;
361   unsigned int hash;
362   char helpstr[HUGE_STRING * 3];
363   char qry[256];
364   char title[256];
365
366   if (!prompt)
367     prompt = _("Enter keyID: ");
368   snprintf (index_file, sizeof (index_file), "%s/.index",
369             public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys));
370
371   idx = fopen (index_file, "r");
372   if (idx == NULL) {
373     mutt_perror (index_file);
374     return NULL;
375   }
376   /* Count Lines */
377   cert_num = 0;
378   while (!feof (idx)) {
379     if (fgets (buf, sizeof (buf), idx))
380       cert_num++;
381   }
382   fclose (idx);
383
384   for (;;) {
385     *qry = 0;
386     if (mutt_get_field (prompt, qry, sizeof (qry), 0))
387       return NULL;
388     snprintf (title, sizeof (title),
389               _("S/MIME certificates matching \"%s\"."), qry);
390
391
392     idx = fopen (index_file, "r");
393     if (idx == NULL) {
394       mutt_perror (index_file);
395       return NULL;
396     }
397     /* Read Entries */
398     cur = 0;
399     Table = p_new(smime_id, cert_num);
400     while (!feof (idx)) {
401       numFields =
402         fscanf (idx, MUTT_FORMAT (STRING) " %x.%i " MUTT_FORMAT (STRING),
403                 fields[0], &hash, &hash_suffix, fields[2]);
404       if (public)
405         fscanf (idx, MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) "\n",
406                 fields[3], fields[4]);
407
408       /* 0=email 1=name 2=nick 3=intermediate 4=trust */
409       if (numFields < 2)
410         continue;
411
412       /* Check if query matches this certificate */
413       if (!m_stristr(fields[0], qry) && !m_stristr(fields[2], qry))
414         continue;
415
416       Table[cur].hash = hash;
417       Table[cur].suffix = hash_suffix;
418       m_strcpy(Table[cur].email, sizeof(Table[cur].email), fields[0]);
419       m_strcpy(Table[cur].nick,  sizeof(Table[cur].nick),  fields[2]);
420       Table[cur].trust = *fields[4];
421       Table[cur].public = public;
422
423       cur++;
424     }
425     fclose (idx);
426
427     /* Make Helpstring */
428     helpstr[0] = 0;
429     mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_SMIME, OP_EXIT);
430     strcat (helpstr, buf);      /* __STRCAT_CHECKED__ */
431     mutt_make_help (buf, sizeof (buf), _("Select  "), MENU_SMIME,
432                     OP_GENERIC_SELECT_ENTRY);
433     strcat (helpstr, buf);      /* __STRCAT_CHECKED__ */
434     mutt_make_help (buf, sizeof (buf), _("Help"), MENU_SMIME, OP_HELP);
435     strcat (helpstr, buf);      /* __STRCAT_CHECKED__ */
436
437     /* Create the menu */
438     menu = mutt_new_menu ();
439     menu->max = cur;
440     menu->make_entry = smime_entry;
441     menu->menu = MENU_SMIME;
442     menu->help = helpstr;
443     menu->data = Table;
444     menu->title = title;
445     /* sorting keys might be done later - TODO */
446
447     mutt_clear_error ();
448
449     done = 0;
450     hash = 0;
451     while (!done) {
452       switch (mutt_menuLoop (menu)) {
453       case OP_GENERIC_SELECT_ENTRY:
454         cur = menu->current;
455         hash = 1;
456         done = 1;
457         break;
458       case OP_EXIT:
459         hash = 0;
460         done = 1;
461         break;
462       }
463     }
464     if (hash) {
465       fname = p_new(char, 13); /* Hash + '.' + Suffix + \0 */
466       sprintf (fname, "%.8x.%i", Table[cur].hash, Table[cur].suffix);
467     }
468     else
469       fname = NULL;
470
471     mutt_menuDestroy (&menu);
472     p_delete(&Table);
473     set_option (OPTNEEDREDRAW);
474
475     if (fname)
476       return fname;
477   }
478 }
479
480
481
482 char *smime_get_field_from_db (char *mailbox, char *query, short public,
483                                short may_ask)
484 {
485   int addr_len, query_len, found = 0, ask = 0, choice = 0;
486   char cert_path[_POSIX_PATH_MAX];
487   char buf[LONG_STRING], prompt[STRING];
488   char fields[5][STRING];
489   char key[STRING];
490   int numFields;
491   struct stat info;
492   char key_trust_level = 0;
493   FILE *fp;
494
495   if (!mailbox && !query)
496     return (NULL);
497
498   addr_len = mailbox ? m_strlen(mailbox) : 0;
499   query_len = query ? m_strlen(query) : 0;
500
501   *key = '\0';
502
503   /* index-file format:
504      mailbox certfile label issuer_certfile trust_flags\n
505
506      certfile is a hash value generated by openssl.
507      Note that this was done according to the OpenSSL
508      specs on their CA-directory.
509
510    */
511   snprintf (cert_path, sizeof (cert_path), "%s/.index",
512             (public ? NONULL (SmimeCertificates) : NONULL (SmimeKeys)));
513
514   if (!stat (cert_path, &info)) {
515     if ((fp = safe_fopen (cert_path, "r")) == NULL) {
516       mutt_perror (cert_path);
517       return (NULL);
518     }
519
520     while (fgets (buf, sizeof (buf) - 1, fp) != NULL)
521       if (mailbox && !(m_strncasecmp(mailbox, buf, addr_len))) {
522         numFields = sscanf (buf,
523                             MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
524                             MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
525                             MUTT_FORMAT (STRING) "\n",
526                             fields[0], fields[1],
527                             fields[2], fields[3], fields[4]);
528         if (numFields < 2)
529           continue;
530         if (mailbox && public &&
531             (!fields[4] ||
532              *fields[4] == 'i' || *fields[4] == 'e' || *fields[4] == 'r'))
533           continue;
534
535         if (found) {
536           if (public && *fields[4] == 'u')
537             snprintf (prompt, sizeof (prompt),
538                       _
539                       ("ID %s is unverified. Do you want to use it for %s ?"),
540                       fields[1], mailbox);
541           else if (public && *fields[4] == 'v')
542             snprintf (prompt, sizeof (prompt),
543                       _("Use (untrusted!) ID %s for %s ?"),
544                       fields[1], mailbox);
545           else
546             snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"),
547                       fields[1], mailbox);
548           if (may_ask == 0)
549             choice = M_YES;
550           if (may_ask && (choice = mutt_yesorno (prompt, M_NO)) == -1) {
551             found = 0;
552             ask = 0;
553             *key = '\0';
554             break;
555           }
556           else if (choice == M_NO) {
557             ask = 1;
558             continue;
559           }
560           else if (choice == M_YES) {
561             m_strcpy(key, sizeof(key), fields[1]);
562             ask = 0;
563             break;
564           }
565         }
566         else {
567           if (public)
568             key_trust_level = *fields[4];
569           m_strcpy(key, sizeof(key), fields[1]);
570         }
571         found = 1;
572       }
573       else if (query) {
574         numFields = sscanf (buf,
575                             MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
576                             MUTT_FORMAT (STRING) " " MUTT_FORMAT (STRING) " "
577                             MUTT_FORMAT (STRING) "\n",
578                             fields[0], fields[1],
579                             fields[2], fields[3], fields[4]);
580
581         /* query = label: return certificate. */
582         if (numFields >= 3 &&
583             !(m_strncasecmp(query, fields[2], query_len))) {
584           ask = 0;
585           m_strcpy(key, sizeof(key), fields[1]);
586         }
587         /* query = certificate: return intermediate certificate. */
588         else if (numFields >= 4 &&
589                  !(m_strncasecmp(query, fields[1], query_len))) {
590           ask = 0;
591           m_strcpy(key, sizeof(key), fields[3]);
592         }
593       }
594
595     safe_fclose (&fp);
596
597     if (ask) {
598       if (public && *fields[4] == 'u')
599         snprintf (prompt, sizeof (prompt),
600                   _("ID %s is unverified. Do you want to use it for %s ?"),
601                   fields[1], mailbox);
602       else if (public && *fields[4] == 'v')
603         snprintf (prompt, sizeof (prompt),
604                   _("Use (untrusted!) ID %s for %s ?"), fields[1], mailbox);
605       else
606         snprintf (prompt, sizeof (prompt), _("Use ID %s for %s ?"), key,
607                   mailbox);
608       choice = mutt_yesorno (prompt, M_NO);
609       if (choice == -1 || choice == M_NO)
610         *key = '\0';
611     }
612     else if (key_trust_level && may_ask) {
613       if (key_trust_level == 'u') {
614         snprintf (prompt, sizeof (prompt),
615                   _("ID %s is unverified. Do you want to use it for %s ?"),
616                   key, mailbox);
617         choice = mutt_yesorno (prompt, M_NO);
618         if (choice != M_YES)
619           *key = '\0';
620       }
621       else if (key_trust_level == 'v') {
622         mutt_error (_
623                     ("Warning: You have not yet decided to trust ID %s. (any key to continue)"),
624                     key);
625         mutt_sleep (5);
626       }
627     }
628
629   }
630
631   /* Note: m_strdup("") returns NULL. */
632   return m_strdup(key);
633 }
634
635
636
637
638 /* 
639    This sets the '*ToUse' variables for an upcoming decryption, where
640    the reuquired key is different from SmimeDefaultKey.
641 */
642
643 void _smime_getkeys (char *mailbox)
644 {
645   char *k = NULL;
646   char buf[STRING];
647
648   k = smime_get_field_from_db (mailbox, NULL, 0, 1);
649
650   if (!k) {
651     snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), mailbox);
652     k = smime_ask_for_key (buf, mailbox, 0);
653   }
654
655   if (k) {
656     /* the key used last time. */
657     if (*SmimeKeyToUse &&
658         !m_strcasecmp(k, SmimeKeyToUse + m_strlen(SmimeKeys) + 1)) {
659       p_delete(&k);
660       return;
661     }
662     else
663       smime_void_passphrase ();
664
665     snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
666               NONULL (SmimeKeys), k);
667
668     snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
669               NONULL (SmimeCertificates), k);
670
671     if (m_strcasecmp(k, SmimeDefaultKey))
672       smime_void_passphrase ();
673
674     p_delete(&k);
675     return;
676   }
677
678   if (*SmimeKeyToUse) {
679     if (!m_strcasecmp(SmimeDefaultKey,
680                           SmimeKeyToUse + m_strlen(SmimeKeys) + 1))
681       return;
682
683     smime_void_passphrase ();
684   }
685
686   snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
687             NONULL (SmimeKeys), NONULL (SmimeDefaultKey));
688
689   snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
690             NONULL (SmimeCertificates), NONULL (SmimeDefaultKey));
691 }
692
693 void smime_getkeys (ENVELOPE * env)
694 {
695   address_t *t;
696   int found = 0;
697
698   if (option (OPTSDEFAULTDECRYPTKEY) && SmimeDefaultKey && *SmimeDefaultKey) {
699     snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
700               NONULL (SmimeKeys), SmimeDefaultKey);
701
702     snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
703               NONULL (SmimeCertificates), SmimeDefaultKey);
704
705     return;
706   }
707
708   for (t = env->to; !found && t; t = t->next)
709     if (mutt_addr_is_user (t)) {
710       found = 1;
711       _smime_getkeys (t->mailbox);
712     }
713   for (t = env->cc; !found && t; t = t->next)
714     if (mutt_addr_is_user (t)) {
715       found = 1;
716       _smime_getkeys (t->mailbox);
717     }
718   if (!found && (t = mutt_default_from ())) {
719     _smime_getkeys (t->mailbox);
720     address_list_wipe(&t);
721   }
722 }
723
724 /* This routine attempts to find the keyids of the recipients of a message.
725  * It returns NULL if any of the keys can not be found.
726  */
727
728 char *smime_findKeys (address_t * to, address_t * cc, address_t * bcc)
729 {
730   char *keyID, *keylist = NULL;
731   ssize_t keylist_size = 0;
732   ssize_t keylist_used = 0;
733   address_t *tmp = NULL, *addr = NULL;
734   address_t **last = &tmp;
735   address_t *p, *q;
736   int i;
737
738   const char *fqdn = mutt_fqdn (1);
739
740   for (i = 0; i < 3; i++) {
741     switch (i) {
742     case 0:
743       p = to;
744       break;
745     case 1:
746       p = cc;
747       break;
748     case 2:
749       p = bcc;
750       break;
751     default:
752       abort ();
753     }
754
755     *last = address_list_dup (p);
756     while (*last)
757       last = &((*last)->next);
758   }
759
760   if (fqdn)
761     rfc822_qualify (tmp, fqdn);
762
763   tmp = mutt_remove_duplicates (tmp);
764
765   for (p = tmp; p; p = p->next) {
766     char buf[LONG_STRING];
767
768     q = p;
769
770     if ((keyID = smime_get_field_from_db (q->mailbox, NULL, 1, 1)) == NULL) {
771       snprintf (buf, sizeof (buf), _("Enter keyID for %s: "), q->mailbox);
772       keyID = smime_ask_for_key (buf, q->mailbox, 1);
773     }
774     if (!keyID) {
775       mutt_message (_("No (valid) certificate found for %s."), q->mailbox);
776       p_delete(&keylist);
777       address_list_wipe(&tmp);
778       address_list_wipe(&addr);
779       return NULL;
780     }
781
782     keylist_size += m_strlen(keyID) + 2;
783     p_realloc(&keylist, keylist_size);
784     sprintf (keylist + keylist_used, "%s\n", keyID);    /* __SPRINTF_CHECKED__ */
785     keylist_used = m_strlen(keylist);
786
787     address_list_wipe(&addr);
788
789   }
790   address_list_wipe(&tmp);
791   return (keylist);
792 }
793
794
795
796
797
798
799 static int smime_handle_cert_email (char *certificate, char *mailbox,
800                                     int copy, char ***buffer, int *num)
801 {
802   FILE *fpout = NULL, *fperr = NULL;
803   char tmpfname[_POSIX_PATH_MAX];
804   char email[STRING];
805   int ret = -1, count = 0;
806   pid_t thepid;
807
808   mutt_mktemp (tmpfname);
809   if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
810     mutt_perror (tmpfname);
811     return 1;
812   }
813   mutt_unlink (tmpfname);
814
815   mutt_mktemp (tmpfname);
816   if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
817     fclose (fperr);
818     mutt_perror (tmpfname);
819     return 1;
820   }
821   mutt_unlink (tmpfname);
822
823   if ((thepid = smime_invoke (NULL, NULL, NULL,
824                               -1, fileno (fpout), fileno (fperr),
825                               certificate, NULL, NULL, NULL, NULL, NULL,
826                               SmimeGetCertEmailCommand)) == -1) {
827     mutt_message (_("Error: unable to create OpenSSL subprocess!"));
828     fclose (fperr);
829     fclose (fpout);
830     return 1;
831   }
832
833   mutt_wait_filter (thepid);
834
835   fflush (fpout);
836   rewind (fpout);
837   rewind (fperr);
838   fflush (fperr);
839
840
841   while ((fgets (email, sizeof (email), fpout))) {
842     *(email + m_strlen(email) - 1) = '\0';
843     if (m_strncasecmp(email, mailbox, m_strlen(mailbox)) == 0)
844       ret = 1;
845
846     ret = ret < 0 ? 0 : ret;
847     count++;
848   }
849
850   if (ret == -1) {
851     mutt_endwin (NULL);
852     mutt_copy_stream (fperr, stdout);
853     mutt_any_key_to_continue (_
854                               ("Error: unable to create OpenSSL subprocess!"));
855     ret = 1;
856   }
857   else if (!ret)
858     ret = 1;
859   else
860     ret = 0;
861
862   if (copy && buffer && num) {
863     (*num) = count;
864     *buffer = p_new(char *, count);
865     count = 0;
866
867     rewind (fpout);
868     while ((fgets (email, sizeof (email), fpout))) {
869       *(email + m_strlen(email) - 1) = '\0';
870       (*buffer)[count] = p_dupstr(email, m_strlen(email));
871       count++;
872     }
873   }
874   else if (copy)
875     ret = 2;
876
877   fclose (fpout);
878   fclose (fperr);
879
880   return ret;
881 }
882
883
884
885 static char *smime_extract_certificate (char *infile)
886 {
887   FILE *fpout = NULL, *fperr = NULL;
888   char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
889   char tmpfname[_POSIX_PATH_MAX];
890   pid_t thepid;
891   int empty;
892
893
894   mutt_mktemp (tmpfname);
895   if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
896     mutt_perror (tmpfname);
897     return NULL;
898   }
899   mutt_unlink (tmpfname);
900
901   mutt_mktemp (pk7out);
902   if ((fpout = safe_fopen (pk7out, "w+")) == NULL) {
903     fclose (fperr);
904     mutt_perror (pk7out);
905     return NULL;
906   }
907
908   /* Step 1: Convert the signature to a PKCS#7 structure, as we can't
909      extract the full set of certificates directly.
910    */
911   if ((thepid = smime_invoke (NULL, NULL, NULL,
912                               -1, fileno (fpout), fileno (fperr),
913                               infile, NULL, NULL, NULL, NULL, NULL,
914                               SmimePk7outCommand)) == -1) {
915     mutt_any_key_to_continue (_
916                               ("Error: unable to create OpenSSL subprocess!"));
917     fclose (fperr);
918     fclose (fpout);
919     mutt_unlink (pk7out);
920     return NULL;
921   }
922
923   mutt_wait_filter (thepid);
924
925
926   fflush (fpout);
927   rewind (fpout);
928   rewind (fperr);
929   fflush (fperr);
930   empty = (fgetc (fpout) == EOF);
931   if (empty) {
932     mutt_perror (pk7out);
933     mutt_copy_stream (fperr, stdout);
934     fclose (fpout);
935     fclose (fperr);
936     mutt_unlink (pk7out);
937     return NULL;
938
939   }
940
941
942   fclose (fpout);
943   mutt_mktemp (certfile);
944   if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
945     fclose (fperr);
946     mutt_unlink (pk7out);
947     mutt_perror (certfile);
948     return NULL;
949   }
950
951   /* Step 2: Extract the certificates from a PKCS#7 structure.
952    */
953   if ((thepid = smime_invoke (NULL, NULL, NULL,
954                               -1, fileno (fpout), fileno (fperr),
955                               pk7out, NULL, NULL, NULL, NULL, NULL,
956                               SmimeGetCertCommand)) == -1) {
957     mutt_any_key_to_continue (_
958                               ("Error: unable to create OpenSSL subprocess!"));
959     fclose (fperr);
960     fclose (fpout);
961     mutt_unlink (pk7out);
962     mutt_unlink (certfile);
963     return NULL;
964   }
965
966   mutt_wait_filter (thepid);
967
968   mutt_unlink (pk7out);
969
970   fflush (fpout);
971   rewind (fpout);
972   rewind (fperr);
973   fflush (fperr);
974   empty = (fgetc (fpout) == EOF);
975   if (empty) {
976     mutt_copy_stream (fperr, stdout);
977     fclose (fpout);
978     fclose (fperr);
979     mutt_unlink (certfile);
980     return NULL;
981   }
982
983   fclose (fpout);
984   fclose (fperr);
985
986   return m_strdup(certfile);
987 }
988
989 static char *smime_extract_signer_certificate (char *infile)
990 {
991   FILE *fpout = NULL, *fperr = NULL;
992   char pk7out[_POSIX_PATH_MAX], certfile[_POSIX_PATH_MAX];
993   char tmpfname[_POSIX_PATH_MAX];
994   pid_t thepid;
995   int empty;
996
997
998   mutt_mktemp (tmpfname);
999   if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1000     mutt_perror (tmpfname);
1001     return NULL;
1002   }
1003   mutt_unlink (tmpfname);
1004
1005
1006   mutt_mktemp (certfile);
1007   if ((fpout = safe_fopen (certfile, "w+")) == NULL) {
1008     fclose (fperr);
1009     mutt_perror (certfile);
1010     return NULL;
1011   }
1012
1013   /* Extract signer's certificate
1014    */
1015   if ((thepid = smime_invoke (NULL, NULL, NULL,
1016                               -1, -1, fileno (fperr),
1017                               infile, NULL, NULL, NULL, certfile, NULL,
1018                               SmimeGetSignerCertCommand)) == -1) {
1019     mutt_any_key_to_continue (_
1020                               ("Error: unable to create OpenSSL subprocess!"));
1021     fclose (fperr);
1022     fclose (fpout);
1023     mutt_unlink (pk7out);
1024     mutt_unlink (certfile);
1025     return NULL;
1026   }
1027
1028   mutt_wait_filter (thepid);
1029
1030   fflush (fpout);
1031   rewind (fpout);
1032   rewind (fperr);
1033   fflush (fperr);
1034   empty = (fgetc (fpout) == EOF);
1035   if (empty) {
1036     mutt_endwin (NULL);
1037     mutt_copy_stream (fperr, stdout);
1038     mutt_any_key_to_continue (NULL);
1039     fclose (fpout);
1040     fclose (fperr);
1041     mutt_unlink (certfile);
1042     return NULL;
1043   }
1044
1045   fclose (fpout);
1046   fclose (fperr);
1047
1048   return m_strdup(certfile);
1049 }
1050
1051
1052
1053
1054 /* Add a certificate and update index file (externally). */
1055
1056 void smime_invoke_import (char *infile, char *mailbox __attribute__((notused)))
1057 {
1058   char tmpfname[_POSIX_PATH_MAX], *certfile = NULL, buf[STRING];
1059   FILE *smimein = NULL, *fpout = NULL, *fperr = NULL;
1060   pid_t thepid = -1;
1061
1062   mutt_mktemp (tmpfname);
1063   if ((fperr = safe_fopen (tmpfname, "w+")) == NULL) {
1064     mutt_perror (tmpfname);
1065     return;
1066   }
1067   mutt_unlink (tmpfname);
1068
1069   mutt_mktemp (tmpfname);
1070   if ((fpout = safe_fopen (tmpfname, "w+")) == NULL) {
1071     fclose (fperr);
1072     mutt_perror (tmpfname);
1073     return;
1074   }
1075   mutt_unlink (tmpfname);
1076
1077
1078   buf[0] = '\0';
1079   if (option (OPTASKCERTLABEL))
1080     mutt_get_field ("Label for certificate:", buf, sizeof (buf), 0);
1081
1082   mutt_endwin (NULL);
1083   if ((certfile = smime_extract_certificate (infile))) {
1084     mutt_endwin (NULL);
1085
1086     if ((thepid = smime_invoke (&smimein, NULL, NULL,
1087                                 -1, fileno (fpout), fileno (fperr),
1088                                 certfile, NULL, NULL, NULL, NULL, NULL,
1089                                 SmimeImportCertCommand)) == -1) {
1090       mutt_message (_("Error: unable to create OpenSSL subprocess!"));
1091       return;
1092     }
1093     fputs (buf, smimein);
1094     fputc ('\n', smimein);
1095     fclose (smimein);
1096
1097     mutt_wait_filter (thepid);
1098
1099     mutt_unlink (certfile);
1100     p_delete(&certfile);
1101   }
1102
1103   fflush (fpout);
1104   rewind (fpout);
1105   fflush (fperr);
1106   rewind (fperr);
1107
1108   mutt_copy_stream (fpout, stdout);
1109   mutt_copy_stream (fperr, stdout);
1110
1111   fclose (fpout);
1112   fclose (fperr);
1113
1114 }
1115
1116
1117
1118 int smime_verify_sender (HEADER * h)
1119 {
1120   char *mbox = NULL, *certfile, tempfname[_POSIX_PATH_MAX];
1121   FILE *fpout;
1122   int retval = 1;
1123
1124   mutt_mktemp (tempfname);
1125   if (!(fpout = safe_fopen (tempfname, "w"))) {
1126     mutt_perror (tempfname);
1127     return 1;
1128   }
1129
1130   if (h->security & ENCRYPT)
1131     mutt_copy_message (fpout, Context, h,
1132                        M_CM_DECODE_CRYPT & M_CM_DECODE_SMIME,
1133                        CH_MIME | CH_WEED | CH_NONEWLINE);
1134   else
1135     mutt_copy_message (fpout, Context, h, 0, 0);
1136
1137   fflush (fpout);
1138   fclose (fpout);
1139
1140   if (h->env->from) {
1141     h->env->from = mutt_expand_aliases (h->env->from);
1142     mbox = h->env->from->mailbox;
1143   }
1144   else if (h->env->sender) {
1145     h->env->sender = mutt_expand_aliases (h->env->sender);
1146     mbox = h->env->sender->mailbox;
1147   }
1148
1149   if (mbox) {
1150     if ((certfile = smime_extract_signer_certificate (tempfname))) {
1151       mutt_unlink (tempfname);
1152       if (smime_handle_cert_email (certfile, mbox, 0, NULL, NULL)) {
1153         if (isendwin ())
1154           mutt_any_key_to_continue (NULL);
1155       }
1156       else
1157         retval = 0;
1158       mutt_unlink (certfile);
1159       p_delete(&certfile);
1160     }
1161     else
1162       mutt_any_key_to_continue (_("no certfile"));
1163   }
1164   else
1165     mutt_any_key_to_continue (_("no mbox"));
1166
1167   mutt_unlink (tempfname);
1168   return retval;
1169 }
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179 /*
1180  *    Creating S/MIME - bodies.
1181  */
1182
1183
1184
1185
1186 static
1187 pid_t smime_invoke_encrypt (FILE ** smimein, FILE ** smimeout,
1188                             FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1189                             int smimeerrfd, const char *fname,
1190                             const char *uids)
1191 {
1192   return smime_invoke (smimein, smimeout, smimeerr,
1193                        smimeinfd, smimeoutfd, smimeerrfd,
1194                        fname, NULL, SmimeCryptAlg, NULL, uids, NULL,
1195                        SmimeEncryptCommand);
1196 }
1197
1198
1199 static
1200 pid_t smime_invoke_sign (FILE ** smimein, FILE ** smimeout, FILE ** smimeerr,
1201                          int smimeinfd, int smimeoutfd, int smimeerrfd,
1202                          const char *fname)
1203 {
1204   return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1205                        smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1206                        SmimeCertToUse, SmimeIntermediateToUse,
1207                        SmimeSignCommand);
1208 }
1209
1210
1211
1212
1213 BODY *smime_build_smime_entity (BODY * a, char *certlist)
1214 {
1215   char buf[LONG_STRING], certfile[LONG_STRING];
1216   char tempfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1217   char smimeinfile[_POSIX_PATH_MAX];
1218   char *cert_start = certlist, *cert_end = certlist;
1219   FILE *smimein = NULL, *smimeerr = NULL, *fpout = NULL, *fptmp = NULL;
1220   BODY *t;
1221   int err = 0, empty;
1222   pid_t thepid;
1223
1224   mutt_mktemp (tempfile);
1225   if ((fpout = safe_fopen (tempfile, "w+")) == NULL) {
1226     mutt_perror (tempfile);
1227     return (NULL);
1228   }
1229
1230   mutt_mktemp (smimeerrfile);
1231   if ((smimeerr = safe_fopen (smimeerrfile, "w+")) == NULL) {
1232     mutt_perror (smimeerrfile);
1233     fclose (fpout);
1234     mutt_unlink (tempfile);
1235     return NULL;
1236   }
1237   mutt_unlink (smimeerrfile);
1238
1239   mutt_mktemp (smimeinfile);
1240   if ((fptmp = safe_fopen (smimeinfile, "w+")) == NULL) {
1241     mutt_perror (smimeinfile);
1242     mutt_unlink (tempfile);
1243     fclose (fpout);
1244     fclose (smimeerr);
1245     return NULL;
1246   }
1247
1248   *certfile = '\0';
1249   while (1) {
1250     int off = m_strlen(certfile);
1251
1252     while (*++cert_end && *cert_end != '\n');
1253     if (!*cert_end)
1254       break;
1255     *cert_end = '\0';
1256     snprintf (certfile + off, sizeof (certfile) - off, " %s/%s",
1257               NONULL (SmimeCertificates), cert_start);
1258     *cert_end = '\n';
1259     cert_start = cert_end;
1260     cert_start++;
1261   }
1262
1263   /* write a MIME entity */
1264   mutt_write_mime_header (a, fptmp);
1265   fputc ('\n', fptmp);
1266   mutt_write_mime_body (a, fptmp);
1267   fclose (fptmp);
1268
1269   if ((thepid =
1270        smime_invoke_encrypt (&smimein, NULL, NULL, -1,
1271                              fileno (fpout), fileno (smimeerr),
1272                              smimeinfile, certfile)) == -1) {
1273     fclose (smimeerr);
1274     mutt_unlink (smimeinfile);
1275     mutt_unlink (certfile);
1276     return (NULL);
1277   }
1278
1279   fclose (smimein);
1280
1281   mutt_wait_filter (thepid);
1282   mutt_unlink (smimeinfile);
1283   mutt_unlink (certfile);
1284
1285   fflush (fpout);
1286   rewind (fpout);
1287   empty = (fgetc (fpout) == EOF);
1288   fclose (fpout);
1289
1290   fflush (smimeerr);
1291   rewind (smimeerr);
1292   while (fgets (buf, sizeof (buf) - 1, smimeerr) != NULL) {
1293     err = 1;
1294     fputs (buf, stdout);
1295   }
1296   fclose (smimeerr);
1297
1298   /* pause if there is any error output from SMIME */
1299   if (err)
1300     mutt_any_key_to_continue (NULL);
1301
1302   if (empty) {
1303     /* fatal error while trying to encrypt message */
1304     if (!err)
1305       mutt_any_key_to_continue _("No output from OpenSSL..");
1306
1307     mutt_unlink (tempfile);
1308     return (NULL);
1309   }
1310
1311   t = mutt_new_body ();
1312   t->type = TYPEAPPLICATION;
1313   t->subtype = m_strdup("x-pkcs7-mime");
1314   mutt_set_parameter ("name", "smime.p7m", &t->parameter);
1315   mutt_set_parameter ("smime-type", "enveloped-data", &t->parameter);
1316   t->encoding = ENCBASE64;      /* The output of OpenSSL SHOULD be binary */
1317   t->use_disp = 1;
1318   t->disposition = DISPATTACH;
1319   t->d_filename = m_strdup("smime.p7m");
1320   t->filename = m_strdup(tempfile);
1321   t->unlink = 1;                /*delete after sending the message */
1322   t->parts = 0;
1323   t->next = 0;
1324
1325   return (t);
1326 }
1327
1328
1329
1330
1331 BODY *smime_sign_message (BODY * a)
1332 {
1333   BODY *t;
1334   char buffer[LONG_STRING];
1335   char signedfile[_POSIX_PATH_MAX], filetosign[_POSIX_PATH_MAX];
1336   FILE *smimein = NULL, *smimeout = NULL, *smimeerr = NULL, *sfp = NULL;
1337   int err = 0;
1338   int empty = 0;
1339   pid_t thepid;
1340   char *intermediates = smime_get_field_from_db (NULL, SmimeDefaultKey, 1, 1);
1341
1342   if (!intermediates) {
1343     mutt_message (_("Warning: Intermediate certificate not found."));
1344     intermediates = SmimeDefaultKey;    /* so openssl won't complain in any case */
1345   }
1346
1347   convert_to_7bit (a);          /* Signed data _must_ be in 7-bit format. */
1348
1349   mutt_mktemp (filetosign);
1350   if ((sfp = safe_fopen (filetosign, "w+")) == NULL) {
1351     mutt_perror (filetosign);
1352     return NULL;
1353   }
1354
1355   mutt_mktemp (signedfile);
1356   if ((smimeout = safe_fopen (signedfile, "w+")) == NULL) {
1357     mutt_perror (signedfile);
1358     fclose (sfp);
1359     mutt_unlink (filetosign);
1360     return NULL;
1361   }
1362
1363   mutt_write_mime_header (a, sfp);
1364   fputc ('\n', sfp);
1365   mutt_write_mime_body (a, sfp);
1366   fclose (sfp);
1367
1368
1369
1370   snprintf (SmimeKeyToUse, sizeof (SmimeKeyToUse), "%s/%s",
1371             NONULL (SmimeKeys), SmimeDefaultKey);
1372
1373   snprintf (SmimeCertToUse, sizeof (SmimeCertToUse), "%s/%s",
1374             NONULL (SmimeCertificates), SmimeDefaultKey);
1375
1376   snprintf (SmimeIntermediateToUse, sizeof (SmimeIntermediateToUse), "%s/%s",
1377             NONULL (SmimeCertificates), intermediates);
1378
1379
1380
1381   if ((thepid = smime_invoke_sign (&smimein, NULL, &smimeerr,
1382                                    -1, fileno (smimeout), -1,
1383                                    filetosign)) == -1) {
1384     mutt_perror (_("Can't open OpenSSL subprocess!"));
1385
1386     fclose (smimeout);
1387     mutt_unlink (signedfile);
1388     mutt_unlink (filetosign);
1389     return NULL;
1390   }
1391   fputs (SmimePass, smimein);
1392   fputc ('\n', smimein);
1393   fclose (smimein);
1394
1395
1396   mutt_wait_filter (thepid);
1397
1398   /* check for errors from OpenSSL */
1399   err = 0;
1400   fflush (smimeerr);
1401   rewind (smimeerr);
1402   while (fgets (buffer, sizeof (buffer) - 1, smimeerr) != NULL) {
1403     err = 1;
1404     fputs (buffer, stdout);
1405   }
1406   fclose (smimeerr);
1407
1408
1409   fflush (smimeout);
1410   rewind (smimeout);
1411   empty = (fgetc (smimeout) == EOF);
1412   fclose (smimeout);
1413
1414   mutt_unlink (filetosign);
1415
1416
1417   if (err)
1418     mutt_any_key_to_continue (NULL);
1419
1420   if (empty) {
1421     mutt_any_key_to_continue _("No output from OpenSSL...");
1422
1423     mutt_unlink (signedfile);
1424     return (NULL);              /* fatal error while signing */
1425   }
1426
1427   t = mutt_new_body ();
1428   t->type = TYPEMULTIPART;
1429   t->subtype = m_strdup("signed");
1430   t->encoding = ENC7BIT;
1431   t->use_disp = 0;
1432   t->disposition = DISPINLINE;
1433
1434   mutt_generate_boundary (&t->parameter);
1435   /* check if this can be extracted from private key somehow.... */
1436   mutt_set_parameter ("micalg", "sha1", &t->parameter);
1437   mutt_set_parameter ("protocol", "application/x-pkcs7-signature",
1438                       &t->parameter);
1439
1440   t->parts = a;
1441   a = t;
1442
1443   t->parts->next = mutt_new_body ();
1444   t = t->parts->next;
1445   t->type = TYPEAPPLICATION;
1446   t->subtype = m_strdup("x-pkcs7-signature");
1447   t->filename = m_strdup(signedfile);
1448   t->d_filename = m_strdup("smime.p7s");
1449   t->use_disp = 1;
1450   t->disposition = DISPATTACH;
1451   t->encoding = ENCBASE64;
1452   t->unlink = 1;                /* ok to remove this file after sending. */
1453
1454   return (a);
1455
1456 }
1457
1458
1459
1460
1461
1462
1463 /*
1464  *    Handling S/MIME - bodies.
1465  */
1466
1467
1468
1469
1470
1471
1472 static
1473 pid_t smime_invoke_verify (FILE ** smimein, FILE ** smimeout,
1474                            FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1475                            int smimeerrfd, const char *fname,
1476                            const char *sig_fname, int opaque)
1477 {
1478   return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1479                        smimeerrfd, fname, sig_fname, NULL, NULL, NULL, NULL,
1480                        (opaque ? SmimeVerifyOpaqueCommand :
1481                         SmimeVerifyCommand));
1482 }
1483
1484
1485 static
1486 pid_t smime_invoke_decrypt (FILE ** smimein, FILE ** smimeout,
1487                             FILE ** smimeerr, int smimeinfd, int smimeoutfd,
1488                             int smimeerrfd, const char *fname)
1489 {
1490   return smime_invoke (smimein, smimeout, smimeerr, smimeinfd, smimeoutfd,
1491                        smimeerrfd, fname, NULL, NULL, SmimeKeyToUse,
1492                        SmimeCertToUse, NULL, SmimeDecryptCommand);
1493 }
1494
1495
1496
1497 int smime_verify_one (BODY * sigbdy, STATE * s, const char *tempfile)
1498 {
1499   char signedfile[_POSIX_PATH_MAX], smimeerrfile[_POSIX_PATH_MAX];
1500   FILE *fp = NULL, *smimeout = NULL, *smimeerr = NULL;
1501   pid_t thepid;
1502   int badsig = -1;
1503
1504   long tmpoffset = 0;
1505   ssize_t tmplength = 0;
1506   int origType = sigbdy->type;
1507   char *savePrefix = NULL;
1508
1509
1510   snprintf (signedfile, sizeof (signedfile), "%s.sig", tempfile);
1511
1512   /* decode to a tempfile, saving the original destination */
1513   fp = s->fpout;
1514   if ((s->fpout = safe_fopen (signedfile, "w")) == NULL) {
1515     mutt_perror (signedfile);
1516     return -1;
1517   }
1518   /* decoding the attachment changes the size and offset, so save a copy
1519    * of the "real" values now, and restore them after processing
1520    */
1521   tmplength = sigbdy->length;
1522   tmpoffset = sigbdy->offset;
1523
1524   /* if we are decoding binary bodies, we don't want to prefix each
1525    * line with the prefix or else the data will get corrupted.
1526    */
1527   savePrefix = s->prefix;
1528   s->prefix = NULL;
1529
1530   mutt_decode_attachment (sigbdy, s);
1531
1532   sigbdy->length = ftello (s->fpout);
1533   sigbdy->offset = 0;
1534   fclose (s->fpout);
1535
1536   /* restore final destination and substitute the tempfile for input */
1537   s->fpout = fp;
1538   fp = s->fpin;
1539   s->fpin = fopen (signedfile, "r");
1540
1541   /* restore the prefix */
1542   s->prefix = savePrefix;
1543
1544   sigbdy->type = origType;
1545
1546
1547   mutt_mktemp (smimeerrfile);
1548   if (!(smimeerr = safe_fopen (smimeerrfile, "w+"))) {
1549     mutt_perror (smimeerrfile);
1550     mutt_unlink (signedfile);
1551     return -1;
1552   }
1553
1554   crypt_current_time (s, "OpenSSL");
1555
1556   if ((thepid = smime_invoke_verify (NULL, &smimeout, NULL,
1557                                      -1, -1, fileno (smimeerr),
1558                                      tempfile, signedfile, 0)) != -1) {
1559     fflush (smimeout);
1560     fclose (smimeout);
1561
1562     if (mutt_wait_filter (thepid))
1563       badsig = -1;
1564     else {
1565       char *line = NULL;
1566       int lineno = 0;
1567       ssize_t linelen;
1568
1569       fflush (smimeerr);
1570       rewind (smimeerr);
1571
1572       line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1573       if (linelen && !m_strcasecmp(line, "verification successful"))
1574         badsig = 0;
1575
1576       p_delete(&line);
1577     }
1578   }
1579
1580   fflush (smimeerr);
1581   rewind (smimeerr);
1582   mutt_copy_stream (smimeerr, s->fpout);
1583   fclose (smimeerr);
1584
1585   state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1586
1587   mutt_unlink (signedfile);
1588   mutt_unlink (smimeerrfile);
1589
1590   sigbdy->length = tmplength;
1591   sigbdy->offset = tmpoffset;
1592
1593   /* restore the original source stream */
1594   fclose (s->fpin);
1595   s->fpin = fp;
1596
1597
1598   return badsig;
1599 }
1600
1601
1602
1603
1604
1605 /*
1606   This handles application/pkcs7-mime which can either be a signed
1607   or an encrypted message.
1608 */
1609
1610 static BODY *smime_handle_entity (BODY * m, STATE * s, FILE * outFile)
1611 {
1612   int len = 0;
1613   int c;
1614   long last_pos;
1615   char buf[HUGE_STRING];
1616   char outfile[_POSIX_PATH_MAX], errfile[_POSIX_PATH_MAX];
1617   char tmpfname[_POSIX_PATH_MAX];
1618   char tmptmpfname[_POSIX_PATH_MAX];
1619   FILE *smimeout = NULL, *smimein = NULL, *smimeerr = NULL;
1620   FILE *tmpfp = NULL, *tmpfp_buffer = NULL, *fpout = NULL;
1621   struct stat info;
1622   BODY *p = NULL;
1623   pid_t thepid = -1;
1624   unsigned int type = mutt_is_application_smime (m);
1625
1626   if (!(type & APPLICATION_SMIME))
1627     return NULL;
1628
1629   mutt_mktemp (outfile);
1630   if ((smimeout = safe_fopen (outfile, "w+")) == NULL) {
1631     mutt_perror (outfile);
1632     return NULL;
1633   }
1634
1635   mutt_mktemp (errfile);
1636   if ((smimeerr = safe_fopen (errfile, "w+")) == NULL) {
1637     mutt_perror (errfile);
1638     fclose (smimeout);
1639     smimeout = NULL;
1640     return NULL;
1641   }
1642   mutt_unlink (errfile);
1643
1644
1645   mutt_mktemp (tmpfname);
1646   if ((tmpfp = safe_fopen (tmpfname, "w+")) == NULL) {
1647     mutt_perror (tmpfname);
1648     fclose (smimeout);
1649     smimeout = NULL;
1650     fclose (smimeerr);
1651     smimeerr = NULL;
1652     return NULL;
1653   }
1654
1655   fseeko (s->fpin, m->offset, 0);
1656   last_pos = m->offset;
1657
1658   mutt_copy_bytes (s->fpin, tmpfp, m->length);
1659
1660   fflush (tmpfp);
1661   fclose (tmpfp);
1662
1663   if ((type & ENCRYPT) &&
1664       (thepid = smime_invoke_decrypt (&smimein, NULL, NULL, -1,
1665                                       fileno (smimeout), fileno (smimeerr),
1666                                       tmpfname)) == -1) {
1667     fclose (smimeout);
1668     smimeout = NULL;
1669     mutt_unlink (tmpfname);
1670     if (s->flags & M_DISPLAY)
1671       state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1672     return NULL;
1673   }
1674   else if ((type & SIGNOPAQUE) &&
1675            (thepid = smime_invoke_verify (&smimein, NULL, NULL, -1,
1676                                           fileno (smimeout),
1677                                           fileno (smimeerr), NULL, tmpfname,
1678                                           SIGNOPAQUE)) == -1) {
1679     fclose (smimeout);
1680     smimeout = NULL;
1681     mutt_unlink (tmpfname);
1682     if (s->flags & M_DISPLAY)
1683       state_attach_puts (_("[-- Error: unable to create OpenSSL subprocess! --]\n"), s);
1684     return NULL;
1685   }
1686
1687
1688   if (type & ENCRYPT) {
1689     if (!smime_valid_passphrase ())
1690       smime_void_passphrase ();
1691     fputs (SmimePass, smimein);
1692     fputc ('\n', smimein);
1693   }
1694
1695   fclose (smimein);
1696
1697   mutt_wait_filter (thepid);
1698   mutt_unlink (tmpfname);
1699
1700
1701   if (s->flags & M_DISPLAY) {
1702     rewind (smimeerr);
1703
1704     if ((c = fgetc (smimeerr)) != EOF) {
1705       ungetc (c, smimeerr);
1706
1707       crypt_current_time (s, "OpenSSL");
1708       mutt_copy_stream (smimeerr, s->fpout);
1709       state_attach_puts (_("[-- End of OpenSSL output --]\n\n"), s);
1710     }
1711
1712     if (type & ENCRYPT)
1713       state_attach_puts (_("[-- The following data is S/MIME"
1714                            " encrypted --]\n"), s);
1715     else
1716       state_attach_puts (_("[-- The following data is S/MIME signed --]\n"),
1717                          s);
1718   }
1719
1720   if (smimeout) {
1721     fflush (smimeout);
1722     rewind (smimeout);
1723
1724     if (outFile)
1725       fpout = outFile;
1726     else {
1727       mutt_mktemp (tmptmpfname);
1728       if ((fpout = safe_fopen (tmptmpfname, "w+")) == NULL) {
1729         mutt_perror (tmptmpfname);
1730         fclose (smimeout);
1731         smimeout = NULL;
1732         return NULL;
1733       }
1734     }
1735     while (fgets (buf, sizeof (buf) - 1, smimeout) != NULL) {
1736       len = m_strlen(buf);
1737       if (len > 1 && buf[len - 2] == '\r') {
1738         buf[len - 2] = '\n';
1739         buf[len - 1] = '\0';
1740       }
1741       fputs (buf, fpout);
1742     }
1743     fflush (fpout);
1744     rewind (fpout);
1745
1746
1747     if ((p = mutt_read_mime_header (fpout, 0)) != NULL) {
1748       fstat (fileno (fpout), &info);
1749       p->length = info.st_size - p->offset;
1750
1751       mutt_parse_part (fpout, p);
1752       if (s->fpout) {
1753         rewind (fpout);
1754         tmpfp_buffer = s->fpin;
1755         s->fpin = fpout;
1756         mutt_body_handler (p, s);
1757         s->fpin = tmpfp_buffer;
1758       }
1759
1760     }
1761     fclose (smimeout);
1762     smimeout = NULL;
1763     mutt_unlink (outfile);
1764
1765     if (!outFile) {
1766       fclose (fpout);
1767       mutt_unlink (tmptmpfname);
1768     }
1769     fpout = NULL;
1770   }
1771
1772   if (s->flags & M_DISPLAY) {
1773     if (type & ENCRYPT)
1774       state_attach_puts (_("\n[-- End of S/MIME encrypted data. --]\n"), s);
1775     else
1776       state_attach_puts (_("\n[-- End of S/MIME signed data. --]\n"), s);
1777   }
1778
1779   if (type & SIGNOPAQUE) {
1780     char *line = NULL;
1781     int lineno = 0;
1782     ssize_t linelen;
1783
1784     rewind (smimeerr);
1785
1786     line = mutt_read_line (line, &linelen, smimeerr, &lineno);
1787     if (linelen && !m_strcasecmp(line, "verification successful"))
1788       m->goodsig = 1;
1789     p_delete(&line);
1790   }
1791   else {
1792     m->goodsig = p->goodsig;
1793     m->badsig = p->badsig;
1794   }
1795   fclose (smimeerr);
1796
1797   return (p);
1798 }
1799
1800
1801
1802
1803
1804 int smime_decrypt_mime (FILE * fpin, FILE ** fpout, BODY * b, BODY ** cur)
1805 {
1806
1807
1808   char tempfile[_POSIX_PATH_MAX];
1809   STATE s;
1810   long tmpoffset = b->offset;
1811   ssize_t tmplength = b->length;
1812   int origType = b->type;
1813   FILE *tmpfp = NULL;
1814   int rv = 0;
1815
1816   if (!mutt_is_application_smime (b))
1817     return -1;
1818
1819   if (b->parts)
1820     return -1;
1821
1822   p_clear(&s, 1);
1823   s.fpin = fpin;
1824   fseeko (s.fpin, b->offset, 0);
1825
1826   mutt_mktemp (tempfile);
1827   if ((tmpfp = safe_fopen (tempfile, "w+")) == NULL) {
1828     mutt_perror (tempfile);
1829     return (-1);
1830   }
1831
1832   mutt_unlink (tempfile);
1833   s.fpout = tmpfp;
1834   mutt_decode_attachment (b, &s);
1835   fflush (tmpfp);
1836   b->length = ftello (s.fpout);
1837   b->offset = 0;
1838   rewind (tmpfp);
1839   s.fpin = tmpfp;
1840   s.fpout = 0;
1841
1842   mutt_mktemp (tempfile);
1843   if ((*fpout = safe_fopen (tempfile, "w+")) == NULL) {
1844     mutt_perror (tempfile);
1845     rv = -1;
1846     goto bail;
1847   }
1848   mutt_unlink (tempfile);
1849
1850   if (!(*cur = smime_handle_entity (b, &s, *fpout))) {
1851     rv = -1;
1852     goto bail;
1853   }
1854
1855   (*cur)->goodsig = b->goodsig;
1856   (*cur)->badsig  = b->badsig;
1857
1858 bail:
1859   b->type = origType;
1860   b->length = tmplength;
1861   b->offset = tmpoffset;
1862
1863   safe_fclose (&tmpfp);
1864   if (*fpout)
1865     rewind (*fpout);
1866   return (rv);
1867 }
1868
1869
1870 int smime_application_smime_handler (BODY * m, STATE * s)
1871 {
1872   return smime_handle_entity (m, s, NULL) ? 0 : -1;
1873 }
1874
1875 int smime_send_menu (HEADER * msg, int *redraw)
1876 {
1877   char *p;
1878
1879   switch (mutt_multi_choice
1880           (_("S/MIME (e)ncrypt, (s)ign, encrypt (w)ith, sign (a)s, (b)oth, or (c)lear? "),
1881            _("eswabfc"))) {
1882   case 1:                      /* (e)ncrypt */
1883     msg->security |= ENCRYPT;
1884     msg->security &= ~SIGN;
1885     break;
1886
1887   case 3:                      /* encrypt (w)ith */
1888     {
1889       int choice = 0;
1890       msg->security |= ENCRYPT;
1891
1892       do {
1893         /* I use "dra" because "123" is recognized anyway */
1894         switch (mutt_multi_choice (_("Choose algorithm family:"
1895                                      " 1: DES, 2: RC2, 3: AES,"
1896                                      " or (c)lear? "), _("drac"))) {
1897           case 1:
1898             switch (choice = mutt_multi_choice (_("1: DES, 2: Triple-DES "),
1899                                                 _("dt"))) {
1900               case 1:
1901                 m_strreplace(&SmimeCryptAlg, "des");
1902                 break;
1903               case 2:
1904                 m_strreplace(&SmimeCryptAlg, "des3");
1905                 break;
1906             }
1907             break;
1908
1909           case 2:
1910             switch (choice = mutt_multi_choice (_("1: RC2-40, 2: RC2-64, 3: RC2-128 "),
1911                                                 _("468"))) {
1912               case 1:
1913                 m_strreplace(&SmimeCryptAlg, "rc2-40");
1914                 break;
1915               case 2:
1916                 m_strreplace(&SmimeCryptAlg, "rc2-64");
1917                 break;
1918               case 3:
1919                 m_strreplace(&SmimeCryptAlg, "rc2-128");
1920                 break;
1921             }
1922             break;
1923
1924           case 3:
1925             switch (choice = mutt_multi_choice (_("1: AES128, 2: AES192, 3: AES256 "),
1926                                                 _("895"))) {
1927               case 1:
1928                 m_strreplace(&SmimeCryptAlg, "aes128");
1929                 break;
1930               case 2:
1931                 m_strreplace(&SmimeCryptAlg, "aes192");
1932                 break;
1933               case 3:
1934                 m_strreplace(&SmimeCryptAlg, "aes256");
1935                 break;
1936             }
1937             break;
1938
1939           case 4: /* (c)lear */
1940             p_delete(&SmimeCryptAlg);
1941             /* fallback */
1942           case -1: /* Ctrl-G or Enter */
1943             choice = 0;
1944             break;
1945         }
1946       } while (choice == -1);
1947     }
1948     break;
1949
1950   case 2:                      /* (s)ign */
1951
1952     if (!SmimeDefaultKey)
1953       mutt_message (_("Can't sign: No key specified. Use Sign As."));
1954
1955     else {
1956       msg->security |= SIGN;
1957       msg->security &= ~ENCRYPT;
1958     }
1959     break;
1960
1961   case 4:                      /* sign (a)s */
1962
1963     if ((p = smime_ask_for_key (_("Sign as: "), NULL, 0))) {
1964       m_strreplace(&SmimeDefaultKey, p);
1965
1966       msg->security |= SIGN;
1967
1968       /* probably need a different passphrase */
1969       crypt_smime_void_passphrase ();
1970     }
1971 #if 0
1972     else
1973       msg->security &= ~SIGN;
1974 #endif
1975
1976     *redraw = REDRAW_FULL;
1977     break;
1978
1979   case 5:                      /* (b)oth */
1980     msg->security |= (ENCRYPT | SIGN);
1981     break;
1982
1983   case 6:                      /* (f)orget it */
1984   case 7:                      /* (c)lear */
1985     msg->security = 0;
1986     break;
1987   }
1988
1989   if (msg->security && msg->security != APPLICATION_SMIME)
1990     msg->security |= APPLICATION_SMIME;
1991   else
1992     msg->security = 0;
1993
1994   return (msg->security);
1995 }