19d36c053918a61bdd28a7771236c0f9695f18d7
[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
28 #include "mx.h"
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 =
124          query_quadoption (OPT_PGPMIMEAUTO,
125                            _
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 int crypt_write_signed (BODY * a, STATE * s, const char *tempfile)
269 {
270   FILE *fp;
271   int c;
272   short hadcr;
273   size_t bytes;
274
275   if (!(fp = safe_fopen (tempfile, "w"))) {
276     mutt_perror (tempfile);
277     return -1;
278   }
279
280   fseeko (s->fpin, a->hdr_offset, 0);
281   bytes = a->length + a->offset - a->hdr_offset;
282   hadcr = 0;
283   while (bytes > 0) {
284     if ((c = fgetc (s->fpin)) == EOF)
285       break;
286
287     bytes--;
288
289     if (c == '\r')
290       hadcr = 1;
291     else {
292       if (c == '\n' && !hadcr)
293         fputc ('\r', fp);
294
295       hadcr = 0;
296     }
297
298     fputc (c, fp);
299
300   }
301   fclose (fp);
302
303   return 0;
304 }
305
306
307
308 void convert_to_7bit (BODY * a)
309 {
310   while (a) {
311     if (a->type == TYPEMULTIPART) {
312       if (a->encoding != ENC7BIT) {
313         a->encoding = ENC7BIT;
314         convert_to_7bit (a->parts);
315       }
316       else if (option (OPTPGPSTRICTENC))
317         convert_to_7bit (a->parts);
318     }
319     else if (a->type == TYPEMESSAGE &&
320              m_strcasecmp(a->subtype, "delivery-status")) {
321       if (a->encoding != ENC7BIT)
322         mutt_message_to_7bit (a, NULL);
323     }
324     else if (a->encoding == ENC8BIT)
325       a->encoding = ENCQUOTEDPRINTABLE;
326     else if (a->encoding == ENCBINARY)
327       a->encoding = ENCBASE64;
328     else if (a->content && a->encoding != ENCBASE64 &&
329              (a->content->from || (a->content->space &&
330                                    option (OPTPGPSTRICTENC))))
331       a->encoding = ENCQUOTEDPRINTABLE;
332     a = a->next;
333   }
334 }
335
336
337 void crypt_extract_keys_from_messages (HEADER * h)
338 {
339   int i;
340   char tempfname[_POSIX_PATH_MAX], *mbox;
341   address_t *tmp = NULL;
342   FILE *fpout;
343
344   mutt_mktemp (tempfname);
345   if (!(fpout = safe_fopen (tempfname, "w"))) {
346     mutt_perror (tempfname);
347     return;
348   }
349
350   set_option (OPTDONTHANDLEPGPKEYS);
351
352   if (!h) {
353     for (i = 0; i < Context->vcount; i++) {
354       if (Context->hdrs[Context->v2r[i]]->tagged) {
355         mutt_parse_mime_message (Context, Context->hdrs[Context->v2r[i]]);
356         if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT &&
357             !crypt_valid_passphrase (Context->hdrs[Context->v2r[i]]->
358                                      security)) {
359           fclose (fpout);
360           break;
361         }
362
363         if (Context->hdrs[Context->v2r[i]]->security & APPLICATION_PGP) {
364           mutt_copy_message (fpout, Context, Context->hdrs[Context->v2r[i]],
365                              M_CM_DECODE | M_CM_CHARCONV, 0);
366           fflush (fpout);
367
368           mutt_endwin (_("Trying to extract PGP keys...\n"));
369           crypt_pgp_invoke_import (tempfname);
370         }
371
372         if (Context->hdrs[Context->v2r[i]]->security & APPLICATION_SMIME) {
373           if (Context->hdrs[Context->v2r[i]]->security & ENCRYPT)
374             mutt_copy_message (fpout, Context, Context->hdrs[Context->v2r[i]],
375                                M_CM_NOHEADER | M_CM_DECODE_CRYPT
376                                | M_CM_DECODE_SMIME, 0);
377           else
378             mutt_copy_message (fpout, Context,
379                                Context->hdrs[Context->v2r[i]], 0, 0);
380           fflush (fpout);
381
382           if (Context->hdrs[Context->v2r[i]]->env->from)
383             tmp = mutt_expand_aliases (h->env->from);
384           else if (Context->hdrs[Context->v2r[i]]->env->sender)
385             tmp = mutt_expand_aliases (Context->hdrs[Context->v2r[i]]
386                                        ->env->sender);
387           mbox = tmp ? tmp->mailbox : NULL;
388           if (mbox) {
389             mutt_endwin (_("Trying to extract S/MIME certificates...\n"));
390             crypt_smime_invoke_import (tempfname, mbox);
391             tmp = NULL;
392           }
393         }
394
395         rewind (fpout);
396       }
397     }
398   }
399   else {
400     mutt_parse_mime_message (Context, h);
401     if (!(h->security & ENCRYPT && !crypt_valid_passphrase (h->security))) {
402       if (h->security & APPLICATION_PGP) {
403         mutt_copy_message (fpout, Context, h, M_CM_DECODE | M_CM_CHARCONV, 0);
404         fflush (fpout);
405         mutt_endwin (_("Trying to extract PGP keys...\n"));
406         crypt_pgp_invoke_import (tempfname);
407       }
408
409       if (h->security & APPLICATION_SMIME) {
410         if (h->security & ENCRYPT)
411           mutt_copy_message (fpout, Context, h, M_CM_NOHEADER
412                              | M_CM_DECODE_CRYPT | M_CM_DECODE_SMIME, 0);
413         else
414           mutt_copy_message (fpout, Context, h, 0, 0);
415
416         fflush (fpout);
417         if (h->env->from)
418           tmp = mutt_expand_aliases (h->env->from);
419         else if (h->env->sender)
420           tmp = mutt_expand_aliases (h->env->sender);
421         mbox = tmp ? tmp->mailbox : NULL;
422         if (mbox) {             /* else ? */
423           mutt_message (_("Trying to extract S/MIME certificates...\n"));
424           crypt_smime_invoke_import (tempfname, mbox);
425         }
426       }
427     }
428   }
429
430   fclose (fpout);
431   if (isendwin ())
432     mutt_any_key_to_continue (NULL);
433
434   mutt_unlink (tempfname);
435
436   unset_option (OPTDONTHANDLEPGPKEYS);
437 }
438
439
440
441 int crypt_get_keys (HEADER * msg, char **keylist)
442 {
443   /* Do a quick check to make sure that we can find all of the encryption
444    * keys if the user has requested this service.
445    */
446
447   set_option (OPTPGPCHECKTRUST);
448
449   *keylist = NULL;
450
451   if (msg->security & ENCRYPT) {
452     if (msg->security & APPLICATION_PGP) {
453       if ((*keylist = crypt_pgp_findkeys (msg->env->to, msg->env->cc,
454                                           msg->env->bcc)) == NULL)
455         return (-1);
456       unset_option (OPTPGPCHECKTRUST);
457     }
458     if (msg->security & APPLICATION_SMIME) {
459       if ((*keylist = crypt_smime_findkeys (msg->env->to, msg->env->cc,
460                                             msg->env->bcc)) == NULL)
461         return (-1);
462     }
463   }
464
465   return (0);
466 }
467
468
469
470 static void crypt_fetch_signatures (BODY ***signatures, BODY * a, int *n)
471 {
472   for (; a; a = a->next) {
473     if (a->type == TYPEMULTIPART)
474       crypt_fetch_signatures (signatures, a->parts, n);
475     else {
476       if ((*n % 5) == 0)
477         p_realloc(signatures, *n + 6);
478
479       (*signatures)[(*n)++] = a;
480     }
481   }
482 }
483
484
485 /*
486  * This routine verifies a  "multipart/signed"  body.
487  */
488
489 int mutt_signed_handler (BODY * a, STATE * s)
490 {
491   char tempfile[_POSIX_PATH_MAX];
492   char *protocol;
493   int protocol_major = TYPEOTHER;
494   char *protocol_minor = NULL;
495
496   BODY *b = a;
497   BODY **signatures = NULL;
498   int sigcnt = 0;
499   int i;
500   short goodsig = 1;
501   int rc = 0;
502
503   protocol = parameter_getval(a->parameter, "protocol");
504   a = a->parts;
505
506   /* extract the protocol information */
507
508   if (protocol) {
509     char major[STRING];
510     char *t;
511
512     if ((protocol_minor = strchr (protocol, '/')))
513       protocol_minor++;
514
515     m_strcpy(major, sizeof(major), protocol);
516     if ((t = strchr (major, '/')))
517       *t = '\0';
518
519     protocol_major = mutt_check_mime_type (major);
520   }
521
522   /* consistency check */
523
524   if (!(a && a->next && a->next->type == protocol_major &&
525         !m_strcasecmp(a->next->subtype, protocol_minor))) {
526     state_attach_puts (_("[-- Error: "
527                          "Inconsistent multipart/signed structure! --]\n\n"),
528                        s);
529     return mutt_body_handler (a, s);
530   }
531
532
533   if (protocol_major == TYPEAPPLICATION
534       && !m_strcasecmp(protocol_minor, "pgp-signature"));
535   else if (protocol_major == TYPEAPPLICATION
536            && !(m_strcasecmp(protocol_minor, "x-pkcs7-signature")
537                 && m_strcasecmp(protocol_minor, "pkcs7-signature")));
538   else if (protocol_major == TYPEMULTIPART
539            && !m_strcasecmp(protocol_minor, "mixed"));
540   else {
541     state_printf (s, _("[-- Error: "
542                        "Unknown multipart/signed protocol %s! --]\n\n"),
543                   protocol);
544     return mutt_body_handler (a, s);
545   }
546
547   if (s->flags & M_DISPLAY) {
548
549     crypt_fetch_signatures (&signatures, a->next, &sigcnt);
550
551     if (sigcnt) {
552       mutt_mktemp (tempfile);
553       if (crypt_write_signed (a, s, tempfile) == 0) {
554         for (i = 0; i < sigcnt; i++) {
555           if (signatures[i]->type == TYPEAPPLICATION
556               && !m_strcasecmp(signatures[i]->subtype, "pgp-signature")) {
557             if (crypt_pgp_verify_one (signatures[i], s, tempfile) != 0)
558               goodsig = 0;
559
560             continue;
561           }
562
563           if (signatures[i]->type == TYPEAPPLICATION
564           && (!m_strcasecmp(signatures[i]->subtype, "x-pkcs7-signature")
565                || !m_strcasecmp(signatures[i]->subtype, "pkcs7-signature")))
566           {
567             if (crypt_smime_verify_one (signatures[i], s, tempfile) != 0)
568               goodsig = 0;
569
570             continue;
571           }
572
573           state_printf (s, _("[-- Warning: "
574                              "We can't verify %s/%s signatures. --]\n\n"),
575                         TYPE (signatures[i]), signatures[i]->subtype);
576         }
577       }
578
579       mutt_unlink (tempfile);
580
581       b->goodsig = goodsig;
582       b->badsig = !goodsig;
583
584       /* Now display the signed body */
585       state_attach_puts (_("[-- The following data is signed --]\n\n"), s);
586
587
588       p_delete(&signatures);
589     }
590     else
591       state_attach_puts (_("[-- Warning: Can't find any signatures. --]\n\n"),
592                          s);
593   }
594
595   rc = mutt_body_handler (a, s);
596
597   if (s->flags & M_DISPLAY && sigcnt)
598     state_attach_puts (_("\n[-- End of signed data --]\n"), s);
599
600   return (rc);
601 }