refactor import_keys to take directly an open file.
[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 #include <lib-mime/mime.h>
18 #include <lib-ui/curses.h>
19 #include <lib-mx/mx.h>
20
21 #include "alias.h"
22 #include "handler.h"
23 #include "copy.h"
24 #include "crypt.h"
25
26 int mutt_protect (HEADER * msg, char *keylist)
27 {
28   BODY *pbody = NULL, *tmp_pbody = NULL;
29   BODY *tmp_smime_pbody = NULL;
30   BODY *tmp_pgp_pbody = NULL;
31   int flags = msg->security;
32
33   if (!isendwin ())
34     mutt_endwin (NULL);
35
36   tmp_smime_pbody = msg->content;
37   tmp_pgp_pbody = msg->content;
38
39   if (msg->security & SIGN) {
40     if (msg->security & APPLICATION_SMIME) {
41       if (!(tmp_pbody = crypt_smime_sign_message (msg->content)))
42         return -1;
43       pbody = tmp_smime_pbody = tmp_pbody;
44     }
45
46     if ((msg->security & APPLICATION_PGP)
47         && (!(flags & ENCRYPT) || option (OPTPGPRETAINABLESIG))) {
48       if (!(tmp_pbody = crypt_pgp_sign_message (msg->content)))
49         return -1;
50
51       flags &= ~SIGN;
52       pbody = tmp_pgp_pbody = tmp_pbody;
53     }
54
55     if ((msg->security & APPLICATION_SMIME)
56         && (msg->security & APPLICATION_PGP)) {
57       /* here comes the draft ;-) */
58     }
59   }
60
61
62   if (msg->security & ENCRYPT) {
63     if ((msg->security & APPLICATION_SMIME)) {
64       if (!(tmp_pbody = crypt_smime_build_smime_entity (tmp_smime_pbody,
65                                                         keylist))) {
66         /* signed ? free it! */
67         return (-1);
68       }
69       /* free tmp_body if messages was signed AND encrypted ... */
70       if (tmp_smime_pbody != msg->content && tmp_smime_pbody != tmp_pbody) {
71         /* detatch and dont't delete msg->content,
72            which tmp_smime_pbody->parts after signing. */
73         tmp_smime_pbody->parts = tmp_smime_pbody->parts->next;
74         msg->content->next = NULL;
75         body_list_wipe(&tmp_smime_pbody);
76       }
77       pbody = tmp_pbody;
78     }
79
80     if ((msg->security & APPLICATION_PGP)) {
81       if (!(pbody = crypt_pgp_encrypt_message (tmp_pgp_pbody, keylist,
82                                                flags & SIGN))) {
83
84         /* did we perform a retainable signature? */
85         if (flags != msg->security) {
86           /* remove the outer multipart layer */
87           tmp_pgp_pbody = mutt_remove_multipart (tmp_pgp_pbody);
88           /* get rid of the signature */
89           body_list_wipe(&tmp_pgp_pbody->next);
90         }
91
92         return (-1);
93       }
94
95       /* destroy temporary signature envelope when doing retainable 
96        * signatures.
97
98        */
99       if (flags != msg->security) {
100         tmp_pgp_pbody = mutt_remove_multipart (tmp_pgp_pbody);
101         body_list_wipe(&tmp_pgp_pbody->next);
102       }
103     }
104   }
105
106   if (pbody)
107     msg->content = pbody;
108
109   return 0;
110 }
111
112
113 int crypt_query (BODY * m)
114 {
115   int t = 0;
116
117   if (!m)
118     return 0;
119
120   if (m->type == TYPEAPPLICATION) {
121     t |= mutt_is_application_pgp (m);
122
123     t |= mutt_is_application_smime (m);
124     if (t && m->goodsig)
125       t |= GOODSIGN;
126     if (t && m->badsig)
127       t |= BADSIGN;
128   }
129   else if (m->type == TYPETEXT) {
130     t |= mutt_is_application_pgp (m);
131     if (t && m->goodsig)
132       t |= GOODSIGN;
133   }
134
135   if (m->type == TYPEMULTIPART) {
136     t |= mutt_is_multipart_encrypted (m);
137     t |= mutt_is_multipart_signed (m);
138
139     if (t && m->goodsig)
140       t |= GOODSIGN;
141   }
142
143   if (m->type == TYPEMULTIPART || m->type == TYPEMESSAGE) {
144     BODY *p;
145     int u, v, w;
146
147     u = m->parts ? 0xffffffff : 0;      /* Bits set in all parts */
148     w = 0;                      /* Bits set in any part  */
149
150     for (p = m->parts; p; p = p->next) {
151       v = crypt_query (p);
152       u &= v;
153       w |= v;
154     }
155     t |= u | (w & ~GOODSIGN);
156
157     if ((w & GOODSIGN) && !(u & GOODSIGN))
158       t |= PARTSIGN;
159   }
160
161   return t;
162 }
163
164
165 static void crypt_write_signed(BODY * a, STATE * s, FILE *fp)
166 {
167     int c;
168     short hadcr;
169     size_t bytes;
170
171     fseeko (s->fpin, a->hdr_offset, 0);
172     bytes = a->length + a->offset - a->hdr_offset;
173     hadcr = 0;
174     while (bytes > 0) {
175         if ((c = fgetc (s->fpin)) == EOF)
176             break;
177
178         bytes--;
179
180         if (c == '\r')
181             hadcr = 1;
182         else {
183             if (c == '\n' && !hadcr)
184                 fputc ('\r', fp);
185
186             hadcr = 0;
187         }
188         fputc (c, fp);
189     }
190 }
191
192
193
194 void convert_to_7bit (BODY * a)
195 {
196   while (a) {
197     if (a->type == TYPEMULTIPART) {
198       if (a->encoding != ENC7BIT) {
199         a->encoding = ENC7BIT;
200         convert_to_7bit (a->parts);
201       } else {
202         convert_to_7bit (a->parts);
203       }
204     }
205     else if (a->type == TYPEMESSAGE &&
206              m_strcasecmp(a->subtype, "delivery-status")) {
207       if (a->encoding != ENC7BIT)
208         mutt_message_to_7bit (a, NULL);
209     }
210     else if (a->encoding == ENC8BIT)
211       a->encoding = ENCQUOTEDPRINTABLE;
212     else if (a->encoding == ENCBINARY)
213       a->encoding = ENCBASE64;
214     else if (a->content && a->encoding != ENCBASE64 &&
215              (a->content->from || a->content->space))
216       a->encoding = ENCQUOTEDPRINTABLE;
217     a = a->next;
218   }
219 }
220
221
222 static void extract_keys_aux(FILE *fpout, HEADER *h)
223 {
224     mutt_parse_mime_message (Context, h);
225
226     rewind(fpout);
227     if (h->security & APPLICATION_PGP) {
228         mutt_copy_message(fpout, Context, h, M_CM_DECODE | M_CM_CHARCONV, 0);
229         fflush (fpout);
230
231         mutt_endwin (_("Trying to extract PGP keys...\n"));
232     }
233
234     if (h->security & APPLICATION_SMIME) {
235         if (h->security & ENCRYPT)
236             mutt_copy_message (fpout, Context, h, M_CM_NOHEADER
237                                | M_CM_DECODE_CRYPT | M_CM_DECODE_SMIME, 0);
238         else
239             mutt_copy_message(fpout, Context, h, 0, 0);
240         fflush (fpout);
241
242         mutt_message (_("Trying to extract S/MIME certificates...\n"));
243     }
244
245     rewind(fpout);
246     crypt_invoke_import(fpout, h->security & APPLICATION_SMIME);
247 }
248
249 void crypt_extract_keys_from_messages(HEADER * h)
250 {
251     FILE *tmpfp = tmpfile();
252     if (!tmpfp) {
253         mutt_error(_("Could not create temporary file"));
254         return;
255     }
256
257     set_option(OPTDONTHANDLEPGPKEYS);
258     if (!h) {
259         int i;
260         for (i = 0; i < Context->vcount; i++) {
261             if (!Context->hdrs[Context->v2r[i]]->tagged)
262                 continue;
263             extract_keys_aux(tmpfp, Context->hdrs[Context->v2r[i]]);
264         }
265     } else {
266         extract_keys_aux(tmpfp, h);
267     }
268     unset_option(OPTDONTHANDLEPGPKEYS);
269     m_fclose(&tmpfp);
270
271     if (isendwin())
272         mutt_any_key_to_continue(NULL);
273 }
274
275
276
277 int crypt_get_keys (HEADER * msg, char **keylist)
278 {
279   /* Do a quick check to make sure that we can find all of the encryption
280    * keys if the user has requested this service.
281    */
282
283   set_option (OPTPGPCHECKTRUST);
284
285   *keylist = NULL;
286
287   if (msg->security & ENCRYPT) {
288     if (msg->security & APPLICATION_PGP) {
289       if ((*keylist = crypt_pgp_findkeys (msg->env->to, msg->env->cc,
290                                           msg->env->bcc)) == NULL)
291         return (-1);
292       unset_option (OPTPGPCHECKTRUST);
293     }
294     if (msg->security & APPLICATION_SMIME) {
295       if ((*keylist = crypt_smime_findkeys (msg->env->to, msg->env->cc,
296                                             msg->env->bcc)) == NULL)
297         return (-1);
298     }
299   }
300
301   return (0);
302 }
303
304
305
306 static void crypt_fetch_signatures (BODY ***signatures, BODY * a, int *n)
307 {
308   for (; a; a = a->next) {
309     if (a->type == TYPEMULTIPART)
310       crypt_fetch_signatures (signatures, a->parts, n);
311     else {
312       if ((*n % 5) == 0)
313         p_realloc(signatures, *n + 6);
314
315       (*signatures)[(*n)++] = a;
316     }
317   }
318 }
319
320
321 /*
322  * This routine verifies a  "multipart/signed"  body.
323  */
324
325 int mutt_signed_handler (BODY * a, STATE * s)
326 {
327   char tempfile[_POSIX_PATH_MAX];
328   FILE * tempfp;
329   char *protocol;
330   int protocol_major = TYPEOTHER;
331   char *protocol_minor = NULL;
332
333   BODY *b = a;
334   BODY **signatures = NULL;
335   int sigcnt = 0;
336   int i;
337   short goodsig = 1;
338   int rc = 0;
339
340   protocol = parameter_getval(a->parameter, "protocol");
341   a = a->parts;
342
343   /* extract the protocol information */
344
345   if (protocol) {
346     char major[STRING];
347     char *t;
348
349     if ((protocol_minor = strchr (protocol, '/')))
350       protocol_minor++;
351
352     m_strcpy(major, sizeof(major), protocol);
353     if ((t = strchr (major, '/')))
354       *t = '\0';
355
356     protocol_major = mutt_check_mime_type (major);
357   }
358
359   /* consistency check */
360
361   if (!(a && a->next && a->next->type == protocol_major &&
362         !m_strcasecmp(a->next->subtype, protocol_minor))) {
363     state_attach_puts (_("[-- Error: "
364                          "Inconsistent multipart/signed structure! --]\n\n"),
365                        s);
366     return mutt_body_handler (a, s);
367   }
368
369
370   if (protocol_major == TYPEAPPLICATION
371       && !m_strcasecmp(protocol_minor, "pgp-signature"));
372   else if (protocol_major == TYPEAPPLICATION
373            && !(m_strcasecmp(protocol_minor, "x-pkcs7-signature")
374                 && m_strcasecmp(protocol_minor, "pkcs7-signature")));
375   else if (protocol_major == TYPEMULTIPART
376            && !m_strcasecmp(protocol_minor, "mixed"));
377   else {
378     state_printf (s, _("[-- Error: "
379                        "Unknown multipart/signed protocol %s! --]\n\n"),
380                   protocol);
381     return mutt_body_handler (a, s);
382   }
383
384   if (s->flags & M_DISPLAY) {
385
386     crypt_fetch_signatures (&signatures, a->next, &sigcnt);
387
388     if (sigcnt) {
389       tempfp = m_tempfile(tempfile, sizeof(tempfile), NONULL(MCore.tmpdir), NULL);
390       if (!tempfp) {
391           mutt_error(_("Could not create temporary file"));
392       } else {
393         crypt_write_signed(a, s, tempfp);
394         m_fclose(&tempfp);
395         for (i = 0; i < sigcnt; i++) {
396           if (signatures[i]->type == TYPEAPPLICATION
397               && !m_strcasecmp(signatures[i]->subtype, "pgp-signature")) {
398             if (crypt_pgp_verify_one (signatures[i], s, tempfile) != 0)
399               goodsig = 0;
400
401             continue;
402           }
403
404           if (signatures[i]->type == TYPEAPPLICATION
405           && (!m_strcasecmp(signatures[i]->subtype, "x-pkcs7-signature")
406                || !m_strcasecmp(signatures[i]->subtype, "pkcs7-signature")))
407           {
408             if (crypt_smime_verify_one (signatures[i], s, tempfile) != 0)
409               goodsig = 0;
410
411             continue;
412           }
413
414           state_printf (s, _("[-- Warning: "
415                              "We can't verify %s/%s signatures. --]\n\n"),
416                         TYPE (signatures[i]), signatures[i]->subtype);
417         }
418       }
419
420       mutt_unlink (tempfile);
421
422       b->goodsig = goodsig;
423       b->badsig = !goodsig;
424
425       /* Now display the signed body */
426       state_attach_puts (_("[-- The following data is signed --]\n\n"), s);
427
428
429       p_delete(&signatures);
430     }
431     else
432       state_attach_puts (_("[-- Warning: Can't find any signatures. --]\n\n"),
433                          s);
434   }
435
436   rc = mutt_body_handler (a, s);
437
438   if (s->flags & M_DISPLAY && sigcnt)
439     state_attach_puts (_("\n[-- End of signed data --]\n"), s);
440
441   return (rc);
442 }