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