3ee7853c3ca47aefa786de2e720add68c7a55be3
[apps/madmutt.git] / lib-crypt / crypt.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996,1997 Michael R. Elkins <me@mutt.org>
4  * Copyright (C) 1999-2000 Thomas Roessler <roessler@does-not-exist.org>
5  * Copyright (C) 2001  Thomas Roessler <roessler@does-not-exist.org>
6  *                     Oliver Ehli <elmy@acm.org>
7  * Copyright (C) 2003  Werner Koch <wk@gnupg.org>
8  * Copyright (C) 2004 g10code GmbH
9  *
10  * This file is part of mutt-ng, see http://www.muttng.org/.
11  * It's licensed under the GNU General Public License,
12  * please see the file GPL in the top level source directory.
13  */
14
15 #include <lib-lib/lib-lib.h>
16
17 #ifdef HAVE_LOCALE_H
18 #  include <locale.h>
19 #endif
20 #ifdef HAVE_SYS_RESOURCE_H
21 #  include <sys/resource.h>
22 #endif
23
24 #include <lib-mime/mime.h>
25
26 #include <lib-ui/curses.h>
27 #include <lib-mx/mx.h>
28
29 #include "alias.h"
30 #include "handler.h"
31 #include "copy.h"
32 #include "crypt.h"
33 #include "pgp.h"
34
35 static int crypt_write_signed (BODY *, STATE *, FILE *);
36
37 /* print the current time to avoid spoofing of the signature output */
38 void crypt_current_time (STATE * s, const char *app_name)
39 {
40   time_t t;
41   char p[STRING], tmp[STRING];
42
43   if (option (OPTCRYPTTIMESTAMP)) {
44     t = time (NULL);
45     setlocale (LC_TIME, "");
46     strftime (p, sizeof (p), _(" (current time: %c)"), localtime (&t));
47     setlocale (LC_TIME, "C");
48   }
49   else
50     *p = '\0';
51
52   snprintf (tmp, sizeof (tmp), _("[-- %s output follows%s --]\n"),
53             NONULL (app_name), p);
54   state_attach_puts (tmp, s);
55 }
56
57
58
59 void crypt_forget_passphrase (void)
60 {
61     crypt_pgp_void_passphrase ();
62     crypt_smime_void_passphrase ();
63     mutt_message _("Passphrase(s) forgotten.");
64 }
65
66
67 #if defined(HAVE_SETRLIMIT)
68
69 static void disable_coredumps (void)
70 {
71   struct rlimit rl = { 0, 0 };
72   static short done = 0;
73
74   if (!done) {
75     setrlimit (RLIMIT_CORE, &rl);
76     done = 1;
77   }
78 }
79
80 #endif /* HAVE_SETRLIMIT */
81
82
83 int crypt_valid_passphrase (int flags)
84 {
85   int ret = 0;
86
87 # if defined(HAVE_SETRLIMIT)
88   disable_coredumps ();
89 # endif
90
91   if (flags & APPLICATION_PGP)
92     ret = crypt_pgp_valid_passphrase ();
93
94   if (flags & APPLICATION_SMIME)
95     ret = crypt_smime_valid_passphrase ();
96
97   return ret;
98 }
99
100
101
102 int mutt_protect (HEADER * msg, char *keylist)
103 {
104   BODY *pbody = NULL, *tmp_pbody = NULL;
105   BODY *tmp_smime_pbody = NULL;
106   BODY *tmp_pgp_pbody = NULL;
107   int flags = msg->security;
108   int i;
109
110   if ((msg->security & SIGN) && !crypt_valid_passphrase (msg->security))
111     return (-1);
112
113   if ((msg->security & PGPINLINE) == PGPINLINE) {
114     /* they really want to send it inline... go for it */
115     if (!isendwin ())
116       mutt_endwin _("Invoking PGP...");
117
118     pbody = crypt_pgp_traditional_encryptsign (msg->content, flags, keylist);
119     if (pbody) {
120       msg->content = pbody;
121       return 0;
122     }
123
124     /* otherwise inline won't work...ask for revert */
125     if ((i =
126          query_quadoption (OPT_PGPMIMEAUTO,
127                            _
128                            ("Message can't be sent inline.  Revert to using PGP/MIME?")))
129         != M_YES) {
130       mutt_error _("Mail not sent.");
131
132       return -1;
133     }
134
135     /* go ahead with PGP/MIME */
136   }
137
138   if (!isendwin ())
139     mutt_endwin (NULL);
140
141   tmp_smime_pbody = msg->content;
142   tmp_pgp_pbody = msg->content;
143
144   if (msg->security & SIGN) {
145     if (msg->security & APPLICATION_SMIME) {
146       if (!(tmp_pbody = crypt_smime_sign_message (msg->content)))
147         return -1;
148       pbody = tmp_smime_pbody = tmp_pbody;
149     }
150
151     if ((msg->security & APPLICATION_PGP)
152         && (!(flags & ENCRYPT) || option (OPTPGPRETAINABLESIG))) {
153       if (!(tmp_pbody = crypt_pgp_sign_message (msg->content)))
154         return -1;
155
156       flags &= ~SIGN;
157       pbody = tmp_pgp_pbody = tmp_pbody;
158     }
159
160     if ((msg->security & APPLICATION_SMIME)
161         && (msg->security & APPLICATION_PGP)) {
162       /* here comes the draft ;-) */
163     }
164   }
165
166
167   if (msg->security & ENCRYPT) {
168     if ((msg->security & APPLICATION_SMIME)) {
169       if (!(tmp_pbody = crypt_smime_build_smime_entity (tmp_smime_pbody,
170                                                         keylist))) {
171         /* signed ? free it! */
172         return (-1);
173       }
174       /* free tmp_body if messages was signed AND encrypted ... */
175       if (tmp_smime_pbody != msg->content && tmp_smime_pbody != tmp_pbody) {
176         /* detatch and dont't delete msg->content,
177            which tmp_smime_pbody->parts after signing. */
178         tmp_smime_pbody->parts = tmp_smime_pbody->parts->next;
179         msg->content->next = NULL;
180         body_list_wipe(&tmp_smime_pbody);
181       }
182       pbody = tmp_pbody;
183     }
184
185     if ((msg->security & APPLICATION_PGP)) {
186       if (!(pbody = crypt_pgp_encrypt_message (tmp_pgp_pbody, keylist,
187                                                flags & SIGN))) {
188
189         /* did we perform a retainable signature? */
190         if (flags != msg->security) {
191           /* remove the outer multipart layer */
192           tmp_pgp_pbody = mutt_remove_multipart (tmp_pgp_pbody);
193           /* get rid of the signature */
194           body_list_wipe(&tmp_pgp_pbody->next);
195         }
196
197         return (-1);
198       }
199
200       /* destroy temporary signature envelope when doing retainable 
201        * signatures.
202
203        */
204       if (flags != msg->security) {
205         tmp_pgp_pbody = mutt_remove_multipart (tmp_pgp_pbody);
206         body_list_wipe(&tmp_pgp_pbody->next);
207       }
208     }
209   }
210
211   if (pbody)
212     msg->content = pbody;
213
214   return 0;
215 }
216
217
218 int crypt_query (BODY * m)
219 {
220   int t = 0;
221
222   if (!m)
223     return 0;
224
225   if (m->type == TYPEAPPLICATION) {
226     t |= mutt_is_application_pgp (m);
227
228     t |= mutt_is_application_smime (m);
229     if (t && m->goodsig)
230       t |= GOODSIGN;
231     if (t && m->badsig)
232       t |= BADSIGN;
233   }
234   else if (m->type == TYPETEXT) {
235     t |= mutt_is_application_pgp (m);
236     if (t && m->goodsig)
237       t |= GOODSIGN;
238   }
239
240   if (m->type == TYPEMULTIPART) {
241     t |= mutt_is_multipart_encrypted (m);
242     t |= mutt_is_multipart_signed (m);
243
244     if (t && m->goodsig)
245       t |= GOODSIGN;
246   }
247
248   if (m->type == TYPEMULTIPART || m->type == TYPEMESSAGE) {
249     BODY *p;
250     int u, v, w;
251
252     u = m->parts ? 0xffffffff : 0;      /* Bits set in all parts */
253     w = 0;                      /* Bits set in any part  */
254
255     for (p = m->parts; p; p = p->next) {
256       v = crypt_query (p);
257       u &= v;
258       w |= v;
259     }
260     t |= u | (w & ~GOODSIGN);
261
262     if ((w & GOODSIGN) && !(u & GOODSIGN))
263       t |= PARTSIGN;
264   }
265
266   return t;
267 }
268
269
270 static int crypt_write_signed (BODY * a, STATE * s, FILE *fp)
271 {
272   int c;
273   short hadcr;
274   size_t bytes;
275
276   fseeko (s->fpin, a->hdr_offset, 0);
277   bytes = a->length + a->offset - a->hdr_offset;
278   hadcr = 0;
279   while (bytes > 0) {
280     if ((c = fgetc (s->fpin)) == EOF)
281       break;
282
283     bytes--;
284
285     if (c == '\r')
286       hadcr = 1;
287     else {
288       if (c == '\n' && !hadcr)
289         fputc ('\r', fp);
290
291       hadcr = 0;
292     }
293
294     fputc (c, fp);
295
296   }
297   fclose (fp);
298
299   return 0;
300 }
301
302
303
304 void convert_to_7bit (BODY * a)
305 {
306   while (a) {
307     if (a->type == TYPEMULTIPART) {
308       if (a->encoding != ENC7BIT) {
309         a->encoding = ENC7BIT;
310         convert_to_7bit (a->parts);
311       }
312       else if (option (OPTPGPSTRICTENC))
313         convert_to_7bit (a->parts);
314     }
315     else if (a->type == TYPEMESSAGE &&
316              m_strcasecmp(a->subtype, "delivery-status")) {
317       if (a->encoding != ENC7BIT)
318         mutt_message_to_7bit (a, NULL);
319     }
320     else if (a->encoding == ENC8BIT)
321       a->encoding = ENCQUOTEDPRINTABLE;
322     else if (a->encoding == ENCBINARY)
323       a->encoding = ENCBASE64;
324     else if (a->content && a->encoding != ENCBASE64 &&
325              (a->content->from || (a->content->space &&
326                                    option (OPTPGPSTRICTENC))))
327       a->encoding = ENCQUOTEDPRINTABLE;
328     a = a->next;
329   }
330 }
331
332
333 void crypt_extract_keys_from_messages (HEADER * h)
334 {
335   int i;
336   char tempfname[_POSIX_PATH_MAX], *mbox;
337   address_t *tmp = NULL;
338   FILE *fpout;
339
340   fpout = m_tempfile(tempfname, sizeof(tempfname), NONULL(Tempdir), NULL);
341   if (!fpout) {
342     mutt_error(_("Could not create temporary file"));
343     return;
344   }
345
346   set_option (OPTDONTHANDLEPGPKEYS);
347
348   if (!h) {
349     for (i = 0; i < Context->vcount; i++) {
350       if (Context->hdrs[Context->v2r[i]]->tagged) {
351         mutt_parse_mime_message (Context, Context->hdrs[Context->v2r[i]]);
352         if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT &&
353             !crypt_valid_passphrase (Context->hdrs[Context->v2r[i]]->
354                                      security)) {
355           fclose (fpout);
356           break;
357         }
358
359         if (Context->hdrs[Context->v2r[i]]->security & APPLICATION_PGP) {
360           mutt_copy_message (fpout, Context, Context->hdrs[Context->v2r[i]],
361                              M_CM_DECODE | M_CM_CHARCONV, 0);
362           fflush (fpout);
363
364           mutt_endwin (_("Trying to extract PGP keys...\n"));
365           crypt_pgp_invoke_import (tempfname);
366         }
367
368         if (Context->hdrs[Context->v2r[i]]->security & APPLICATION_SMIME) {
369           if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT)
370             mutt_copy_message (fpout, Context, Context->hdrs[Context->v2r[i]],
371                                M_CM_NOHEADER | M_CM_DECODE_CRYPT
372                                | M_CM_DECODE_SMIME, 0);
373           else
374             mutt_copy_message (fpout, Context,
375                                Context->hdrs[Context->v2r[i]], 0, 0);
376           fflush (fpout);
377
378           if (Context->hdrs[Context->v2r[i]]->env->from)
379             tmp = mutt_expand_aliases (h->env->from);
380           else if (Context->hdrs[Context->v2r[i]]->env->sender)
381             tmp = mutt_expand_aliases (Context->hdrs[Context->v2r[i]]
382                                        ->env->sender);
383           mbox = tmp ? tmp->mailbox : NULL;
384           if (mbox) {
385             mutt_endwin (_("Trying to extract S/MIME certificates...\n"));
386             crypt_smime_invoke_import (tempfname, mbox);
387             tmp = NULL;
388           }
389         }
390
391         rewind (fpout);
392       }
393     }
394   }
395   else {
396     mutt_parse_mime_message (Context, h);
397     if (!(h->security & ENCRYPT && !crypt_valid_passphrase (h->security))) {
398       if (h->security & APPLICATION_PGP) {
399         mutt_copy_message (fpout, Context, h, M_CM_DECODE | M_CM_CHARCONV, 0);
400         fflush (fpout);
401         mutt_endwin (_("Trying to extract PGP keys...\n"));
402         crypt_pgp_invoke_import (tempfname);
403       }
404
405       if (h->security & APPLICATION_SMIME) {
406         if (h->security & ENCRYPT)
407           mutt_copy_message (fpout, Context, h, M_CM_NOHEADER
408                              | M_CM_DECODE_CRYPT | M_CM_DECODE_SMIME, 0);
409         else
410           mutt_copy_message (fpout, Context, h, 0, 0);
411
412         fflush (fpout);
413         if (h->env->from)
414           tmp = mutt_expand_aliases (h->env->from);
415         else if (h->env->sender)
416           tmp = mutt_expand_aliases (h->env->sender);
417         mbox = tmp ? tmp->mailbox : NULL;
418         if (mbox) {             /* else ? */
419           mutt_message (_("Trying to extract S/MIME certificates...\n"));
420           crypt_smime_invoke_import (tempfname, mbox);
421         }
422       }
423     }
424   }
425
426   fclose (fpout);
427   if (isendwin ())
428     mutt_any_key_to_continue (NULL);
429
430   mutt_unlink (tempfname);
431
432   unset_option (OPTDONTHANDLEPGPKEYS);
433 }
434
435
436
437 int crypt_get_keys (HEADER * msg, char **keylist)
438 {
439   /* Do a quick check to make sure that we can find all of the encryption
440    * keys if the user has requested this service.
441    */
442
443   set_option (OPTPGPCHECKTRUST);
444
445   *keylist = NULL;
446
447   if (msg->security & ENCRYPT) {
448     if (msg->security & APPLICATION_PGP) {
449       if ((*keylist = crypt_pgp_findkeys (msg->env->to, msg->env->cc,
450                                           msg->env->bcc)) == NULL)
451         return (-1);
452       unset_option (OPTPGPCHECKTRUST);
453     }
454     if (msg->security & APPLICATION_SMIME) {
455       if ((*keylist = crypt_smime_findkeys (msg->env->to, msg->env->cc,
456                                             msg->env->bcc)) == NULL)
457         return (-1);
458     }
459   }
460
461   return (0);
462 }
463
464
465
466 static void crypt_fetch_signatures (BODY ***signatures, BODY * a, int *n)
467 {
468   for (; a; a = a->next) {
469     if (a->type == TYPEMULTIPART)
470       crypt_fetch_signatures (signatures, a->parts, n);
471     else {
472       if ((*n % 5) == 0)
473         p_realloc(signatures, *n + 6);
474
475       (*signatures)[(*n)++] = a;
476     }
477   }
478 }
479
480
481 /*
482  * This routine verifies a  "multipart/signed"  body.
483  */
484
485 int mutt_signed_handler (BODY * a, STATE * s)
486 {
487   char tempfile[_POSIX_PATH_MAX];
488   FILE * tempfp;
489   char *protocol;
490   int protocol_major = TYPEOTHER;
491   char *protocol_minor = NULL;
492
493   BODY *b = a;
494   BODY **signatures = NULL;
495   int sigcnt = 0;
496   int i;
497   short goodsig = 1;
498   int rc = 0;
499
500   protocol = parameter_getval(a->parameter, "protocol");
501   a = a->parts;
502
503   /* extract the protocol information */
504
505   if (protocol) {
506     char major[STRING];
507     char *t;
508
509     if ((protocol_minor = strchr (protocol, '/')))
510       protocol_minor++;
511
512     m_strcpy(major, sizeof(major), protocol);
513     if ((t = strchr (major, '/')))
514       *t = '\0';
515
516     protocol_major = mutt_check_mime_type (major);
517   }
518
519   /* consistency check */
520
521   if (!(a && a->next && a->next->type == protocol_major &&
522         !m_strcasecmp(a->next->subtype, protocol_minor))) {
523     state_attach_puts (_("[-- Error: "
524                          "Inconsistent multipart/signed structure! --]\n\n"),
525                        s);
526     return mutt_body_handler (a, s);
527   }
528
529
530   if (protocol_major == TYPEAPPLICATION
531       && !m_strcasecmp(protocol_minor, "pgp-signature"));
532   else if (protocol_major == TYPEAPPLICATION
533            && !(m_strcasecmp(protocol_minor, "x-pkcs7-signature")
534                 && m_strcasecmp(protocol_minor, "pkcs7-signature")));
535   else if (protocol_major == TYPEMULTIPART
536            && !m_strcasecmp(protocol_minor, "mixed"));
537   else {
538     state_printf (s, _("[-- Error: "
539                        "Unknown multipart/signed protocol %s! --]\n\n"),
540                   protocol);
541     return mutt_body_handler (a, s);
542   }
543
544   if (s->flags & M_DISPLAY) {
545
546     crypt_fetch_signatures (&signatures, a->next, &sigcnt);
547
548     if (sigcnt) {
549       tempfp = m_tempfile(tempfile, sizeof(tempfile), NONULL(Tempdir), NULL);
550       if (!tempfp) {
551             mutt_perror (tempfile);
552       }
553       else {
554         if (crypt_write_signed (a, s, tempfp) == 0) {
555           for (i = 0; i < sigcnt; i++) {
556             if (signatures[i]->type == TYPEAPPLICATION
557                 && !m_strcasecmp(signatures[i]->subtype, "pgp-signature")) {
558               if (crypt_pgp_verify_one (signatures[i], s, tempfile) != 0)
559                 goodsig = 0;
560
561               continue;
562             }
563
564             if (signatures[i]->type == TYPEAPPLICATION
565             && (!m_strcasecmp(signatures[i]->subtype, "x-pkcs7-signature")
566                  || !m_strcasecmp(signatures[i]->subtype, "pkcs7-signature")))
567             {
568               if (crypt_smime_verify_one (signatures[i], s, tempfile) != 0)
569                 goodsig = 0;
570
571               continue;
572             }
573
574             state_printf (s, _("[-- Warning: "
575                                "We can't verify %s/%s signatures. --]\n\n"),
576                           TYPE (signatures[i]), signatures[i]->subtype);
577          }
578         }
579       }
580
581       mutt_unlink (tempfile);
582
583       b->goodsig = goodsig;
584       b->badsig = !goodsig;
585
586       /* Now display the signed body */
587       state_attach_puts (_("[-- The following data is signed --]\n\n"), s);
588
589
590       p_delete(&signatures);
591     }
592     else
593       state_attach_puts (_("[-- Warning: Can't find any signatures. --]\n\n"),
594                          s);
595   }
596
597   rc = mutt_body_handler (a, s);
598
599   if (s->flags & M_DISPLAY && sigcnt)
600     state_attach_puts (_("\n[-- End of signed data --]\n"), s);
601
602   return (rc);
603 }