Fix Coverity issues in common
[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 = sizeof(md);
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 (fp == NULL) {
557                         debug_print("fopen %s failed: %s\n", chain_file, strerror(errno));
558                         g_free(chain_file);
559                         return (guint)-1;
560                 }
561                 if ((r = gnutls_import_X509_list_fp(fp, GNUTLS_X509_FMT_PEM, &chain, &max_certs)) < 0) {
562                         debug_print("chain import failed: %s\n", gnutls_strerror(r));
563                         fclose(fp);
564                         g_free(chain_file);
565                         return (guint)-1;
566                 }
567                 g_free(chain_file);
568                 fclose(fp);
569                 fp = NULL;
570
571                 gnutls_x509_crt_get_fingerprint(chain[0], GNUTLS_DIG_MD5, md, &n);
572                 fingerprint = readable_fingerprint(md, n);
573                 if (!fingerprint || strcmp(fingerprint, cert->fingerprint)) {
574                         debug_print("Saved chain fingerprint does not match current : %s / %s",
575                                 cert->fingerprint, fingerprint);
576                                 
577                         return (guint)-1;
578                 }
579                 g_free(fingerprint);
580
581                 r = gnutls_x509_crt_list_verify (chain,
582                                      max_certs,
583                                      ca_list, max_ca,
584                                      NULL, 0,
585                                      GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
586                                      &status);
587                 if (r < 0)
588                         debug_print("chain check failed: %s\n", gnutls_strerror(r));
589
590                 for (i = 0; i < max_certs; i++)
591                         gnutls_x509_crt_deinit(chain[i]);
592                 free(chain);
593
594         } else {
595                 r = gnutls_x509_crt_verify(cert->x509_cert, ca_list, max_ca, flags, &status);
596                 if (r < 0)
597                         debug_print("cert check failed: %s\n", gnutls_strerror(r));
598         }
599
600         for (i = 0; i < max_ca; i++)
601                 gnutls_x509_crt_deinit(ca_list[i]);
602         free(ca_list);
603
604         if (r < 0)
605                 return (guint)-1;
606         else
607                 return status;
608
609 }
610
611 static gboolean ssl_certificate_is_valid(SSLCertificate *cert, guint status)
612 {
613         gchar *str_status = ssl_certificate_check_signer(cert, status);
614
615         if (str_status != NULL) {
616                 g_free(str_status);
617                 return FALSE;
618         }
619         return ssl_certificate_check_subject_cn(cert);
620 }
621
622 char *ssl_certificate_check_signer (SSLCertificate *cert, guint status) 
623 {
624         gnutls_x509_crt_t x509_cert = cert ? cert->x509_cert : NULL;
625
626         if (!cert) 
627                 return g_strdup(_("Internal error"));
628
629         if (status == (guint)-1) {
630                 status = check_cert(cert);
631                 if (status == -1)
632                         return g_strdup(_("Uncheckable"));
633         }
634         if (status & GNUTLS_CERT_INVALID) {
635                 if (gnutls_x509_crt_check_issuer(x509_cert, x509_cert))
636                         return g_strdup(_("Self-signed certificate"));
637         }
638         if (status & GNUTLS_CERT_REVOKED)
639                 return g_strdup(_("Revoked certificate"));
640         if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
641                 return g_strdup(_("No certificate issuer found"));
642         if (status & GNUTLS_CERT_SIGNER_NOT_CA)
643                 return g_strdup(_("Certificate issuer is not a CA"));
644
645
646         return NULL;
647 }
648
649 static void ssl_certificate_save_chain(gnutls_x509_crt_t *certs, gint len, const gchar *host, gushort port)
650 {
651         gint i;
652         gchar *file = NULL;
653         FILE *fp = NULL;
654         
655         for (i = 0; i < len; i++) {
656                 size_t n;
657                 unsigned char md[128];  
658                 gnutls_x509_crt_t cert = certs[i];
659                 gchar *fingerprint;
660
661                 if (i == 0) {
662                         n = sizeof(md);
663                         gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_MD5, md, &n);
664                         fingerprint = readable_fingerprint(md, n);
665                         gchar *buf = g_strdup_printf("%d", port);
666
667                         file = get_certificate_chain_path(host, buf, fingerprint);
668
669                         g_free(buf);
670
671                         fp = g_fopen(file, "wb");
672                         if (fp == NULL) {
673                                 g_free(file);
674                                 debug_print("Can't save certificate !\n");
675                                 return;
676                         }
677                         g_free(file);
678                 }
679
680                 gnutls_export_X509_fp(fp, cert, GNUTLS_X509_FMT_PEM);
681
682         }
683         if (fp)
684                 fclose(fp);
685 }
686
687 gboolean ssl_certificate_check (gnutls_x509_crt_t x509_cert, guint status, 
688                                 const gchar *host, gushort port,
689                                 gboolean accept_if_valid)
690 {
691         SSLCertificate *current_cert = NULL;
692         SSLCertificate *known_cert;
693         SSLCertHookData cert_hook_data;
694         gchar *fingerprint;
695         size_t n;
696         unsigned char md[128];
697         gboolean valid = FALSE;
698
699         current_cert = ssl_certificate_new(x509_cert, host, port);
700
701         if (current_cert == NULL) {
702                 debug_print("Buggy certificate !\n");
703                 return FALSE;
704         }
705
706         current_cert->status = status;
707         /* fingerprint */
708         n = sizeof(md);
709         gnutls_x509_crt_get_fingerprint(x509_cert, GNUTLS_DIG_MD5, md, &n);
710         fingerprint = readable_fingerprint(md, n);
711
712         known_cert = ssl_certificate_find(host, port, fingerprint);
713
714         g_free(fingerprint);
715
716         if (accept_if_valid)
717                 valid = ssl_certificate_is_valid(current_cert, status);
718         else
719                 valid = FALSE; /* Force check */
720
721         if (known_cert == NULL) {
722                 if (valid) {
723                         ssl_certificate_save(current_cert);
724                         ssl_certificate_destroy(current_cert);
725                         return TRUE;
726                 }
727
728                 cert_hook_data.cert = current_cert;
729                 cert_hook_data.old_cert = NULL;
730                 cert_hook_data.expired = FALSE;
731                 cert_hook_data.accept = FALSE;
732
733                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
734
735                 if (!cert_hook_data.accept) {
736                         ssl_certificate_destroy(current_cert);
737                         return FALSE;
738                 } else {
739                         ssl_certificate_save(current_cert);
740                         ssl_certificate_destroy(current_cert);
741                         return TRUE;
742                 }
743         } else if (!ssl_certificate_compare (current_cert, known_cert)) {
744                 if (valid) {
745                         ssl_certificate_save(current_cert);
746                         ssl_certificate_destroy(current_cert);
747                         ssl_certificate_destroy(known_cert);
748                         return TRUE;
749                 }
750
751                 cert_hook_data.cert = current_cert;
752                 cert_hook_data.old_cert = known_cert;
753                 cert_hook_data.expired = FALSE;
754                 cert_hook_data.accept = FALSE;
755
756                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
757
758                 if (!cert_hook_data.accept) {
759                         ssl_certificate_destroy(current_cert);
760                         ssl_certificate_destroy(known_cert);
761                         return FALSE;
762                 } else {
763                         ssl_certificate_save(current_cert);
764                         ssl_certificate_destroy(current_cert);
765                         ssl_certificate_destroy(known_cert);
766                         return TRUE;
767                 }
768         } else if (gnutls_x509_crt_get_expiration_time(current_cert->x509_cert) < time(NULL)) {
769                 gchar *tmp = g_strdup_printf("%s:%d", current_cert->host, current_cert->port);
770
771                 if (warned_expired == NULL)
772                         warned_expired = g_hash_table_new(g_str_hash, g_str_equal);
773
774                 if (g_hash_table_lookup(warned_expired, tmp)) {
775                         g_free(tmp);
776                         ssl_certificate_destroy(current_cert);
777                         ssl_certificate_destroy(known_cert);
778                         return TRUE;
779                 }
780
781                 cert_hook_data.cert = current_cert;
782                 cert_hook_data.old_cert = NULL;
783                 cert_hook_data.expired = TRUE;
784                 cert_hook_data.accept = FALSE;
785
786                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
787
788                 if (!cert_hook_data.accept) {
789                         g_free(tmp);
790                         ssl_certificate_destroy(current_cert);
791                         ssl_certificate_destroy(known_cert);
792                         return FALSE;
793                 } else {
794                         g_hash_table_insert(warned_expired, tmp, GINT_TO_POINTER(1));
795                         ssl_certificate_destroy(current_cert);
796                         ssl_certificate_destroy(known_cert);
797                         return TRUE;
798                 }
799         }
800
801         ssl_certificate_destroy(current_cert);
802         ssl_certificate_destroy(known_cert);
803         return TRUE;
804 }
805
806 gboolean ssl_certificate_check_chain(gnutls_x509_crt_t *certs, gint chain_len,
807                                      const gchar *host, gushort port,
808                                      gboolean accept_if_valid)
809 {
810         int ncas = 0;
811         gnutls_x509_crt_t *cas = NULL;
812         gboolean result = FALSE;
813         int i;
814         gint status;
815
816         if (claws_ssl_get_cert_file()) {
817                 FILE *fp = g_fopen(claws_ssl_get_cert_file(), "rb");
818                 int r = -errno;
819
820                 if (fp) {
821                         r = gnutls_import_X509_list_fp(fp, GNUTLS_X509_FMT_PEM, &cas, &ncas);
822                         fclose(fp);
823                 }
824
825                 if (r < 0)
826                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
827                                 claws_ssl_get_cert_file(), 
828                                 gnutls_strerror(r));
829         } else {
830                 debug_print("Can't find SSL ca-certificates file\n");
831         }
832
833
834         gnutls_x509_crt_list_verify (certs,
835                              chain_len,
836                              cas, ncas,
837                              NULL, 0,
838                              GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
839                              &status);
840
841         result = ssl_certificate_check(certs[0], status, host, port,
842                                         accept_if_valid);
843
844         if (result == TRUE) {
845                 ssl_certificate_save_chain(certs, chain_len, host, port);
846         }
847
848         for (i = 0; i < ncas; i++)
849                 gnutls_x509_crt_deinit(cas[i]);
850         free(cas);
851
852         return result;
853 }
854
855 gnutls_x509_crt_t ssl_certificate_get_x509_from_pem_file(const gchar *file)
856 {
857         gnutls_x509_crt_t x509 = NULL;
858         if (!file)
859                 return NULL;
860         
861         if (is_file_exist(file)) {
862                 FILE *fp = g_fopen(file, "r");
863                 if (fp) {
864                         x509 = gnutls_import_X509_fp(fp, GNUTLS_X509_FMT_PEM);
865                         fclose(fp);
866                         return x509;
867                 } else {
868                         log_error(LOG_PROTOCOL, _("Cannot open certificate file %s: %s\n"),
869                                   file, strerror(errno));
870                 }
871         } else {
872                 log_error(LOG_PROTOCOL, _("Certificate file %s missing (%s)\n"),
873                           file, strerror(errno));
874         }
875         return NULL;
876 }
877
878 gnutls_x509_privkey_t ssl_certificate_get_pkey_from_pem_file(const gchar *file)
879 {
880         gnutls_x509_privkey_t key = NULL;
881         if (!file)
882                 return NULL;
883         
884         if (is_file_exist(file)) {
885                 FILE *fp = g_fopen(file, "r");
886                 if (fp) {
887                         key = gnutls_import_key_fp(fp, GNUTLS_X509_FMT_PEM);
888                         fclose(fp);
889                         return key;
890                 } else {
891                         log_error(LOG_PROTOCOL, _("Cannot open key file %s (%s)\n"),
892                         file, strerror(errno));
893                 }
894         } else {
895                 log_error(LOG_PROTOCOL, _("Key file %s missing (%s)\n"), file,
896                           strerror(errno));
897         }
898         return NULL;
899 }
900
901 /* From GnuTLS lib/gnutls_x509.c */
902 static int
903 parse_pkcs12 (gnutls_pkcs12_t p12,
904               const char *password,
905               gnutls_x509_privkey_t * key,
906               gnutls_x509_crt_t * cert)
907 {
908   gnutls_pkcs12_bag_t bag = NULL;
909   int index = 0;
910   int ret;
911
912   for (;;)
913     {
914       int elements_in_bag;
915       int i;
916
917       ret = gnutls_pkcs12_bag_init (&bag);
918       if (ret < 0)
919         {
920           bag = NULL;
921           goto done;
922         }
923
924       ret = gnutls_pkcs12_get_bag (p12, index, bag);
925       if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
926         break;
927       if (ret < 0)
928         {
929           goto done;
930         }
931
932       ret = gnutls_pkcs12_bag_get_type (bag, 0);
933       if (ret < 0)
934         {
935           goto done;
936         }
937
938       if (ret == GNUTLS_BAG_ENCRYPTED)
939         {
940           ret = gnutls_pkcs12_bag_decrypt (bag, password);
941           if (ret < 0)
942             {
943               goto done;
944             }
945         }
946
947       elements_in_bag = gnutls_pkcs12_bag_get_count (bag);
948       if (elements_in_bag < 0)
949         {
950           goto done;
951         }
952
953       for (i = 0; i < elements_in_bag; i++)
954         {
955           int type;
956           gnutls_datum_t data;
957
958           type = gnutls_pkcs12_bag_get_type (bag, i);
959           if (type < 0)
960             {
961               goto done;
962             }
963
964           ret = gnutls_pkcs12_bag_get_data (bag, i, &data);
965           if (ret < 0)
966             {
967               goto done;
968             }
969
970           switch (type)
971             {
972             case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY:
973             case GNUTLS_BAG_PKCS8_KEY:
974               ret = gnutls_x509_privkey_init (key);
975               if (ret < 0)
976                 {
977                   goto done;
978                 }
979
980               ret = gnutls_x509_privkey_import_pkcs8
981                 (*key, &data, GNUTLS_X509_FMT_DER, password,
982                  type == GNUTLS_BAG_PKCS8_KEY ? GNUTLS_PKCS_PLAIN : 0);
983               if (ret < 0)
984                 {
985                   goto done;
986                 }
987               break;
988
989             case GNUTLS_BAG_CERTIFICATE:
990               ret = gnutls_x509_crt_init (cert);
991               if (ret < 0)
992                 {
993                   goto done;
994                 }
995
996               ret =
997                 gnutls_x509_crt_import (*cert, &data, GNUTLS_X509_FMT_DER);
998               if (ret < 0)
999                 {
1000                   goto done;
1001                 }
1002               break;
1003
1004             case GNUTLS_BAG_ENCRYPTED:
1005               /* XXX Bother to recurse one level down?  Unlikely to
1006                  use the same password anyway. */
1007             case GNUTLS_BAG_EMPTY:
1008             default:
1009               break;
1010             }
1011         }
1012
1013       index++;
1014       gnutls_pkcs12_bag_deinit (bag);
1015     }
1016
1017   ret = 0;
1018
1019 done:
1020   if (bag)
1021     gnutls_pkcs12_bag_deinit (bag);
1022
1023   return ret;
1024 }
1025 void ssl_certificate_get_x509_and_pkey_from_p12_file(const gchar *file, const gchar *password,
1026                         gnutls_x509_crt_t *x509, gnutls_x509_privkey_t *pkey)
1027 {
1028         gnutls_pkcs12_t p12 = NULL;
1029
1030         int r;
1031
1032         *x509 = NULL;
1033         *pkey = NULL;
1034         if (!file)
1035                 return;
1036
1037         if (is_file_exist(file)) {
1038                 FILE *fp = g_fopen(file, "r");
1039                 if (fp) {
1040                         p12 = gnutls_import_PKCS12_fp(fp, GNUTLS_X509_FMT_DER);
1041                         fclose(fp);
1042                         if (!p12) {
1043                                 log_error(LOG_PROTOCOL, _("Failed to read P12 certificate file %s\n"), file);
1044                         }
1045                 } else {
1046                         log_error(LOG_PROTOCOL, _("Cannot open P12 certificate file %s (%s)\n"),
1047                                   file, strerror(errno));
1048                 }
1049         } else {
1050                 log_error(LOG_PROTOCOL, _("P12 Certificate file %s missing (%s)\n"), file,
1051                           strerror(errno));
1052         }
1053         if (p12 != NULL) {
1054                 if ((r = parse_pkcs12(p12, password, pkey, x509)) == 0) {
1055                         debug_print("got p12\n");
1056                 } else {
1057                         log_error(LOG_PROTOCOL, "%s\n", gnutls_strerror(r));
1058                 }
1059                 gnutls_pkcs12_deinit(p12);
1060         }
1061 }
1062
1063 gboolean ssl_certificate_check_subject_cn(SSLCertificate *cert)
1064 {
1065         return gnutls_x509_crt_check_hostname(cert->x509_cert, cert->host) != 0;
1066 }
1067
1068 gchar *ssl_certificate_get_subject_cn(SSLCertificate *cert)
1069 {
1070         gchar subject_cn[BUFFSIZE];
1071         size_t n = BUFFSIZE;
1072
1073         if(gnutls_x509_crt_get_dn_by_oid(cert->x509_cert, 
1074                 GNUTLS_OID_X520_COMMON_NAME, 0, 0, subject_cn, &n))
1075                 return g_strdup(_("<not in certificate>"));
1076
1077         return g_strdup(subject_cn);
1078 }
1079
1080 #endif /* USE_GNUTLS */