Users don't know what they are doing most of the timeā€¦
[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       } else {
303         convert_to_7bit (a->parts);
304       }
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       a->encoding = ENCQUOTEDPRINTABLE;
318     a = a->next;
319   }
320 }
321
322
323 void crypt_extract_keys_from_messages (HEADER * h)
324 {
325   int i;
326   char tempfname[_POSIX_PATH_MAX], *mbox;
327   address_t *tmp = NULL;
328   FILE *fpout;
329
330   fpout = m_tempfile(tempfname, sizeof(tempfname), NONULL(MCore.tmpdir), NULL);
331   if (!fpout) {
332     mutt_error(_("Could not create temporary file"));
333     return;
334   }
335
336   set_option (OPTDONTHANDLEPGPKEYS);
337
338   if (!h) {
339     for (i = 0; i < Context->vcount; i++) {
340       if (Context->hdrs[Context->v2r[i]]->tagged) {
341         mutt_parse_mime_message (Context, Context->hdrs[Context->v2r[i]]);
342         if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT &&
343             !crypt_valid_passphrase (Context->hdrs[Context->v2r[i]]->
344                                      security)) {
345           m_fclose(&fpout);
346           break;
347         }
348
349         if (Context->hdrs[Context->v2r[i]]->security & APPLICATION_PGP) {
350           mutt_copy_message (fpout, Context, Context->hdrs[Context->v2r[i]],
351                              M_CM_DECODE | M_CM_CHARCONV, 0);
352           fflush (fpout);
353
354           mutt_endwin (_("Trying to extract PGP keys...\n"));
355           crypt_pgp_invoke_import (tempfname);
356         }
357
358         if (Context->hdrs[Context->v2r[i]]->security & APPLICATION_SMIME) {
359           if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT)
360             mutt_copy_message (fpout, Context, Context->hdrs[Context->v2r[i]],
361                                M_CM_NOHEADER | M_CM_DECODE_CRYPT
362                                | M_CM_DECODE_SMIME, 0);
363           else
364             mutt_copy_message (fpout, Context,
365                                Context->hdrs[Context->v2r[i]], 0, 0);
366           fflush (fpout);
367
368           if (Context->hdrs[Context->v2r[i]]->env->from)
369             tmp = mutt_expand_aliases (h->env->from);
370           else if (Context->hdrs[Context->v2r[i]]->env->sender)
371             tmp = mutt_expand_aliases (Context->hdrs[Context->v2r[i]]
372                                        ->env->sender);
373           mbox = tmp ? tmp->mailbox : NULL;
374           if (mbox) {
375             mutt_endwin (_("Trying to extract S/MIME certificates...\n"));
376             crypt_smime_invoke_import (tempfname, mbox);
377             tmp = NULL;
378           }
379         }
380
381         rewind (fpout);
382       }
383     }
384   }
385   else {
386     mutt_parse_mime_message (Context, h);
387     if (!(h->security & ENCRYPT && !crypt_valid_passphrase (h->security))) {
388       if (h->security & APPLICATION_PGP) {
389         mutt_copy_message (fpout, Context, h, M_CM_DECODE | M_CM_CHARCONV, 0);
390         fflush (fpout);
391         mutt_endwin (_("Trying to extract PGP keys...\n"));
392         crypt_pgp_invoke_import (tempfname);
393       }
394
395       if (h->security & APPLICATION_SMIME) {
396         if (h->security & ENCRYPT)
397           mutt_copy_message (fpout, Context, h, M_CM_NOHEADER
398                              | M_CM_DECODE_CRYPT | M_CM_DECODE_SMIME, 0);
399         else
400           mutt_copy_message (fpout, Context, h, 0, 0);
401
402         fflush (fpout);
403         if (h->env->from)
404           tmp = mutt_expand_aliases (h->env->from);
405         else if (h->env->sender)
406           tmp = mutt_expand_aliases (h->env->sender);
407         mbox = tmp ? tmp->mailbox : NULL;
408         if (mbox) {             /* else ? */
409           mutt_message (_("Trying to extract S/MIME certificates...\n"));
410           crypt_smime_invoke_import (tempfname, mbox);
411         }
412       }
413     }
414   }
415
416   m_fclose(&fpout);
417   if (isendwin ())
418     mutt_any_key_to_continue (NULL);
419
420   mutt_unlink (tempfname);
421
422   unset_option (OPTDONTHANDLEPGPKEYS);
423 }
424
425
426
427 int crypt_get_keys (HEADER * msg, char **keylist)
428 {
429   /* Do a quick check to make sure that we can find all of the encryption
430    * keys if the user has requested this service.
431    */
432
433   set_option (OPTPGPCHECKTRUST);
434
435   *keylist = NULL;
436
437   if (msg->security & ENCRYPT) {
438     if (msg->security & APPLICATION_PGP) {
439       if ((*keylist = crypt_pgp_findkeys (msg->env->to, msg->env->cc,
440                                           msg->env->bcc)) == NULL)
441         return (-1);
442       unset_option (OPTPGPCHECKTRUST);
443     }
444     if (msg->security & APPLICATION_SMIME) {
445       if ((*keylist = crypt_smime_findkeys (msg->env->to, msg->env->cc,
446                                             msg->env->bcc)) == NULL)
447         return (-1);
448     }
449   }
450
451   return (0);
452 }
453
454
455
456 static void crypt_fetch_signatures (BODY ***signatures, BODY * a, int *n)
457 {
458   for (; a; a = a->next) {
459     if (a->type == TYPEMULTIPART)
460       crypt_fetch_signatures (signatures, a->parts, n);
461     else {
462       if ((*n % 5) == 0)
463         p_realloc(signatures, *n + 6);
464
465       (*signatures)[(*n)++] = a;
466     }
467   }
468 }
469
470
471 /*
472  * This routine verifies a  "multipart/signed"  body.
473  */
474
475 int mutt_signed_handler (BODY * a, STATE * s)
476 {
477   char tempfile[_POSIX_PATH_MAX];
478   FILE * tempfp;
479   char *protocol;
480   int protocol_major = TYPEOTHER;
481   char *protocol_minor = NULL;
482
483   BODY *b = a;
484   BODY **signatures = NULL;
485   int sigcnt = 0;
486   int i;
487   short goodsig = 1;
488   int rc = 0;
489
490   protocol = parameter_getval(a->parameter, "protocol");
491   a = a->parts;
492
493   /* extract the protocol information */
494
495   if (protocol) {
496     char major[STRING];
497     char *t;
498
499     if ((protocol_minor = strchr (protocol, '/')))
500       protocol_minor++;
501
502     m_strcpy(major, sizeof(major), protocol);
503     if ((t = strchr (major, '/')))
504       *t = '\0';
505
506     protocol_major = mutt_check_mime_type (major);
507   }
508
509   /* consistency check */
510
511   if (!(a && a->next && a->next->type == protocol_major &&
512         !m_strcasecmp(a->next->subtype, protocol_minor))) {
513     state_attach_puts (_("[-- Error: "
514                          "Inconsistent multipart/signed structure! --]\n\n"),
515                        s);
516     return mutt_body_handler (a, s);
517   }
518
519
520   if (protocol_major == TYPEAPPLICATION
521       && !m_strcasecmp(protocol_minor, "pgp-signature"));
522   else if (protocol_major == TYPEAPPLICATION
523            && !(m_strcasecmp(protocol_minor, "x-pkcs7-signature")
524                 && m_strcasecmp(protocol_minor, "pkcs7-signature")));
525   else if (protocol_major == TYPEMULTIPART
526            && !m_strcasecmp(protocol_minor, "mixed"));
527   else {
528     state_printf (s, _("[-- Error: "
529                        "Unknown multipart/signed protocol %s! --]\n\n"),
530                   protocol);
531     return mutt_body_handler (a, s);
532   }
533
534   if (s->flags & M_DISPLAY) {
535
536     crypt_fetch_signatures (&signatures, a->next, &sigcnt);
537
538     if (sigcnt) {
539       tempfp = m_tempfile(tempfile, sizeof(tempfile), NONULL(MCore.tmpdir), NULL);
540       if (!tempfp) {
541           mutt_error(_("Could not create temporary file"));
542       } else {
543         crypt_write_signed(a, s, tempfp);
544         m_fclose(&tempfp);
545         for (i = 0; i < sigcnt; i++) {
546           if (signatures[i]->type == TYPEAPPLICATION
547               && !m_strcasecmp(signatures[i]->subtype, "pgp-signature")) {
548             if (crypt_pgp_verify_one (signatures[i], s, tempfile) != 0)
549               goodsig = 0;
550
551             continue;
552           }
553
554           if (signatures[i]->type == TYPEAPPLICATION
555           && (!m_strcasecmp(signatures[i]->subtype, "x-pkcs7-signature")
556                || !m_strcasecmp(signatures[i]->subtype, "pkcs7-signature")))
557           {
558             if (crypt_smime_verify_one (signatures[i], s, tempfile) != 0)
559               goodsig = 0;
560
561             continue;
562           }
563
564           state_printf (s, _("[-- Warning: "
565                              "We can't verify %s/%s signatures. --]\n\n"),
566                         TYPE (signatures[i]), signatures[i]->subtype);
567         }
568       }
569
570       mutt_unlink (tempfile);
571
572       b->goodsig = goodsig;
573       b->badsig = !goodsig;
574
575       /* Now display the signed body */
576       state_attach_puts (_("[-- The following data is signed --]\n\n"), s);
577
578
579       p_delete(&signatures);
580     }
581     else
582       state_attach_puts (_("[-- Warning: Can't find any signatures. --]\n\n"),
583                          s);
584   }
585
586   rc = mutt_body_handler (a, s);
587
588   if (s->flags & M_DISPLAY && sigcnt)
589     state_attach_puts (_("\n[-- End of signed data --]\n"), s);
590
591   return (rc);
592 }