Implement saving of the certificate chain, making the offline status
[claws.git] / src / common / ssl_certificate.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Colin Leroy <colin@colino.net> 
4  * and the Claws Mail team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  * 
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #include "claws-features.h"
24 #endif
25
26 #ifdef USE_GNUTLS
27 #include <gnutls/gnutls.h>
28 #include <gnutls/x509.h>
29 #include <gnutls/pkcs12.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #include <stdio.h>
35 #include <glib.h>
36 #include <glib/gi18n.h>
37 #include <errno.h>
38 #ifdef G_OS_WIN32
39 #  include <winsock2.h>
40 #else
41 #  include <sys/socket.h>
42 #  include <netinet/in.h>
43 #  include <netdb.h>
44 #endif /* G_OS_WIN32 */
45 #include "ssl_certificate.h"
46 #include "utils.h"
47 #include "log.h"
48 #include "socket.h"
49 #include "hooks.h"
50 #include "defs.h"
51
52 static GHashTable *warned_expired = NULL;
53
54 gboolean prefs_common_unsafe_ssl_certs(void);
55
56 static gchar *get_certificate_path(const gchar *host, const gchar *port, const gchar *fp)
57 {
58         if (fp != NULL && prefs_common_unsafe_ssl_certs())
59                 return g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
60                           "certs", G_DIR_SEPARATOR_S,
61                           host, ".", port, ".", fp, ".cert", NULL);
62         else 
63                 return g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
64                           "certs", G_DIR_SEPARATOR_S,
65                           host, ".", port, ".cert", NULL);
66 }
67
68 static gchar *get_certificate_chain_path(const gchar *host, const gchar *port, const gchar *fp)
69 {
70         gchar *tmp = get_certificate_path(host, port, fp);
71         gchar *result = g_strconcat(tmp, ".chain", NULL);
72
73         g_free(tmp);
74
75         return result;
76 }
77
78 char * readable_fingerprint(unsigned char *src, int len) 
79 {
80         int i=0;
81         char * ret;
82         
83         if (src == NULL)
84                 return NULL;
85         ret = g_strdup("");
86         while (i < len) {
87                 char *tmp2;
88                 if(i>0)
89                         tmp2 = g_strdup_printf("%s:%02X", ret, src[i]);
90                 else
91                         tmp2 = g_strdup_printf("%02X", src[i]);
92                 g_free(ret);
93                 ret = g_strdup(tmp2);
94                 g_free(tmp2);
95                 i++;
96         }
97         return ret;
98 }
99
100 #if USE_GNUTLS
101 static gnutls_x509_crt_t x509_crt_copy(gnutls_x509_crt_t src)
102 {
103     int ret;
104     size_t size;
105     gnutls_datum_t tmp;
106     gnutls_x509_crt_t dest;
107     size = 0;
108     
109     if (gnutls_x509_crt_init(&dest) != 0) {
110         g_warning("couldn't gnutls_x509_crt_init\n");
111         return NULL;
112     }
113
114     if (gnutls_x509_crt_export(src, GNUTLS_X509_FMT_DER, NULL, &size) 
115         != GNUTLS_E_SHORT_MEMORY_BUFFER) {
116         g_warning("couldn't gnutls_x509_crt_export to get size\n");
117         gnutls_x509_crt_deinit(dest);
118         return NULL;
119     }
120
121     tmp.data = malloc(size);
122     memset(tmp.data, 0, size);
123     ret = gnutls_x509_crt_export(src, GNUTLS_X509_FMT_DER, tmp.data, &size);
124     if (ret == 0) {
125         tmp.size = size;
126         ret = gnutls_x509_crt_import(dest, &tmp, GNUTLS_X509_FMT_DER);
127         if (ret) {
128                 g_warning("couldn't gnutls_x509_crt_import for real (%d %s)\n", ret, gnutls_strerror(ret));
129                 gnutls_x509_crt_deinit(dest);
130                 dest = NULL;
131         }
132     } else {
133         g_warning("couldn't gnutls_x509_crt_export for real (%d %s)\n", ret, gnutls_strerror(ret));
134         gnutls_x509_crt_deinit(dest);
135         dest = NULL;
136     }
137
138     free(tmp.data);
139     return dest;
140 }
141 #endif
142
143 static SSLCertificate *ssl_certificate_new(gnutls_x509_crt_t x509_cert, const gchar *host, gushort port)
144 {
145         SSLCertificate *cert = g_new0(SSLCertificate, 1);
146         size_t n;
147         unsigned char md[128];  
148
149         if (host == NULL || x509_cert == NULL) {
150                 ssl_certificate_destroy(cert);
151                 return NULL;
152         }
153         cert->x509_cert = x509_crt_copy(x509_cert);
154         cert->status = (guint)-1;
155         cert->host = g_strdup(host);
156         cert->port = port;
157         
158         /* fingerprint */
159         n = 128;
160         gnutls_x509_crt_get_fingerprint(cert->x509_cert, GNUTLS_DIG_MD5, md, &n);
161         cert->fingerprint = readable_fingerprint(md, (int)n);
162         return cert;
163 }
164
165 static void gnutls_export_X509_fp(FILE *fp, gnutls_x509_crt_t x509_cert, gnutls_x509_crt_fmt_t format)
166 {
167         char output[10*1024];
168         size_t cert_size = 10*1024;
169         int r;
170         
171         if ((r = gnutls_x509_crt_export(x509_cert, format, output, &cert_size)) < 0) {
172                 g_warning("couldn't export cert %s (%zd)\n", gnutls_strerror(r), cert_size);
173                 return;
174         }
175
176         debug_print("writing %zd bytes\n",cert_size);
177         if (fwrite(&output, 1, cert_size, fp) < cert_size) {
178                 g_warning("failed to write cert: %d %s\n", errno, strerror(errno));
179         }
180 }
181
182 size_t gnutls_i2d_X509(gnutls_x509_crt_t x509_cert, unsigned char **output)
183 {
184         size_t cert_size = 10*1024;
185         int r;
186         
187         if (output == NULL)
188                 return 0;
189         
190         *output = malloc(cert_size);
191
192         if ((r = gnutls_x509_crt_export(x509_cert, GNUTLS_X509_FMT_DER, *output, &cert_size)) < 0) {
193                 g_warning("couldn't export cert %s (%zd)\n", gnutls_strerror(r), cert_size);
194                 free(*output);
195                 *output = NULL;
196                 return 0;
197         }
198         return cert_size;
199 }
200
201 size_t gnutls_i2d_PrivateKey(gnutls_x509_privkey_t pkey, unsigned char **output)
202 {
203         size_t key_size = 10*1024;
204         int r;
205         
206         if (output == NULL)
207                 return 0;
208         
209         *output = malloc(key_size);
210
211         if ((r = gnutls_x509_privkey_export(pkey, GNUTLS_X509_FMT_DER, *output, &key_size)) < 0) {
212                 g_warning("couldn't export key %s (%zd)\n", gnutls_strerror(r), key_size);
213                 free(*output);
214                 *output = NULL;
215                 return 0;
216         }
217         return key_size;
218 }
219
220 static int gnutls_import_X509_list_fp(FILE *fp, gnutls_x509_crt_fmt_t format,
221                                    gnutls_x509_crt_t **cert_list, gint *num_certs)
222 {
223         gnutls_x509_crt_t *crt_list;
224         unsigned int max = 512;
225         unsigned int flags = 0;
226         gnutls_datum_t tmp;
227         struct stat s;
228         int r;
229
230         *cert_list = NULL;
231         *num_certs = 0;
232
233         if (fp == NULL)
234                 return -ENOENT;
235
236         if (fstat(fileno(fp), &s) < 0) {
237                 perror("fstat");
238                 return -errno;
239         }
240
241         crt_list=(gnutls_x509_crt_t*)malloc(max*sizeof(gnutls_x509_crt_t));
242         tmp.data = malloc(s.st_size);
243         memset(tmp.data, 0, s.st_size);
244         tmp.size = s.st_size;
245         if (fread (tmp.data, 1, s.st_size, fp) < s.st_size) {
246                 perror("fread");
247                 free(tmp.data);
248                 free(crt_list);
249                 return -EIO;
250         }
251
252         if ((r = gnutls_x509_crt_list_import(crt_list, &max, 
253                         &tmp, format, flags)) < 0) {
254                 debug_print("cert import failed: %s\n", gnutls_strerror(r));
255                 free(tmp.data);
256                 free(crt_list);
257                 return r;
258         }
259         free(tmp.data);
260         debug_print("got %d certs in crt_list! %p\n", max, &crt_list);
261
262         *cert_list = crt_list;
263         *num_certs = max;
264
265         return r;
266 }
267
268 /* return one certificate, read from file */
269 static gnutls_x509_crt_t gnutls_import_X509_fp(FILE *fp, gnutls_x509_crt_fmt_t format)
270 {
271         gnutls_x509_crt_t *certs = NULL;
272         gnutls_x509_crt_t cert = NULL;
273         int i, ncerts, r;
274
275         if ((r = gnutls_import_X509_list_fp(fp, format, &certs, &ncerts)) < 0) {
276                 return NULL;
277         }
278
279         if (ncerts == 0)
280                 return NULL;
281
282         for (i = 1; i < ncerts; i++)
283                 gnutls_x509_crt_deinit(certs[i]);
284
285         cert = certs[0];
286         free(certs);
287
288         return cert;
289 }
290
291 static gnutls_x509_privkey_t gnutls_import_key_fp(FILE *fp, gnutls_x509_crt_fmt_t format)
292 {
293         gnutls_x509_privkey_t key = NULL;
294         gnutls_datum_t tmp;
295         struct stat s;
296         int r;
297         if (fstat(fileno(fp), &s) < 0) {
298                 perror("fstat");
299                 return NULL;
300         }
301         tmp.data = malloc(s.st_size);
302         memset(tmp.data, 0, s.st_size);
303         tmp.size = s.st_size;
304         if (fread (tmp.data, 1, s.st_size, fp) < s.st_size) {
305                 perror("fread");
306                 free(tmp.data);
307                 return NULL;
308         }
309
310         gnutls_x509_privkey_init(&key);
311         if ((r = gnutls_x509_privkey_import(key, &tmp, format)) < 0) {
312                 debug_print("key import failed: %s\n", gnutls_strerror(r));
313                 gnutls_x509_privkey_deinit(key);
314                 key = NULL;
315         }
316         free(tmp.data);
317         debug_print("got key! %p\n", key);
318         return key;
319 }
320
321 static gnutls_pkcs12_t gnutls_import_PKCS12_fp(FILE *fp, gnutls_x509_crt_fmt_t format)
322 {
323         gnutls_pkcs12_t p12 = NULL;
324         gnutls_datum_t tmp;
325         struct stat s;
326         int r;
327         if (fstat(fileno(fp), &s) < 0) {
328                 log_error(LOG_PROTOCOL, _("Cannot stat P12 certificate file (%s)\n"),
329                                   strerror(errno));
330                 return NULL;
331         }
332         tmp.data = malloc(s.st_size);
333         memset(tmp.data, 0, s.st_size);
334         tmp.size = s.st_size;
335         if (fread (tmp.data, 1, s.st_size, fp) < s.st_size) {
336                 log_error(LOG_PROTOCOL, _("Cannot read P12 certificate file (%s)\n"),
337                                   strerror(errno));
338                 free(tmp.data);
339                 return NULL;
340         }
341
342         gnutls_pkcs12_init(&p12);
343
344         if ((r = gnutls_pkcs12_import(p12, &tmp, format, 0)) < 0) {
345                 log_error(LOG_PROTOCOL, _("Cannot import P12 certificate file (%s)\n"),
346                                   gnutls_strerror(r));
347                 gnutls_pkcs12_deinit(p12);
348                 p12 = NULL;
349         }
350         free(tmp.data);
351         debug_print("got p12! %p\n", p12);
352         return p12;
353 }
354
355 static void ssl_certificate_save (SSLCertificate *cert)
356 {
357         gchar *file, *port;
358         FILE *fp;
359
360         file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
361                           "certs", G_DIR_SEPARATOR_S, NULL);
362         
363         if (!is_dir_exist(file))
364                 make_dir_hier(file);
365         g_free(file);
366
367         port = g_strdup_printf("%d", cert->port);
368         file = get_certificate_path(cert->host, port, cert->fingerprint);
369
370         g_free(port);
371         fp = g_fopen(file, "wb");
372         if (fp == NULL) {
373                 g_free(file);
374                 debug_print("Can't save certificate !\n");
375                 return;
376         }
377
378         gnutls_export_X509_fp(fp, cert->x509_cert, GNUTLS_X509_FMT_DER);
379
380         g_free(file);
381         fclose(fp);
382
383 }
384
385 void ssl_certificate_destroy(SSLCertificate *cert) 
386 {
387         if (cert == NULL)
388                 return;
389
390         if (cert->x509_cert)
391                 gnutls_x509_crt_deinit(cert->x509_cert);
392         g_free(cert->host);
393         g_free(cert->fingerprint);
394         g_free(cert);
395         cert = NULL;
396 }
397
398 void ssl_certificate_delete_from_disk(SSLCertificate *cert)
399 {
400         gchar *buf;
401         gchar *file;
402         buf = g_strdup_printf("%d", cert->port);
403         file = get_certificate_path(cert->host, buf, cert->fingerprint);
404         claws_unlink (file);
405         g_free(file);
406         file = get_certificate_chain_path(cert->host, buf, cert->fingerprint);
407         claws_unlink (file);
408         g_free(file);
409         g_free(buf);
410 }
411
412 SSLCertificate *ssl_certificate_find (const gchar *host, gushort port, const gchar *fingerprint)
413 {
414         gchar *file = NULL;
415         gchar *buf;
416         SSLCertificate *cert = NULL;
417         gnutls_x509_crt_t tmp_x509;
418         FILE *fp = NULL;
419         gboolean must_rename = FALSE;
420
421         buf = g_strdup_printf("%d", port);
422         
423         if (fingerprint != NULL) {
424                 file = get_certificate_path(host, buf, fingerprint);
425                 fp = g_fopen(file, "rb");
426         }
427         if (fp == NULL) {
428                 /* see if we have the old one */
429                 debug_print("didn't get %s\n", file);
430                 g_free(file);
431                 file = get_certificate_path(host, buf, NULL);
432                 fp = g_fopen(file, "rb");
433
434                 if (fp) {
435                         debug_print("got %s\n", file);
436                         must_rename = (fingerprint != NULL);
437                 }
438         } else {
439                 debug_print("got %s first try\n", file);
440         }
441         if (fp == NULL) {
442                 g_free(file);
443                 g_free(buf);
444                 return NULL;
445         }
446         
447         if ((tmp_x509 = gnutls_import_X509_fp(fp, GNUTLS_X509_FMT_DER)) != NULL) {
448                 cert = ssl_certificate_new(tmp_x509, host, port);
449                 debug_print("got cert %p\n", cert);
450                 gnutls_x509_crt_deinit(tmp_x509);
451         }
452
453         fclose(fp);
454         g_free(file);
455         
456         if (must_rename) {
457                 gchar *old = get_certificate_path(host, buf, NULL);
458                 gchar *new = get_certificate_path(host, buf, fingerprint);
459                 if (strcmp(old, new))
460                         move_file(old, new, TRUE);
461                 g_free(old);
462                 g_free(new);
463         }
464         g_free(buf);
465
466         return cert;
467 }
468
469 static gboolean ssl_certificate_compare (SSLCertificate *cert_a, SSLCertificate *cert_b)
470 {
471         char *output_a;
472         char *output_b;
473         size_t cert_size_a = 0, cert_size_b = 0;
474         int r;
475
476         if (cert_a == NULL || cert_b == NULL)
477                 return FALSE;
478
479         if ((r = gnutls_x509_crt_export(cert_a->x509_cert, GNUTLS_X509_FMT_DER, NULL, &cert_size_a)) 
480             != GNUTLS_E_SHORT_MEMORY_BUFFER) {
481                 g_warning("couldn't gnutls_x509_crt_export to get size a %s\n", gnutls_strerror(r));
482                 return FALSE;
483         }
484
485         if ((r = gnutls_x509_crt_export(cert_b->x509_cert, GNUTLS_X509_FMT_DER, NULL, &cert_size_b))
486             != GNUTLS_E_SHORT_MEMORY_BUFFER) {
487                 g_warning("couldn't gnutls_x509_crt_export to get size b %s\n", gnutls_strerror(r));
488                 return FALSE;
489         }
490
491         output_a = g_malloc(cert_size_a);
492         output_b = g_malloc(cert_size_b);
493         if ((r = gnutls_x509_crt_export(cert_a->x509_cert, GNUTLS_X509_FMT_DER, output_a, &cert_size_a)) < 0) {
494                 g_warning("couldn't gnutls_x509_crt_export a %s\n", gnutls_strerror(r));
495                 g_free(output_a);
496                 g_free(output_b);
497                 return FALSE;
498         }
499         if ((r = gnutls_x509_crt_export(cert_b->x509_cert, GNUTLS_X509_FMT_DER, output_b, &cert_size_b)) < 0) {
500                 g_warning("couldn't gnutls_x509_crt_export b %s\n", gnutls_strerror(r));
501                 g_free(output_a);
502                 g_free(output_b);
503                 return FALSE;
504         }
505         if (cert_size_a != cert_size_b) {
506                 g_warning("size differ %zd %zd\n", cert_size_a, cert_size_b);
507                 g_free(output_a);
508                 g_free(output_b);
509                 return FALSE;
510         }
511         if (memcmp(output_a, output_b, cert_size_a)) {
512                 g_warning("contents differ\n");
513                 g_free(output_a);
514                 g_free(output_b);
515                 return FALSE;
516         }
517         g_free(output_a);
518         g_free(output_b);
519         
520         return TRUE;
521 }
522
523 static guint check_cert(SSLCertificate *cert)
524 {
525         gnutls_x509_crt_t *ca_list = NULL;
526         gnutls_x509_crt_t *chain = NULL;
527         unsigned int max_ca = 512, max_certs;
528         unsigned int flags = 0;
529         int r, i;
530         unsigned int status;
531         gchar *chain_file = NULL, *buf = NULL;
532         FILE *fp;
533
534         if (claws_ssl_get_cert_file())
535                 fp = g_fopen(claws_ssl_get_cert_file(), "r");
536         else
537                 return (guint)-1;
538
539         if ((r = gnutls_import_X509_list_fp(fp, GNUTLS_X509_FMT_PEM, &ca_list, &max_ca)) < 0) {
540                 debug_print("CA import failed: %s\n", gnutls_strerror(r));
541                 fclose(fp);
542                 return (guint)-1;
543         }
544         fclose(fp);
545         fp = NULL;
546         
547         buf = g_strdup_printf("%d", cert->port);
548         chain_file = get_certificate_chain_path(cert->host, buf, cert->fingerprint);
549         g_free(buf);
550         if (is_file_exist(chain_file)) {
551                 unsigned char md[128];
552                 size_t n;
553                 char *fingerprint;
554
555                 fp = g_fopen(chain_file, "r");
556                 if ((r = gnutls_import_X509_list_fp(fp, GNUTLS_X509_FMT_PEM, &chain, &max_certs)) < 0) {
557                         debug_print("chain import failed: %s\n", gnutls_strerror(r));
558                         fclose(fp);
559                         g_free(chain_file);
560                         return (guint)-1;
561                 }
562                 g_free(chain_file);
563                 fclose(fp);
564                 fp = NULL;
565
566                 gnutls_x509_crt_get_fingerprint(chain[0], GNUTLS_DIG_MD5, md, &n);
567                 fingerprint = readable_fingerprint(md, n);
568                 if (!fingerprint || strcmp(fingerprint, cert->fingerprint)) {
569                         debug_print("Saved chain fingerprint does not match current : %s / %s",
570                                 cert->fingerprint, fingerprint);
571                                 
572                         return (guint)-1;
573                 }
574                 g_free(fingerprint);
575
576                 r = gnutls_x509_crt_list_verify (chain,
577                                      max_certs,
578                                      ca_list, max_ca,
579                                      NULL, 0,
580                                      GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
581                                      &status);
582                 if (r < 0)
583                         debug_print("chain check failed: %s\n", gnutls_strerror(r));
584
585                 for (i = 0; i < max_certs; i++)
586                         gnutls_x509_crt_deinit(chain[i]);
587                 free(chain);
588
589         } else {
590                 r = gnutls_x509_crt_verify(cert->x509_cert, ca_list, max_ca, flags, &status);
591                 if (r < 0)
592                         debug_print("cert check failed: %s\n", gnutls_strerror(r));
593         }
594
595         for (i = 0; i < max_ca; i++)
596                 gnutls_x509_crt_deinit(ca_list[i]);
597         free(ca_list);
598
599         if (r < 0)
600                 return (guint)-1;
601         else
602                 return status;
603
604 }
605
606 char *ssl_certificate_check_signer (SSLCertificate *cert, guint status) 
607 {
608         gnutls_x509_crt_t x509_cert = cert ? cert->x509_cert : NULL;
609
610         if (!cert) 
611                 return g_strdup(_("Internal error"));
612
613         if (status == (guint)-1) {
614                 status = check_cert(cert);
615                 if (status == -1)
616                         return g_strdup(_("Uncheckable"));
617         }
618         if (status & GNUTLS_CERT_INVALID) {
619                 if (gnutls_x509_crt_check_issuer(x509_cert, x509_cert))
620                         return g_strdup(_("Self-signed certificate"));
621         }
622         if (status & GNUTLS_CERT_REVOKED)
623                 return g_strdup(_("Revoked certificate"));
624         if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
625                 return g_strdup(_("No certificate issuer found"));
626         if (status & GNUTLS_CERT_SIGNER_NOT_CA)
627                 return g_strdup(_("Certificate issuer is not a CA"));
628
629
630         return NULL;
631 }
632
633 static void ssl_certificate_save_chain(gnutls_x509_crt_t *certs, gint len, const gchar *host, gushort port)
634 {
635         gint i;
636         gchar *file = NULL;
637         FILE *fp = NULL;
638         
639         for (i = 0; i < len; i++) {
640                 size_t n;
641                 unsigned char md[128];  
642                 gnutls_x509_crt_t cert = certs[i];
643                 gchar *fingerprint;
644
645                 if (i == 0) {
646                         gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, md, &n);
647                         fingerprint = readable_fingerprint(md, n);
648                         gchar *buf = g_strdup_printf("%d", port);
649
650                         file = get_certificate_chain_path(host, buf, fingerprint);
651
652                         g_free(buf);
653
654                         fp = g_fopen(file, "wb");
655                         if (fp == NULL) {
656                                 g_free(file);
657                                 debug_print("Can't save certificate !\n");
658                                 return;
659                         }
660                         g_free(file);
661                 }
662
663                 gnutls_export_X509_fp(fp, cert, GNUTLS_X509_FMT_PEM);
664
665         }
666         if (fp)
667                 fclose(fp);
668 }
669
670 gboolean ssl_certificate_check (gnutls_x509_crt_t x509_cert, guint status, const gchar *host, gushort port)
671 {
672         SSLCertificate *current_cert = NULL;
673         SSLCertificate *known_cert;
674         SSLCertHookData cert_hook_data;
675         gchar *fingerprint;
676         size_t n;
677         unsigned char md[128];  
678
679         current_cert = ssl_certificate_new(x509_cert, host, port);
680         
681         if (current_cert == NULL) {
682                 debug_print("Buggy certificate !\n");
683                 return FALSE;
684         }
685
686         current_cert->status = status;
687         /* fingerprint */
688         n = 128;
689         gnutls_x509_crt_get_fingerprint(x509_cert, GNUTLS_DIG_MD5, md, &n);
690         fingerprint = readable_fingerprint(md, n);
691
692         known_cert = ssl_certificate_find(host, port, fingerprint);
693
694         g_free(fingerprint);
695
696         if (known_cert == NULL) {
697                 cert_hook_data.cert = current_cert;
698                 cert_hook_data.old_cert = NULL;
699                 cert_hook_data.expired = FALSE;
700                 cert_hook_data.accept = FALSE;
701                 
702                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
703                 
704                 if (!cert_hook_data.accept) {
705                         ssl_certificate_destroy(current_cert);
706                         return FALSE;
707                 } else {
708                         ssl_certificate_save(current_cert);
709                         ssl_certificate_destroy(current_cert);
710                         return TRUE;
711                 }
712         } else if (!ssl_certificate_compare (current_cert, known_cert)) {
713                 cert_hook_data.cert = current_cert;
714                 cert_hook_data.old_cert = known_cert;
715                 cert_hook_data.expired = FALSE;
716                 cert_hook_data.accept = FALSE;
717                 
718                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
719
720                 if (!cert_hook_data.accept) {
721                         ssl_certificate_destroy(current_cert);
722                         ssl_certificate_destroy(known_cert);
723                         return FALSE;
724                 } else {
725                         ssl_certificate_save(current_cert);
726                         ssl_certificate_destroy(current_cert);
727                         ssl_certificate_destroy(known_cert);
728                         return TRUE;
729                 }
730         } else if (gnutls_x509_crt_get_expiration_time(current_cert->x509_cert) < time(NULL)) {
731                 gchar *tmp = g_strdup_printf("%s:%d", current_cert->host, current_cert->port);
732                 
733                 if (warned_expired == NULL)
734                         warned_expired = g_hash_table_new(g_str_hash, g_str_equal);
735                 
736                 if (g_hash_table_lookup(warned_expired, tmp)) {
737                         g_free(tmp);
738                         ssl_certificate_destroy(current_cert);
739                         ssl_certificate_destroy(known_cert);
740                         return TRUE;
741                 }
742                         
743                 cert_hook_data.cert = current_cert;
744                 cert_hook_data.old_cert = NULL;
745                 cert_hook_data.expired = TRUE;
746                 cert_hook_data.accept = FALSE;
747                 
748                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
749
750                 if (!cert_hook_data.accept) {
751                         g_free(tmp);
752                         ssl_certificate_destroy(current_cert);
753                         ssl_certificate_destroy(known_cert);
754                         return FALSE;
755                 } else {
756                         g_hash_table_insert(warned_expired, tmp, GINT_TO_POINTER(1));
757                         ssl_certificate_destroy(current_cert);
758                         ssl_certificate_destroy(known_cert);
759                         return TRUE;
760                 }
761         }
762
763         ssl_certificate_destroy(current_cert);
764         ssl_certificate_destroy(known_cert);
765         return TRUE;
766 }
767
768 gboolean ssl_certificate_check_chain(gnutls_x509_crt_t *certs, gint chain_len, const gchar *host, gushort port)
769 {
770         int ncas = 0;
771         gnutls_x509_crt_t *cas = NULL;
772         gboolean result = FALSE;
773         int i;
774         gint status;
775
776         if (claws_ssl_get_cert_file()) {
777                 FILE *fp = g_fopen(claws_ssl_get_cert_file(), "rb");
778                 int r = -errno;
779
780                 if (fp) {
781                         r = gnutls_import_X509_list_fp(fp, GNUTLS_X509_FMT_PEM, &cas, &ncas);
782                         fclose(fp);
783                 }
784
785                 if (r < 0)
786                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
787                                 claws_ssl_get_cert_file(), 
788                                 gnutls_strerror(r));
789         } else {
790                 debug_print("Can't find SSL ca-certificates file\n");
791         }
792
793
794         gnutls_x509_crt_list_verify (certs,
795                              chain_len,
796                              cas, ncas,
797                              NULL, 0,
798                              GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
799                              &status);
800
801         result = ssl_certificate_check(certs[0], status, host, port);
802
803         if (result == TRUE) {
804                 ssl_certificate_save_chain(certs, chain_len, host, port);
805         }
806
807         for (i = 0; i < ncas; i++)
808                 gnutls_x509_crt_deinit(cas[i]);
809         free(cas);
810
811         return result;
812 }
813
814 gnutls_x509_crt_t ssl_certificate_get_x509_from_pem_file(const gchar *file)
815 {
816         gnutls_x509_crt_t x509 = NULL;
817         if (!file)
818                 return NULL;
819         
820         if (is_file_exist(file)) {
821                 FILE *fp = g_fopen(file, "r");
822                 if (fp) {
823                         x509 = gnutls_import_X509_fp(fp, GNUTLS_X509_FMT_PEM);
824                         fclose(fp);
825                         return x509;
826                 } else {
827                         log_error(LOG_PROTOCOL, _("Cannot open certificate file %s: %s\n"),
828                                   file, strerror(errno));
829                 }
830         } else {
831                 log_error(LOG_PROTOCOL, _("Certificate file %s missing (%s)\n"),
832                           file, strerror(errno));
833         }
834         return NULL;
835 }
836
837 gnutls_x509_privkey_t ssl_certificate_get_pkey_from_pem_file(const gchar *file)
838 {
839         gnutls_x509_privkey_t key = NULL;
840         if (!file)
841                 return NULL;
842         
843         if (is_file_exist(file)) {
844                 FILE *fp = g_fopen(file, "r");
845                 if (fp) {
846                         key = gnutls_import_key_fp(fp, GNUTLS_X509_FMT_PEM);
847                         fclose(fp);
848                         return key;
849                 } else {
850                         log_error(LOG_PROTOCOL, _("Cannot open key file %s (%s)\n"),
851                         file, strerror(errno));
852                 }
853         } else {
854                 log_error(LOG_PROTOCOL, _("Key file %s missing (%s)\n"), file,
855                           strerror(errno));
856         }
857         return NULL;
858 }
859
860 /* From GnuTLS lib/gnutls_x509.c */
861 static int
862 parse_pkcs12 (gnutls_pkcs12_t p12,
863               const char *password,
864               gnutls_x509_privkey_t * key,
865               gnutls_x509_crt_t * cert)
866 {
867   gnutls_pkcs12_bag_t bag = NULL;
868   int index = 0;
869   int ret;
870
871   for (;;)
872     {
873       int elements_in_bag;
874       int i;
875
876       ret = gnutls_pkcs12_bag_init (&bag);
877       if (ret < 0)
878         {
879           bag = NULL;
880           goto done;
881         }
882
883       ret = gnutls_pkcs12_get_bag (p12, index, bag);
884       if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
885         break;
886       if (ret < 0)
887         {
888           goto done;
889         }
890
891       ret = gnutls_pkcs12_bag_get_type (bag, 0);
892       if (ret < 0)
893         {
894           goto done;
895         }
896
897       if (ret == GNUTLS_BAG_ENCRYPTED)
898         {
899           ret = gnutls_pkcs12_bag_decrypt (bag, password);
900           if (ret < 0)
901             {
902               goto done;
903             }
904         }
905
906       elements_in_bag = gnutls_pkcs12_bag_get_count (bag);
907       if (elements_in_bag < 0)
908         {
909           goto done;
910         }
911
912       for (i = 0; i < elements_in_bag; i++)
913         {
914           int type;
915           gnutls_datum_t data;
916
917           type = gnutls_pkcs12_bag_get_type (bag, i);
918           if (type < 0)
919             {
920               goto done;
921             }
922
923           ret = gnutls_pkcs12_bag_get_data (bag, i, &data);
924           if (ret < 0)
925             {
926               goto done;
927             }
928
929           switch (type)
930             {
931             case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY:
932             case GNUTLS_BAG_PKCS8_KEY:
933               ret = gnutls_x509_privkey_init (key);
934               if (ret < 0)
935                 {
936                   goto done;
937                 }
938
939               ret = gnutls_x509_privkey_import_pkcs8
940                 (*key, &data, GNUTLS_X509_FMT_DER, password,
941                  type == GNUTLS_BAG_PKCS8_KEY ? GNUTLS_PKCS_PLAIN : 0);
942               if (ret < 0)
943                 {
944                   goto done;
945                 }
946               break;
947
948             case GNUTLS_BAG_CERTIFICATE:
949               ret = gnutls_x509_crt_init (cert);
950               if (ret < 0)
951                 {
952                   goto done;
953                 }
954
955               ret =
956                 gnutls_x509_crt_import (*cert, &data, GNUTLS_X509_FMT_DER);
957               if (ret < 0)
958                 {
959                   goto done;
960                 }
961               break;
962
963             case GNUTLS_BAG_ENCRYPTED:
964               /* XXX Bother to recurse one level down?  Unlikely to
965                  use the same password anyway. */
966             case GNUTLS_BAG_EMPTY:
967             default:
968               break;
969             }
970         }
971
972       index++;
973       gnutls_pkcs12_bag_deinit (bag);
974     }
975
976   ret = 0;
977
978 done:
979   if (bag)
980     gnutls_pkcs12_bag_deinit (bag);
981
982   return ret;
983 }
984 void ssl_certificate_get_x509_and_pkey_from_p12_file(const gchar *file, const gchar *password,
985                         gnutls_x509_crt_t *x509, gnutls_x509_privkey_t *pkey)
986 {
987         gnutls_pkcs12_t p12 = NULL;
988
989         int r;
990
991         *x509 = NULL;
992         *pkey = NULL;
993         if (!file)
994                 return;
995
996         if (is_file_exist(file)) {
997                 FILE *fp = g_fopen(file, "r");
998                 if (fp) {
999                         p12 = gnutls_import_PKCS12_fp(fp, GNUTLS_X509_FMT_DER);
1000                         fclose(fp);
1001                         if (!p12) {
1002                                 log_error(LOG_PROTOCOL, _("Failed to read P12 certificate file %s\n"), file);
1003                         }
1004                 } else {
1005                         log_error(LOG_PROTOCOL, _("Cannot open P12 certificate file %s (%s)\n"),
1006                                   file, strerror(errno));
1007                 }
1008         } else {
1009                 log_error(LOG_PROTOCOL, _("P12 Certificate file %s missing (%s)\n"), file,
1010                           strerror(errno));
1011         }
1012         if (p12 != NULL) {
1013                 if ((r = parse_pkcs12(p12, password, pkey, x509)) == 0) {
1014                         debug_print("got p12\n");
1015                 } else {
1016                         log_error(LOG_PROTOCOL, "%s\n", gnutls_strerror(r));
1017                 }
1018                 gnutls_pkcs12_deinit(p12);
1019         }
1020 }
1021
1022 gboolean ssl_certificate_check_subject_cn(SSLCertificate *cert)
1023 {
1024         return gnutls_x509_crt_check_hostname(cert->x509_cert, cert->host) != 0;
1025 }
1026
1027 gchar *ssl_certificate_get_subject_cn(SSLCertificate *cert)
1028 {
1029         gchar subject_cn[BUFFSIZE];
1030         size_t n = BUFFSIZE;
1031
1032         if(gnutls_x509_crt_get_dn_by_oid(cert->x509_cert, 
1033                 GNUTLS_OID_X520_COMMON_NAME, 0, 0, subject_cn, &n))
1034                 strncpy(subject_cn, _("<not in certificate>"), BUFFSIZE);
1035
1036         return g_strdup(subject_cn);
1037 }
1038
1039 #endif /* USE_GNUTLS */