2e0ee5089ae518d008046beee0a32c9bb03468b8
[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         
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                 return NULL;
292         
293         fname = g_strdup_printf("%s%cplaintext.%08x",
294                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
295
296         if ((dstfp = fopen(fname, "wb")) == NULL) {
297                 FILE_OP_ERROR(fname, "fopen");
298                 g_free(fname);
299                 gpgme_data_release(plain);
300                 return NULL;
301         }
302
303         fprintf(dstfp, "MIME-Version: 1.0\n");
304         gpgme_data_rewind (plain);
305         while (gpgme_data_read(plain, buf, sizeof(buf), &nread) == GPGME_No_Error) {
306                 fwrite (buf, nread, 1, dstfp);
307         }
308         fclose(dstfp);
309         
310         gpgme_data_release(plain);
311
312         parseinfo = procmime_scan_file(fname);
313         g_free(fname);
314         if (parseinfo == NULL)
315                 return NULL;
316         decinfo = g_node_first_child(parseinfo->node) != NULL ?
317                 g_node_first_child(parseinfo->node)->data : NULL;
318         if (decinfo == NULL)
319                 return NULL;
320
321         g_node_unlink(decinfo->node);
322         procmime_mimeinfo_free_all(parseinfo);
323
324         decinfo->tmp = TRUE;
325
326         if (sigstat != GPGME_SIG_STAT_NONE) {
327                 if (decinfo->privacy != NULL) {
328                         data = (PrivacyDataPGP *) decinfo->privacy;
329                 } else {
330                         data = pgpmime_new_privacydata();
331                         decinfo->privacy = (PrivacyData *) data;        
332                 }
333                 data->done_sigtest = TRUE;
334                 data->is_signed = TRUE;
335                 data->sigstatus = sigstat;
336                 if (data->ctx)
337                         gpgme_release(data->ctx);
338                 data->ctx = ctx;
339         } else
340                 gpgme_release(ctx);
341
342         return decinfo;
343 }
344
345 /*
346  * Find TAG in XML and return a pointer into xml set just behind the
347  * closing angle.  Return NULL if not found. 
348  */
349 static const char *
350 find_xml_tag (const char *xml, const char *tag)
351 {
352     int taglen = strlen (tag);
353     const char *s = xml;
354  
355     while ( (s = strchr (s, '<')) ) {
356         s++;
357         if (!strncmp (s, tag, taglen)) {
358             const char *s2 = s + taglen;
359             if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
360                 /* found */
361                 while (*s2 && *s2 != '>') /* skip attributes */
362                     s2++;
363                 /* fixme: do need to handle angles inside attribute vallues? */
364                 return *s2? (s2+1):NULL;
365             }
366         }
367         while (*s && *s != '>') /* skip to end of tag */
368             s++;
369     }
370     return NULL;
371 }
372
373
374 /*
375  * Extract the micalg from an GnupgOperationInfo XML container.
376  */
377 static char *
378 extract_micalg (char *xml)
379 {
380     const char *s;
381
382     s = find_xml_tag (xml, "GnupgOperationInfo");
383     if (s) {
384         const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
385         s = find_xml_tag (s, "signature");
386         if (s && s_end && s < s_end) {
387             const char *s_end2 = find_xml_tag (s, "/signature");
388             if (s_end2 && s_end2 < s_end) {
389                 s = find_xml_tag (s, "micalg");
390                 if (s && s < s_end2) {
391                     s_end = strchr (s, '<');
392                     if (s_end) {
393                         char *p = g_malloc (s_end - s + 1);
394                         memcpy (p, s, s_end - s);
395                         p[s_end-s] = 0;
396                         return p;
397                     }
398                 }
399             }
400         }
401     }
402     return NULL;
403 }
404
405 gboolean pgpmime_sign(MimeInfo *mimeinfo)
406 {
407         MimeInfo *msgcontent, *sigmultipart, *newinfo;
408         gchar *textstr, *opinfo, *micalg;
409         FILE *fp;
410         gchar *boundary, *sigcontent;
411         GpgmeCtx ctx;
412         GpgmeData gpgtext, gpgsig;
413         guint len;
414         struct passphrase_cb_info_s info;
415   
416         memset (&info, 0, sizeof info);
417
418         /* remove content node from message */
419         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
420         g_node_unlink(msgcontent->node);
421
422         /* create temporary multipart for content */
423         sigmultipart = procmime_mimeinfo_new();
424         sigmultipart->type = MIMETYPE_MULTIPART;
425         sigmultipart->subtype = g_strdup("signed");
426         boundary = generate_mime_boundary("Signature");
427         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
428                             g_strdup(boundary));
429         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
430                             g_strdup("application/pgp-signature"));
431         g_node_append(sigmultipart->node, msgcontent->node);
432         g_node_append(mimeinfo->node, sigmultipart->node);
433
434         /* write message content to temporary file */
435         fp = my_tmpfile();
436         procmime_write_mimeinfo(sigmultipart, fp);
437         rewind(fp);
438
439         /* read temporary file into memory */
440         textstr = get_canonical_content(fp, boundary);
441
442         fclose(fp);
443
444         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
445         gpgme_data_new(&gpgsig);
446         gpgme_new(&ctx);
447         gpgme_set_textmode(ctx, 1);
448         gpgme_set_armor(ctx, 1);
449         gpgme_signers_clear(ctx);
450
451         if (!getenv("GPG_AGENT_INFO")) {
452                 info.c = ctx;
453                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
454             }
455
456         if (gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH) != GPGME_No_Error)
457                 return FALSE;
458         opinfo = gpgme_get_op_info(ctx, 0);
459         micalg = extract_micalg(opinfo);
460         g_free(opinfo);
461
462         gpgme_release(ctx);
463         sigcontent = gpgme_data_release_and_get_mem(gpgsig, &len);
464         gpgme_data_release(gpgtext);
465         g_free(textstr);
466
467         /* add signature */
468         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
469                             micalg);
470
471         newinfo = procmime_mimeinfo_new();
472         newinfo->type = MIMETYPE_APPLICATION;
473         newinfo->subtype = g_strdup("pgp-signature");
474         newinfo->content = MIMECONTENT_MEM;
475         newinfo->data.mem = g_memdup(sigcontent, len + 1);
476         newinfo->data.mem[len] = '\0';
477         g_node_append(sigmultipart->node, newinfo->node);
478
479         g_free(sigcontent);
480
481         return TRUE;
482 }
483
484 gchar *pgpmime_get_encrypt_data(GSList *recp_names)
485 {
486         return sgpgme_get_encrypt_data(recp_names);
487 }
488
489 gboolean pgpmime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
490 {
491         MimeInfo *msgcontent, *encmultipart, *newinfo;
492         FILE *fp;
493         gchar *boundary, *enccontent;
494         guint len;
495         gchar *textstr;
496         GpgmeData gpgtext, gpgenc;
497         gchar **recipients, **nextrecp;
498         GpgmeRecipients recp;
499         GpgmeCtx ctx;
500
501         /* build GpgmeRecipients from encrypt_data */
502         recipients = g_strsplit(encrypt_data, " ", 0);
503         gpgme_recipients_new(&recp);
504         for (nextrecp = recipients; *nextrecp != NULL; nextrecp++) {
505                 printf("%s\n", *nextrecp);
506                 gpgme_recipients_add_name_with_validity(recp, *nextrecp,
507                                                         GPGME_VALIDITY_FULL);
508         }
509         g_strfreev(recipients);
510
511         debug_print("Encrypting message content\n");
512
513         /* remove content node from message */
514         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
515         g_node_unlink(msgcontent->node);
516
517         /* create temporary multipart for content */
518         encmultipart = procmime_mimeinfo_new();
519         encmultipart->type = MIMETYPE_MULTIPART;
520         encmultipart->subtype = g_strdup("encrypted");
521         boundary = generate_mime_boundary("Encrypt");
522         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
523                             g_strdup(boundary));
524         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
525                             g_strdup("application/pgp-encrypted"));
526         g_node_append(encmultipart->node, msgcontent->node);
527
528         /* write message content to temporary file */
529         fp = my_tmpfile();
530         procmime_write_mimeinfo(encmultipart, fp);
531         rewind(fp);
532
533         /* read temporary file into memory */
534         textstr = get_canonical_content(fp, boundary);
535
536         fclose(fp);
537
538         /* encrypt data */
539         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
540         gpgme_data_new(&gpgenc);
541         gpgme_new(&ctx);
542         gpgme_set_armor(ctx, 1);
543
544         gpgme_op_encrypt(ctx, recp, gpgtext, gpgenc);
545
546         gpgme_release(ctx);
547         enccontent = gpgme_data_release_and_get_mem(gpgenc, &len);
548         gpgme_recipients_release(recp);
549         gpgme_data_release(gpgtext);
550         g_free(textstr);
551
552         /* create encrypted multipart */
553         g_node_unlink(msgcontent->node);
554         procmime_mimeinfo_free_all(msgcontent);
555         g_node_append(mimeinfo->node, encmultipart->node);
556
557         newinfo = procmime_mimeinfo_new();
558         newinfo->type = MIMETYPE_APPLICATION;
559         newinfo->subtype = g_strdup("pgp-encrypted");
560         newinfo->content = MIMECONTENT_MEM;
561         newinfo->data.mem = g_strdup("Version: 1\n");
562         g_node_append(encmultipart->node, newinfo->node);
563
564         newinfo = procmime_mimeinfo_new();
565         newinfo->type = MIMETYPE_APPLICATION;
566         newinfo->subtype = g_strdup("octet-stream");
567         newinfo->content = MIMECONTENT_MEM;
568         newinfo->data.mem = g_memdup(enccontent, len + 1);
569         newinfo->data.mem[len] = '\0';
570         g_node_append(encmultipart->node, newinfo->node);
571
572         g_free(enccontent);
573
574         return TRUE;
575 }
576
577 static PrivacySystem pgpmime_system = {
578         "pgpmime",                      /* id */
579         "PGP Mime",                     /* name */
580
581         pgpmime_free_privacydata,       /* free_privacydata */
582
583         pgpmime_is_signed,              /* is_signed(MimeInfo *) */
584         pgpmime_check_signature,        /* check_signature(MimeInfo *) */
585         pgpmime_get_sig_status,         /* get_sig_status(MimeInfo *) */
586         pgpmime_get_sig_info_short,     /* get_sig_info_short(MimeInfo *) */
587         pgpmime_get_sig_info_full,      /* get_sig_info_full(MimeInfo *) */
588
589         pgpmime_is_encrypted,           /* is_encrypted(MimeInfo *) */
590         pgpmime_decrypt,                /* decrypt(MimeInfo *) */
591
592         TRUE,
593         pgpmime_sign,
594
595         TRUE,
596         pgpmime_get_encrypt_data,
597         pgpmime_encrypt,
598 };
599
600 void pgpmime_init()
601 {
602         privacy_register_system(&pgpmime_system);
603 }
604
605 void pgpmime_done()
606 {
607         privacy_unregister_system(&pgpmime_system);
608 }
609
610 #endif /* USE_GPGME */