4087e3376f6bd0948c8c7bdbb12c58f4eada0df8
[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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 #include "pgpmime.h"
35 #include "sgpgme.h"
36 #include "prefs_common.h"
37 #include "prefs_gpg.h"
38 #include "passphrase.h"
39
40 typedef struct _PrivacyDataPGP PrivacyDataPGP;
41
42 struct _PrivacyDataPGP
43 {
44         PrivacyData     data;
45         
46         gboolean        done_sigtest;
47         gboolean        is_signed;
48         GpgmeSigStat    sigstatus;
49         GpgmeCtx        ctx;
50 };
51
52 static PrivacySystem pgpmime_system;
53
54 static gint pgpmime_check_signature(MimeInfo *mimeinfo);
55
56 static PrivacyDataPGP *pgpmime_new_privacydata()
57 {
58         PrivacyDataPGP *data;
59
60         data = g_new0(PrivacyDataPGP, 1);
61         data->data.system = &pgpmime_system;
62         data->done_sigtest = FALSE;
63         data->is_signed = FALSE;
64         data->sigstatus = GPGME_SIG_STAT_NONE;
65         gpgme_new(&data->ctx);
66         
67         return data;
68 }
69
70 static void pgpmime_free_privacydata(PrivacyData *_data)
71 {
72         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
73         gpgme_release(data->ctx);
74         g_free(data);
75 }
76
77 static gboolean pgpmime_is_signed(MimeInfo *mimeinfo)
78 {
79         MimeInfo *parent;
80         MimeInfo *signature;
81         const gchar *protocol;
82         PrivacyDataPGP *data = NULL;
83         
84         g_return_val_if_fail(mimeinfo != NULL, FALSE);
85         if (mimeinfo->privacy != NULL) {
86                 data = (PrivacyDataPGP *) mimeinfo->privacy;
87                 if (data->done_sigtest)
88                         return data->is_signed;
89         }
90         
91         /* check parent */
92         parent = procmime_mimeinfo_parent(mimeinfo);
93         if (parent == NULL)
94                 return FALSE;
95         if ((parent->type != MIMETYPE_MULTIPART) ||
96             g_strcasecmp(parent->subtype, "signed"))
97                 return FALSE;
98         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
99         if ((protocol == NULL) || g_strcasecmp(protocol, "application/pgp-signature"))
100                 return FALSE;
101
102         /* check if mimeinfo is the first child */
103         if (parent->node->children->data != mimeinfo)
104                 return FALSE;
105
106         /* check signature */
107         signature = parent->node->children->next != NULL ? 
108             (MimeInfo *) parent->node->children->next->data : NULL;
109         if (signature == NULL)
110                 return FALSE;
111         if ((signature->type != MIMETYPE_APPLICATION) ||
112             g_strcasecmp(signature->subtype, "pgp-signature"))
113                 return FALSE;
114
115         if (data == NULL) {
116                 data = pgpmime_new_privacydata();
117                 mimeinfo->privacy = (PrivacyData *) data;
118         }
119         data->done_sigtest = TRUE;
120         data->is_signed = TRUE;
121
122         return TRUE;
123 }
124
125 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
126 {
127         gchar *ret;
128         GString *textbuffer;
129         guint boundary_len;
130         gchar buf[BUFFSIZE];
131
132         boundary_len = strlen(boundary);
133         while (fgets(buf, sizeof(buf), fp) != NULL)
134                 if (IS_BOUNDARY(buf, boundary, boundary_len))
135                         break;
136
137         textbuffer = g_string_new("");
138         while (fgets(buf, sizeof(buf), fp) != NULL) {
139                 gchar *buf2;
140
141                 if (IS_BOUNDARY(buf, boundary, boundary_len))
142                         break;
143                 
144                 buf2 = canonicalize_str(buf);
145                 g_string_append(textbuffer, buf2);
146                 g_free(buf2);
147         }
148         g_string_truncate(textbuffer, textbuffer->len - 2);
149                 
150         ret = textbuffer->str;
151         g_string_free(textbuffer, FALSE);
152
153         return ret;
154 }
155
156 static gint pgpmime_check_signature(MimeInfo *mimeinfo)
157 {
158         PrivacyDataPGP *data;
159         MimeInfo *parent, *signature;
160         FILE *fp;
161         gchar *boundary;
162         gchar *textstr;
163         GpgmeData sigdata, textdata;
164         
165         g_return_val_if_fail(mimeinfo != NULL, -1);
166         g_return_val_if_fail(mimeinfo->privacy != NULL, -1);
167         data = (PrivacyDataPGP *) mimeinfo->privacy;
168         
169         debug_print("Checking PGP/MIME signature\n");
170         parent = procmime_mimeinfo_parent(mimeinfo);
171
172         fp = fopen(parent->data.filename, "rb");
173         g_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
174         
175         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
176         if (!boundary)
177                 return 0;
178
179         textstr = get_canonical_content(fp, boundary);
180
181         gpgme_data_new_from_mem(&textdata, textstr, strlen(textstr), 0);
182         signature = (MimeInfo *) mimeinfo->node->next->data;
183         sigdata = sgpgme_data_from_mimeinfo(signature);
184
185         data->sigstatus =
186                 sgpgme_verify_signature (data->ctx, sigdata, textdata);
187         
188         gpgme_data_release(sigdata);
189         gpgme_data_release(textdata);
190         g_free(textstr);
191         fclose(fp);
192         
193         return 0;
194 }
195
196 static SignatureStatus pgpmime_get_sig_status(MimeInfo *mimeinfo)
197 {
198         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
199         
200         g_return_val_if_fail(data != NULL, SIGNATURE_INVALID);
201
202         if (data->sigstatus == GPGME_SIG_STAT_NONE && 
203             prefs_gpg_get_config()->auto_check_signatures)
204                 pgpmime_check_signature(mimeinfo);
205         
206         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
207 }
208
209 static gchar *pgpmime_get_sig_info_short(MimeInfo *mimeinfo)
210 {
211         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
212         
213         g_return_val_if_fail(data != NULL, g_strdup("Error"));
214
215         if (data->sigstatus == GPGME_SIG_STAT_NONE && 
216             prefs_gpg_get_config()->auto_check_signatures)
217                 pgpmime_check_signature(mimeinfo);
218         
219         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
220 }
221
222 static gchar *pgpmime_get_sig_info_full(MimeInfo *mimeinfo)
223 {
224         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
225         
226         g_return_val_if_fail(data != NULL, g_strdup("Error"));
227
228         if (data->sigstatus == GPGME_SIG_STAT_NONE && 
229             prefs_gpg_get_config()->auto_check_signatures)
230                 pgpmime_check_signature(mimeinfo);
231         
232         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
233 }
234
235 static gboolean pgpmime_is_encrypted(MimeInfo *mimeinfo)
236 {
237         MimeInfo *tmpinfo;
238         const gchar *tmpstr;
239         
240         if (mimeinfo->type != MIMETYPE_MULTIPART)
241                 return FALSE;
242         if (g_strcasecmp(mimeinfo->subtype, "encrypted"))
243                 return FALSE;
244         tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "protocol");
245         if ((tmpstr == NULL) || g_strcasecmp(tmpstr, "application/pgp-encrypted"))
246                 return FALSE;
247         if (g_node_n_children(mimeinfo->node) != 2)
248                 return FALSE;
249         
250         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 0)->data;
251         if (tmpinfo->type != MIMETYPE_APPLICATION)
252                 return FALSE;
253         if (g_strcasecmp(tmpinfo->subtype, "pgp-encrypted"))
254                 return FALSE;
255         
256         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
257         if (tmpinfo->type != MIMETYPE_APPLICATION)
258                 return FALSE;
259         if (g_strcasecmp(tmpinfo->subtype, "octet-stream"))
260                 return FALSE;
261         
262         return TRUE;
263 }
264
265 static MimeInfo *pgpmime_decrypt(MimeInfo *mimeinfo)
266 {
267         MimeInfo *encinfo, *decinfo, *parseinfo;
268         GpgmeData cipher, plain;
269         static gint id = 0;
270         FILE *dstfp;
271         gint nread;
272         gchar *fname;
273         gchar buf[BUFFSIZE];
274         GpgmeSigStat sigstat = 0;
275         PrivacyDataPGP *data = NULL;
276         GpgmeCtx ctx;
277         
278         if (gpgme_new(&ctx) != GPGME_No_Error)
279                 return NULL;
280
281         
282         g_return_val_if_fail(pgpmime_is_encrypted(mimeinfo), NULL);
283         
284         encinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
285
286         cipher = sgpgme_data_from_mimeinfo(encinfo);
287         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
288
289         gpgme_data_release(cipher);
290         if (plain == NULL) {
291                 gpgme_release(ctx);
292                 return NULL;
293         }
294
295         fname = g_strdup_printf("%s%cplaintext.%08x",
296                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
297
298         if ((dstfp = fopen(fname, "wb")) == NULL) {
299                 FILE_OP_ERROR(fname, "fopen");
300                 g_free(fname);
301                 gpgme_data_release(plain);
302                 gpgme_release(ctx);
303                 return NULL;
304         }
305
306         fprintf(dstfp, "MIME-Version: 1.0\n");
307         gpgme_data_rewind (plain);
308         while (gpgme_data_read(plain, buf, sizeof(buf), &nread) == GPGME_No_Error) {
309                 fwrite (buf, nread, 1, dstfp);
310         }
311         fclose(dstfp);
312         
313         gpgme_data_release(plain);
314
315         parseinfo = procmime_scan_file(fname);
316         g_free(fname);
317         if (parseinfo == NULL) {
318                 gpgme_release(ctx);
319                 return NULL;
320         }
321         decinfo = g_node_first_child(parseinfo->node) != NULL ?
322                 g_node_first_child(parseinfo->node)->data : NULL;
323         if (decinfo == NULL) {
324                 gpgme_release(ctx);
325                 return NULL;
326         }
327
328         g_node_unlink(decinfo->node);
329         procmime_mimeinfo_free_all(parseinfo);
330
331         decinfo->tmp = TRUE;
332
333         if (sigstat != GPGME_SIG_STAT_NONE) {
334                 if (decinfo->privacy != NULL) {
335                         data = (PrivacyDataPGP *) decinfo->privacy;
336                 } else {
337                         data = pgpmime_new_privacydata();
338                         decinfo->privacy = (PrivacyData *) data;        
339                 }
340                 data->done_sigtest = TRUE;
341                 data->is_signed = TRUE;
342                 data->sigstatus = sigstat;
343                 if (data->ctx)
344                         gpgme_release(data->ctx);
345                 data->ctx = ctx;
346         } else
347                 gpgme_release(ctx);
348
349         return decinfo;
350 }
351
352 /*
353  * Find TAG in XML and return a pointer into xml set just behind the
354  * closing angle.  Return NULL if not found. 
355  */
356 static const char *
357 find_xml_tag (const char *xml, const char *tag)
358 {
359     int taglen = strlen (tag);
360     const char *s = xml;
361  
362     while ( (s = strchr (s, '<')) ) {
363         s++;
364         if (!strncmp (s, tag, taglen)) {
365             const char *s2 = s + taglen;
366             if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
367                 /* found */
368                 while (*s2 && *s2 != '>') /* skip attributes */
369                     s2++;
370                 /* fixme: do need to handle angles inside attribute vallues? */
371                 return *s2? (s2+1):NULL;
372             }
373         }
374         while (*s && *s != '>') /* skip to end of tag */
375             s++;
376     }
377     return NULL;
378 }
379
380
381 /*
382  * Extract the micalg from an GnupgOperationInfo XML container.
383  */
384 static char *
385 extract_micalg (char *xml)
386 {
387     const char *s;
388
389     s = find_xml_tag (xml, "GnupgOperationInfo");
390     if (s) {
391         const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
392         s = find_xml_tag (s, "signature");
393         if (s && s_end && s < s_end) {
394             const char *s_end2 = find_xml_tag (s, "/signature");
395             if (s_end2 && s_end2 < s_end) {
396                 s = find_xml_tag (s, "micalg");
397                 if (s && s < s_end2) {
398                     s_end = strchr (s, '<');
399                     if (s_end) {
400                         char *p = g_malloc (s_end - s + 1);
401                         memcpy (p, s, s_end - s);
402                         p[s_end-s] = 0;
403                         return p;
404                     }
405                 }
406             }
407         }
408     }
409     return NULL;
410 }
411
412 gboolean pgpmime_sign(MimeInfo *mimeinfo, PrefsAccount *account)
413 {
414         MimeInfo *msgcontent, *sigmultipart, *newinfo;
415         gchar *textstr, *opinfo, *micalg;
416         FILE *fp;
417         gchar *boundary, *sigcontent;
418         GpgmeCtx ctx;
419         GpgmeData gpgtext, gpgsig;
420         guint len;
421         struct passphrase_cb_info_s info;
422
423         memset (&info, 0, sizeof info);
424
425         /* remove content node from message */
426         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
427         g_node_unlink(msgcontent->node);
428
429         /* create temporary multipart for content */
430         sigmultipart = procmime_mimeinfo_new();
431         sigmultipart->type = MIMETYPE_MULTIPART;
432         sigmultipart->subtype = g_strdup("signed");
433         boundary = generate_mime_boundary("Signature");
434         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
435                             g_strdup(boundary));
436         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
437                             g_strdup("application/pgp-signature"));
438         g_node_append(sigmultipart->node, msgcontent->node);
439         g_node_append(mimeinfo->node, sigmultipart->node);
440
441         /* write message content to temporary file */
442         fp = my_tmpfile();
443         procmime_write_mimeinfo(sigmultipart, fp);
444         rewind(fp);
445
446         /* read temporary file into memory */
447         textstr = get_canonical_content(fp, boundary);
448
449         fclose(fp);
450
451         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
452         gpgme_data_new(&gpgsig);
453         gpgme_new(&ctx);
454         gpgme_set_textmode(ctx, 1);
455         gpgme_set_armor(ctx, 1);
456
457         if (!sgpgme_setup_signers(ctx, account))
458                 return FALSE;
459
460         if (!getenv("GPG_AGENT_INFO")) {
461                 info.c = ctx;
462                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
463         }
464
465         if (gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH) != GPGME_No_Error) {
466                 gpgme_release(ctx);
467                 return FALSE;
468         }
469         opinfo = gpgme_get_op_info(ctx, 0);
470         micalg = extract_micalg(opinfo);
471         g_free(opinfo);
472
473         gpgme_release(ctx);
474         sigcontent = gpgme_data_release_and_get_mem(gpgsig, &len);
475         gpgme_data_release(gpgtext);
476         g_free(textstr);
477
478         /* add signature */
479         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
480                             micalg);
481
482         newinfo = procmime_mimeinfo_new();
483         newinfo->type = MIMETYPE_APPLICATION;
484         newinfo->subtype = g_strdup("pgp-signature");
485         newinfo->content = MIMECONTENT_MEM;
486         newinfo->data.mem = g_malloc(len + 1);
487         g_memmove(newinfo->data.mem, sigcontent, len);
488         newinfo->data.mem[len] = '\0';
489         g_node_append(sigmultipart->node, newinfo->node);
490
491         g_free(sigcontent);
492
493         return TRUE;
494 }
495
496 gchar *pgpmime_get_encrypt_data(GSList *recp_names)
497 {
498         return sgpgme_get_encrypt_data(recp_names);
499 }
500
501 gboolean pgpmime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
502 {
503         MimeInfo *msgcontent, *encmultipart, *newinfo;
504         FILE *fp;
505         gchar *boundary, *enccontent;
506         guint len;
507         gchar *textstr;
508         GpgmeData gpgtext, gpgenc;
509         gchar **recipients, **nextrecp;
510         GpgmeRecipients recp;
511         GpgmeCtx ctx;
512
513         /* build GpgmeRecipients from encrypt_data */
514         recipients = g_strsplit(encrypt_data, " ", 0);
515         gpgme_recipients_new(&recp);
516         for (nextrecp = recipients; *nextrecp != NULL; nextrecp++) {
517                 gpgme_recipients_add_name_with_validity(recp, *nextrecp,
518                                                         GPGME_VALIDITY_FULL);
519         }
520         g_strfreev(recipients);
521
522         debug_print("Encrypting message content\n");
523
524         /* remove content node from message */
525         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
526         g_node_unlink(msgcontent->node);
527
528         /* create temporary multipart for content */
529         encmultipart = procmime_mimeinfo_new();
530         encmultipart->type = MIMETYPE_MULTIPART;
531         encmultipart->subtype = g_strdup("encrypted");
532         boundary = generate_mime_boundary("Encrypt");
533         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
534                             g_strdup(boundary));
535         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
536                             g_strdup("application/pgp-encrypted"));
537         g_node_append(encmultipart->node, msgcontent->node);
538
539         /* write message content to temporary file */
540         fp = my_tmpfile();
541         procmime_write_mimeinfo(encmultipart, fp);
542         rewind(fp);
543
544         /* read temporary file into memory */
545         textstr = get_canonical_content(fp, boundary);
546
547         fclose(fp);
548
549         /* encrypt data */
550         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
551         gpgme_data_new(&gpgenc);
552         gpgme_new(&ctx);
553         gpgme_set_armor(ctx, 1);
554
555         gpgme_op_encrypt(ctx, recp, gpgtext, gpgenc);
556
557         gpgme_release(ctx);
558         enccontent = gpgme_data_release_and_get_mem(gpgenc, &len);
559         gpgme_recipients_release(recp);
560         gpgme_data_release(gpgtext);
561         g_free(textstr);
562
563         /* create encrypted multipart */
564         g_node_unlink(msgcontent->node);
565         procmime_mimeinfo_free_all(msgcontent);
566         g_node_append(mimeinfo->node, encmultipart->node);
567
568         newinfo = procmime_mimeinfo_new();
569         newinfo->type = MIMETYPE_APPLICATION;
570         newinfo->subtype = g_strdup("pgp-encrypted");
571         newinfo->content = MIMECONTENT_MEM;
572         newinfo->data.mem = g_strdup("Version: 1\n");
573         g_node_append(encmultipart->node, newinfo->node);
574
575         newinfo = procmime_mimeinfo_new();
576         newinfo->type = MIMETYPE_APPLICATION;
577         newinfo->subtype = g_strdup("octet-stream");
578         newinfo->content = MIMECONTENT_MEM;
579         newinfo->data.mem = g_malloc(len + 1);
580         g_memmove(newinfo->data.mem, enccontent, len);
581         newinfo->data.mem[len] = '\0';
582         g_node_append(encmultipart->node, newinfo->node);
583
584         g_free(enccontent);
585
586         return TRUE;
587 }
588
589 static PrivacySystem pgpmime_system = {
590         "pgpmime",                      /* id */
591         "PGP Mime",                     /* name */
592
593         pgpmime_free_privacydata,       /* free_privacydata */
594
595         pgpmime_is_signed,              /* is_signed(MimeInfo *) */
596         pgpmime_check_signature,        /* check_signature(MimeInfo *) */
597         pgpmime_get_sig_status,         /* get_sig_status(MimeInfo *) */
598         pgpmime_get_sig_info_short,     /* get_sig_info_short(MimeInfo *) */
599         pgpmime_get_sig_info_full,      /* get_sig_info_full(MimeInfo *) */
600
601         pgpmime_is_encrypted,           /* is_encrypted(MimeInfo *) */
602         pgpmime_decrypt,                /* decrypt(MimeInfo *) */
603
604         TRUE,
605         pgpmime_sign,
606
607         TRUE,
608         pgpmime_get_encrypt_data,
609         pgpmime_encrypt,
610 };
611
612 void pgpmime_init()
613 {
614         privacy_register_system(&pgpmime_system);
615 }
616
617 void pgpmime_done()
618 {
619         privacy_unregister_system(&pgpmime_system);
620 }
621
622 #endif /* USE_GPGME */