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