2005-09-21 [paul] 1.9.14cvs47
[claws.git] / src / plugins / pgpmime / pgpmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto & the Sylpheed-Claws team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #ifdef USE_GPGME
25
26 #include "defs.h"
27 #include <glib.h>
28 #include <gpgme.h>
29 #include <ctype.h>
30
31 #include "utils.h"
32 #include "privacy.h"
33 #include "procmime.h"
34
35 #include "pgpmime.h"
36 #include <plugins/pgpcore/sgpgme.h>
37 #include <plugins/pgpcore/prefs_gpg.h>
38 #include <plugins/pgpcore/passphrase.h>
39
40 #include "prefs_common.h"
41
42 typedef struct _PrivacyDataPGP PrivacyDataPGP;
43
44 struct _PrivacyDataPGP
45 {
46         PrivacyData     data;
47         
48         gboolean        done_sigtest;
49         gboolean        is_signed;
50         gpgme_verify_result_t   sigstatus;
51         gpgme_ctx_t     ctx;
52 };
53
54 static PrivacySystem pgpmime_system;
55
56 static gint pgpmime_check_signature(MimeInfo *mimeinfo);
57
58 static PrivacyDataPGP *pgpmime_new_privacydata()
59 {
60         PrivacyDataPGP *data;
61
62         data = g_new0(PrivacyDataPGP, 1);
63         data->data.system = &pgpmime_system;
64         data->done_sigtest = FALSE;
65         data->is_signed = FALSE;
66         data->sigstatus = NULL;
67         gpgme_new(&data->ctx);
68         
69         return data;
70 }
71
72 static void pgpmime_free_privacydata(PrivacyData *_data)
73 {
74         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
75         gpgme_release(data->ctx);
76         g_free(data);
77 }
78
79 static gboolean pgpmime_is_signed(MimeInfo *mimeinfo)
80 {
81         MimeInfo *parent;
82         MimeInfo *signature;
83         const gchar *protocol;
84         PrivacyDataPGP *data = NULL;
85         
86         g_return_val_if_fail(mimeinfo != NULL, FALSE);
87         if (mimeinfo->privacy != NULL) {
88                 data = (PrivacyDataPGP *) mimeinfo->privacy;
89                 if (data->done_sigtest)
90                         return data->is_signed;
91         }
92         
93         /* check parent */
94         parent = procmime_mimeinfo_parent(mimeinfo);
95         if (parent == NULL)
96                 return FALSE;
97         if ((parent->type != MIMETYPE_MULTIPART) ||
98             g_ascii_strcasecmp(parent->subtype, "signed"))
99                 return FALSE;
100         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
101         if ((protocol == NULL) || g_ascii_strcasecmp(protocol, "application/pgp-signature"))
102                 return FALSE;
103
104         /* check if mimeinfo is the first child */
105         if (parent->node->children->data != mimeinfo)
106                 return FALSE;
107
108         /* check signature */
109         signature = parent->node->children->next != NULL ? 
110             (MimeInfo *) parent->node->children->next->data : NULL;
111         if (signature == NULL)
112                 return FALSE;
113         if ((signature->type != MIMETYPE_APPLICATION) ||
114             g_ascii_strcasecmp(signature->subtype, "pgp-signature"))
115                 return FALSE;
116
117         if (data == NULL) {
118                 data = pgpmime_new_privacydata();
119                 mimeinfo->privacy = (PrivacyData *) data;
120         }
121         data->done_sigtest = TRUE;
122         data->is_signed = TRUE;
123
124         return TRUE;
125 }
126
127 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
128 {
129         gchar *ret;
130         GString *textbuffer;
131         guint boundary_len;
132         gchar buf[BUFFSIZE];
133
134         boundary_len = strlen(boundary);
135         while (fgets(buf, sizeof(buf), fp) != NULL)
136                 if (IS_BOUNDARY(buf, boundary, boundary_len))
137                         break;
138
139         textbuffer = g_string_new("");
140         while (fgets(buf, sizeof(buf), fp) != NULL) {
141                 gchar *buf2;
142
143                 if (IS_BOUNDARY(buf, boundary, boundary_len))
144                         break;
145                 
146                 buf2 = canonicalize_str(buf);
147                 g_string_append(textbuffer, buf2);
148                 g_free(buf2);
149         }
150         g_string_truncate(textbuffer, textbuffer->len - 2);
151                 
152         ret = textbuffer->str;
153         g_string_free(textbuffer, FALSE);
154
155         return ret;
156 }
157
158 static gint pgpmime_check_signature(MimeInfo *mimeinfo)
159 {
160         PrivacyDataPGP *data;
161         MimeInfo *parent, *signature;
162         FILE *fp;
163         gchar *boundary;
164         gchar *textstr;
165         gpgme_data_t sigdata = NULL, textdata = NULL;
166         gpgme_error_t err;
167         g_return_val_if_fail(mimeinfo != NULL, -1);
168         g_return_val_if_fail(mimeinfo->privacy != NULL, -1);
169         data = (PrivacyDataPGP *) mimeinfo->privacy;
170         gpgme_new(&data->ctx);
171         
172         debug_print("Checking PGP/MIME signature\n");
173         parent = procmime_mimeinfo_parent(mimeinfo);
174
175         fp = g_fopen(parent->data.filename, "rb");
176         g_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
177         
178         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
179         if (!boundary)
180                 return 0;
181
182         textstr = get_canonical_content(fp, boundary);
183
184         err = gpgme_data_new_from_mem(&textdata, textstr, strlen(textstr), 0);
185         if (err) {
186                 debug_print ("gpgme_data_new_from_mem failed: %s\n",
187                    gpgme_strerror (err));
188         }
189         signature = (MimeInfo *) mimeinfo->node->next->data;
190         sigdata = sgpgme_data_from_mimeinfo(signature);
191
192         data->sigstatus =
193                 sgpgme_verify_signature (data->ctx, sigdata, textdata, NULL);
194
195         gpgme_data_release(sigdata);
196         gpgme_data_release(textdata);
197         g_free(textstr);
198         fclose(fp);
199         
200         return 0;
201 }
202
203 static SignatureStatus pgpmime_get_sig_status(MimeInfo *mimeinfo)
204 {
205         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
206         
207         g_return_val_if_fail(data != NULL, SIGNATURE_INVALID);
208
209         if (data->sigstatus == NULL && 
210             prefs_gpg_get_config()->auto_check_signatures)
211                 pgpmime_check_signature(mimeinfo);
212         
213         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
214 }
215
216 static gchar *pgpmime_get_sig_info_short(MimeInfo *mimeinfo)
217 {
218         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
219         
220         g_return_val_if_fail(data != NULL, g_strdup("Error"));
221
222         if (data->sigstatus == NULL && 
223             prefs_gpg_get_config()->auto_check_signatures)
224                 pgpmime_check_signature(mimeinfo);
225         
226         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
227 }
228
229 static gchar *pgpmime_get_sig_info_full(MimeInfo *mimeinfo)
230 {
231         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
232         
233         g_return_val_if_fail(data != NULL, g_strdup("Error"));
234
235         if (data->sigstatus == NULL && 
236             prefs_gpg_get_config()->auto_check_signatures)
237                 pgpmime_check_signature(mimeinfo);
238         
239         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
240 }
241
242 static gboolean pgpmime_is_encrypted(MimeInfo *mimeinfo)
243 {
244         MimeInfo *tmpinfo;
245         const gchar *tmpstr;
246         
247         if (mimeinfo->type != MIMETYPE_MULTIPART)
248                 return FALSE;
249         if (g_ascii_strcasecmp(mimeinfo->subtype, "encrypted"))
250                 return FALSE;
251         tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "protocol");
252         if ((tmpstr == NULL) || g_ascii_strcasecmp(tmpstr, "application/pgp-encrypted"))
253                 return FALSE;
254         if (g_node_n_children(mimeinfo->node) != 2)
255                 return FALSE;
256         
257         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 0)->data;
258         if (tmpinfo->type != MIMETYPE_APPLICATION)
259                 return FALSE;
260         if (g_ascii_strcasecmp(tmpinfo->subtype, "pgp-encrypted"))
261                 return FALSE;
262         
263         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
264         if (tmpinfo->type != MIMETYPE_APPLICATION)
265                 return FALSE;
266         if (g_ascii_strcasecmp(tmpinfo->subtype, "octet-stream"))
267                 return FALSE;
268         
269         return TRUE;
270 }
271
272 static MimeInfo *pgpmime_decrypt(MimeInfo *mimeinfo)
273 {
274         MimeInfo *encinfo, *decinfo, *parseinfo;
275         gpgme_data_t cipher = NULL, plain = NULL;
276         static gint id = 0;
277         FILE *dstfp;
278         gchar *fname;
279         gpgme_verify_result_t sigstat = NULL;
280         PrivacyDataPGP *data = NULL;
281         gpgme_ctx_t ctx;
282         gchar *chars;
283         size_t len;
284
285         if (gpgme_new(&ctx) != GPG_ERR_NO_ERROR)
286                 return NULL;
287
288         
289         g_return_val_if_fail(pgpmime_is_encrypted(mimeinfo), NULL);
290         
291         encinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
292
293         cipher = sgpgme_data_from_mimeinfo(encinfo);
294         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
295
296         gpgme_data_release(cipher);
297         if (plain == NULL) {
298                 debug_print("plain is null!\n");
299                 gpgme_release(ctx);
300                 return NULL;
301         }
302
303         fname = g_strdup_printf("%s%cplaintext.%08x",
304                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
305
306         if ((dstfp = g_fopen(fname, "wb")) == NULL) {
307                 FILE_OP_ERROR(fname, "fopen");
308                 g_free(fname);
309                 gpgme_data_release(plain);
310                 gpgme_release(ctx);
311                 debug_print("can't open!\n");
312                 return NULL;
313         }
314
315         fprintf(dstfp, "MIME-Version: 1.0\n");
316
317         chars = gpgme_data_release_and_get_mem(plain, &len);
318         if (len > 0)
319                 fwrite(chars, len, 1, dstfp);
320         fclose(dstfp);
321
322         parseinfo = procmime_scan_file(fname);
323         g_free(fname);
324         if (parseinfo == NULL) {
325                 gpgme_release(ctx);
326                 return NULL;
327         }
328         decinfo = g_node_first_child(parseinfo->node) != NULL ?
329                 g_node_first_child(parseinfo->node)->data : NULL;
330         if (decinfo == NULL) {
331                 gpgme_release(ctx);
332                 return NULL;
333         }
334
335         g_node_unlink(decinfo->node);
336         procmime_mimeinfo_free_all(parseinfo);
337
338         decinfo->tmp = TRUE;
339
340         if (sigstat != NULL && sigstat->signatures != NULL) {
341                 if (decinfo->privacy != NULL) {
342                         data = (PrivacyDataPGP *) decinfo->privacy;
343                 } else {
344                         data = pgpmime_new_privacydata();
345                         decinfo->privacy = (PrivacyData *) data;        
346                 }
347                 data->done_sigtest = TRUE;
348                 data->is_signed = TRUE;
349                 data->sigstatus = sigstat;
350                 if (data->ctx)
351                         gpgme_release(data->ctx);
352                 data->ctx = ctx;
353         } else
354                 gpgme_release(ctx);
355
356         return decinfo;
357 }
358
359 gboolean pgpmime_sign(MimeInfo *mimeinfo, PrefsAccount *account)
360 {
361         MimeInfo *msgcontent, *sigmultipart, *newinfo;
362         gchar *textstr, *micalg;
363         FILE *fp;
364         gchar *boundary, *sigcontent;
365         gpgme_ctx_t ctx;
366         gpgme_data_t gpgtext, gpgsig;
367         size_t len;
368         struct passphrase_cb_info_s info;
369         gpgme_sign_result_t result = NULL;
370
371         memset (&info, 0, sizeof info);
372
373         /* remove content node from message */
374         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
375         g_node_unlink(msgcontent->node);
376
377         /* create temporary multipart for content */
378         sigmultipart = procmime_mimeinfo_new();
379         sigmultipart->type = MIMETYPE_MULTIPART;
380         sigmultipart->subtype = g_strdup("signed");
381         boundary = generate_mime_boundary("Signature");
382         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
383                             g_strdup(boundary));
384         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
385                             g_strdup("application/pgp-signature"));
386         g_node_append(sigmultipart->node, msgcontent->node);
387         g_node_append(mimeinfo->node, sigmultipart->node);
388
389         /* write message content to temporary file */
390         fp = my_tmpfile();
391         procmime_write_mimeinfo(sigmultipart, fp);
392         rewind(fp);
393
394         /* read temporary file into memory */
395         textstr = get_canonical_content(fp, boundary);
396
397         fclose(fp);
398
399         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
400         gpgme_data_new(&gpgsig);
401         gpgme_new(&ctx);
402         gpgme_set_textmode(ctx, 1);
403         gpgme_set_armor(ctx, 1);
404         gpgme_signers_clear (ctx);
405
406         if (!sgpgme_setup_signers(ctx, account)) {
407                 gpgme_release(ctx);
408                 return FALSE;
409         }
410
411         if (!getenv("GPG_AGENT_INFO")) {
412                 info.c = ctx;
413                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
414         }
415
416         if (gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH) != GPG_ERR_NO_ERROR) {
417                 gpgme_release(ctx);
418                 return FALSE;
419         }
420         result = gpgme_op_sign_result(ctx);
421         if (result && result->signatures) {
422             if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
423                 micalg = g_strdup_printf("PGP-%s", gpgme_hash_algo_name(
424                             result->signatures->hash_algo));
425             } else {
426                 micalg = g_strdup(gpgme_hash_algo_name(
427                             result->signatures->hash_algo));
428             }
429         } else {
430             /* can't get result (maybe no signing key?) */
431             return FALSE;
432         }
433
434         gpgme_release(ctx);
435         sigcontent = gpgme_data_release_and_get_mem(gpgsig, &len);
436         gpgme_data_release(gpgtext);
437         g_free(textstr);
438
439         /* add signature */
440         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
441                             micalg);
442
443         newinfo = procmime_mimeinfo_new();
444         newinfo->type = MIMETYPE_APPLICATION;
445         newinfo->subtype = g_strdup("pgp-signature");
446         newinfo->content = MIMECONTENT_MEM;
447         newinfo->data.mem = g_malloc(len + 1);
448         g_memmove(newinfo->data.mem, sigcontent, len);
449         newinfo->data.mem[len] = '\0';
450         g_node_append(sigmultipart->node, newinfo->node);
451
452         g_free(sigcontent);
453
454         return TRUE;
455 }
456 gchar *pgpmime_get_encrypt_data(GSList *recp_names)
457 {
458         return sgpgme_get_encrypt_data(recp_names);
459 }
460
461 gboolean pgpmime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
462 {
463         MimeInfo *msgcontent, *encmultipart, *newinfo;
464         FILE *fp;
465         gchar *boundary, *enccontent;
466         size_t len;
467         gchar *textstr;
468         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
469         gpgme_ctx_t ctx = NULL;
470         gpgme_key_t *kset = NULL;
471         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
472         gint i = 0;
473         while (fprs[i] && strlen(fprs[i])) {
474                 i++;
475         }
476         
477         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
478         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
479         gpgme_new(&ctx);
480         i = 0;
481         while (fprs[i] && strlen(fprs[i])) {
482                 gpgme_key_t key;
483                 gpgme_error_t err;
484                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
485                 if (err) {
486                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
487                         break;
488                 }
489                 debug_print("found %s at %d\n", fprs[i], i);
490                 kset[i] = key;
491                 i++;
492         }
493         
494         debug_print("Encrypting message content\n");
495
496         /* remove content node from message */
497         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
498         g_node_unlink(msgcontent->node);
499
500         /* create temporary multipart for content */
501         encmultipart = procmime_mimeinfo_new();
502         encmultipart->type = MIMETYPE_MULTIPART;
503         encmultipart->subtype = g_strdup("encrypted");
504         boundary = generate_mime_boundary("Encrypt");
505         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
506                             g_strdup(boundary));
507         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
508                             g_strdup("application/pgp-encrypted"));
509         g_node_append(encmultipart->node, msgcontent->node);
510
511         /* write message content to temporary file */
512         fp = my_tmpfile();
513         procmime_write_mimeinfo(encmultipart, fp);
514         rewind(fp);
515
516         /* read temporary file into memory */
517         textstr = get_canonical_content(fp, boundary);
518
519         fclose(fp);
520
521         /* encrypt data */
522         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
523         gpgme_data_new(&gpgenc);
524         gpgme_set_armor(ctx, 1);
525         gpgme_data_rewind(gpgtext);
526         
527         gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
528
529         gpgme_release(ctx);
530         enccontent = gpgme_data_release_and_get_mem(gpgenc, &len);
531         gpgme_data_release(gpgtext);
532         g_free(textstr);
533
534         /* create encrypted multipart */
535         g_node_unlink(msgcontent->node);
536         procmime_mimeinfo_free_all(msgcontent);
537         g_node_append(mimeinfo->node, encmultipart->node);
538
539         newinfo = procmime_mimeinfo_new();
540         newinfo->type = MIMETYPE_APPLICATION;
541         newinfo->subtype = g_strdup("pgp-encrypted");
542         newinfo->content = MIMECONTENT_MEM;
543         newinfo->data.mem = g_strdup("Version: 1\n");
544         g_node_append(encmultipart->node, newinfo->node);
545
546         newinfo = procmime_mimeinfo_new();
547         newinfo->type = MIMETYPE_APPLICATION;
548         newinfo->subtype = g_strdup("octet-stream");
549         newinfo->content = MIMECONTENT_MEM;
550         newinfo->data.mem = g_malloc(len + 1);
551         g_memmove(newinfo->data.mem, enccontent, len);
552         newinfo->data.mem[len] = '\0';
553         g_node_append(encmultipart->node, newinfo->node);
554
555         g_free(enccontent);
556
557         return TRUE;
558 }
559
560 static PrivacySystem pgpmime_system = {
561         "pgpmime",                      /* id */
562         "PGP MIME",                     /* name */
563
564         pgpmime_free_privacydata,       /* free_privacydata */
565
566         pgpmime_is_signed,              /* is_signed(MimeInfo *) */
567         pgpmime_check_signature,        /* check_signature(MimeInfo *) */
568         pgpmime_get_sig_status,         /* get_sig_status(MimeInfo *) */
569         pgpmime_get_sig_info_short,     /* get_sig_info_short(MimeInfo *) */
570         pgpmime_get_sig_info_full,      /* get_sig_info_full(MimeInfo *) */
571
572         pgpmime_is_encrypted,           /* is_encrypted(MimeInfo *) */
573         pgpmime_decrypt,                /* decrypt(MimeInfo *) */
574
575         TRUE,
576         pgpmime_sign,
577
578         TRUE,
579         pgpmime_get_encrypt_data,
580         pgpmime_encrypt,
581 };
582
583 void pgpmime_init()
584 {
585         privacy_register_system(&pgpmime_system);
586 }
587
588 void pgpmime_done()
589 {
590         privacy_unregister_system(&pgpmime_system);
591 }
592
593 #endif /* USE_GPGME */