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