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