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