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