00b7fd658d3e9201b504da36408b39cdb30ee257
[claws.git] / src / common / ssl_certificate.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 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 #endif
24
25 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
26 #if USE_OPENSSL
27 #include <openssl/ssl.h>
28 #else
29 #include <gnutls/gnutls.h>
30 #include <gnutls/x509.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <string.h>
36 #endif
37 #include <glib.h>
38 #include <glib/gi18n.h>
39
40 #ifdef G_OS_WIN32
41 #include "winsock2.h"
42 #endif
43 #include "ssl_certificate.h"
44 #include "utils.h"
45 #include "log.h"
46 #include "socket.h"
47 #include "hooks.h"
48 #include "defs.h"
49
50 static GHashTable *warned_expired = NULL;
51
52 gboolean prefs_common_unsafe_ssl_certs(void);
53
54 static gchar *get_certificate_path(const gchar *host, const gchar *port, const gchar *fp)
55 {
56         if (fp != NULL && prefs_common_unsafe_ssl_certs())
57                 return g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
58                           "certs", G_DIR_SEPARATOR_S,
59                           host, ".", port, ".", fp, ".cert", NULL);
60         else 
61                 return g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
62                           "certs", G_DIR_SEPARATOR_S,
63                           host, ".", port, ".cert", NULL);
64 }
65
66 #if USE_OPENSSL
67 static SSLCertificate *ssl_certificate_new_lookup(X509 *x509_cert, gchar *host, gushort port, gboolean lookup);
68 #else
69 static SSLCertificate *ssl_certificate_new_lookup(gnutls_x509_crt x509_cert, gchar *host, gushort port, gboolean lookup);
70 #endif
71 #if USE_OPENSSL
72 /* from Courier */
73 time_t asn1toTime(ASN1_TIME *asn1Time)
74 {
75         struct tm tm;
76         int offset;
77
78         if (asn1Time == NULL || asn1Time->length < 13)
79                 return 0;
80
81         memset(&tm, 0, sizeof(tm));
82
83 #define N2(n)   ((asn1Time->data[n]-'0')*10 + asn1Time->data[(n)+1]-'0')
84
85 #define CPY(f,n) (tm.f=N2(n))
86
87         CPY(tm_year,0);
88
89         if(tm.tm_year < 50)
90                 tm.tm_year += 100; /* Sux */
91
92         CPY(tm_mon, 2);
93         --tm.tm_mon;
94         CPY(tm_mday, 4);
95         CPY(tm_hour, 6);
96         CPY(tm_min, 8);
97         CPY(tm_sec, 10);
98
99         offset=0;
100
101         if (asn1Time->data[12] != 'Z')
102         {
103                 if (asn1Time->length < 17)
104                         return 0;
105
106                 offset=N2(13)*3600+N2(15)*60;
107
108                 if (asn1Time->data[12] == '-')
109                         offset= -offset;
110         }
111
112 #undef N2
113 #undef CPY
114
115         return mktime(&tm)-offset;
116 }
117 #endif
118
119 static char * get_fqdn(char *host)
120 {
121 #ifdef INET6
122         gint gai_err;
123         struct addrinfo hints, *res;
124 #else
125         struct hostent *hp;
126 #endif
127
128         if (host == NULL || strlen(host) == 0)
129                 return g_strdup("");
130 #ifdef INET6
131         memset(&hints, 0, sizeof(hints));
132         hints.ai_flags = AI_CANONNAME;
133         hints.ai_family = AF_UNSPEC;
134         hints.ai_socktype = SOCK_STREAM;
135         hints.ai_protocol = IPPROTO_TCP;
136
137         gai_err = getaddrinfo(host, NULL, &hints, &res);
138         if (gai_err != 0) {
139                 g_warning("getaddrinfo for %s failed: %s\n",
140                           host, gai_strerror(gai_err));
141                 return g_strdup(host);
142         }
143         if (res != NULL) {
144                 if (res->ai_canonname && strlen(res->ai_canonname)) {
145                         gchar *fqdn = g_strdup(res->ai_canonname);
146                         freeaddrinfo(res);
147                         return fqdn;
148                 } else {
149                         freeaddrinfo(res);
150                         return g_strdup(host);
151                 }
152         } else {
153                 return g_strdup(host);
154         }
155 #else
156         hp = my_gethostbyname(host);
157         if (hp == NULL)
158                 return g_strdup(host); /*caller should free*/
159         else 
160                 return g_strdup(hp->h_name);
161 #endif
162 }
163
164 char * readable_fingerprint(unsigned char *src, int len) 
165 {
166         int i=0;
167         char * ret;
168         
169         if (src == NULL)
170                 return NULL;
171         ret = g_strdup("");
172         while (i < len) {
173                 char *tmp2;
174                 if(i>0)
175                         tmp2 = g_strdup_printf("%s:%02X", ret, src[i]);
176                 else
177                         tmp2 = g_strdup_printf("%02X", src[i]);
178                 g_free(ret);
179                 ret = g_strdup(tmp2);
180                 g_free(tmp2);
181                 i++;
182         }
183         return ret;
184 }
185
186 #if USE_GNUTLS
187 static gnutls_x509_crt x509_crt_copy(gnutls_x509_crt src)
188 {
189     int ret;
190     size_t size;
191     gnutls_datum tmp;
192     gnutls_x509_crt dest;
193     
194     if (gnutls_x509_crt_init(&dest) != 0) {
195         g_warning("couldn't gnutls_x509_crt_init\n");
196         return NULL;
197     }
198
199     if (gnutls_x509_crt_export(src, GNUTLS_X509_FMT_DER, NULL, &size) 
200         != GNUTLS_E_SHORT_MEMORY_BUFFER) {
201         g_warning("couldn't gnutls_x509_crt_export to get size\n");
202         gnutls_x509_crt_deinit(dest);
203         return NULL;
204     }
205
206     tmp.data = malloc(size);
207     memset(tmp.data, 0, size);
208     ret = gnutls_x509_crt_export(src, GNUTLS_X509_FMT_DER, tmp.data, &size);
209     if (ret == 0) {
210         tmp.size = size;
211         ret = gnutls_x509_crt_import(dest, &tmp, GNUTLS_X509_FMT_DER);
212         if (ret) {
213                 g_warning("couldn't gnutls_x509_crt_import for real (%d %s)\n", ret, gnutls_strerror(ret));
214                 gnutls_x509_crt_deinit(dest);
215                 dest = NULL;
216         }
217     } else {
218         g_warning("couldn't gnutls_x509_crt_export for real (%d %s)\n", ret, gnutls_strerror(ret));
219         gnutls_x509_crt_deinit(dest);
220         dest = NULL;
221     }
222
223     free(tmp.data);
224     return dest;
225 }
226 #endif
227
228 #if USE_OPENSSL
229 static SSLCertificate *ssl_certificate_new_lookup(X509 *x509_cert, gchar *host, gushort port, gboolean lookup)
230 #else
231 static SSLCertificate *ssl_certificate_new_lookup(gnutls_x509_crt x509_cert, gchar *host, gushort port, gboolean lookup)
232 #endif
233 {
234         SSLCertificate *cert = g_new0(SSLCertificate, 1);
235         unsigned int n;
236         unsigned char md[128];  
237
238         if (host == NULL || x509_cert == NULL) {
239                 ssl_certificate_destroy(cert);
240                 return NULL;
241         }
242 #if USE_OPENSSL
243         cert->x509_cert = X509_dup(x509_cert);
244 #else
245         cert->x509_cert = x509_crt_copy(x509_cert);
246         cert->status = (guint)-1;
247 #endif
248         if (lookup)
249                 cert->host = get_fqdn(host);
250         else
251                 cert->host = g_strdup(host);
252         cert->port = port;
253         
254         /* fingerprint */
255 #if USE_OPENSSL
256         X509_digest(cert->x509_cert, EVP_md5(), md, &n);
257         cert->fingerprint = readable_fingerprint(md, (int)n);
258 #else
259         gnutls_x509_crt_get_fingerprint(cert->x509_cert, GNUTLS_DIG_MD5, md, &n);
260         cert->fingerprint = readable_fingerprint(md, (int)n);
261 #endif
262         return cert;
263 }
264
265 #ifdef USE_GNUTLS
266 static void i2d_X509_fp(FILE *fp, gnutls_x509_crt x509_cert)
267 {
268         char output[10*1024];
269         size_t cert_size = 10*1024;
270         int r;
271         
272         if ((r = gnutls_x509_crt_export(x509_cert, GNUTLS_X509_FMT_DER, output, &cert_size)) < 0) {
273                 g_warning("couldn't export cert %s (%d)\n", gnutls_strerror(r), cert_size);
274                 return;
275         }
276         debug_print("writing %zd bytes\n",cert_size);
277         if (fwrite(&output, 1, cert_size, fp) < cert_size) {
278                 g_warning("failed to write cert\n");
279         }
280 }
281 static gnutls_x509_crt d2i_X509_fp(FILE *fp, int unused)
282 {
283         gnutls_x509_crt cert = NULL;
284         gnutls_datum tmp;
285         struct stat s;
286         int r;
287         if (fstat(fileno(fp), &s) < 0) {
288                 perror("fstat");
289                 return NULL;
290         }
291         tmp.data = malloc(s.st_size);
292         memset(tmp.data, 0, s.st_size);
293         tmp.size = s.st_size;
294         if (fread (tmp.data, 1, s.st_size, fp) < s.st_size) {
295                 perror("fread");
296                 return NULL;
297         }
298
299         gnutls_x509_crt_init(&cert);
300         if ((r = gnutls_x509_crt_import(cert, &tmp, GNUTLS_X509_FMT_DER)) < 0) {
301                 g_warning("import failed: %s\n", gnutls_strerror(r));
302                 gnutls_x509_crt_deinit(cert);
303                 cert = NULL;
304         }
305         debug_print("got cert! %p\n", cert);
306         return cert;
307 }
308 #endif
309
310 static void ssl_certificate_save (SSLCertificate *cert)
311 {
312         gchar *file, *port;
313         FILE *fp;
314
315         file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, 
316                           "certs", G_DIR_SEPARATOR_S, NULL);
317         
318         if (!is_dir_exist(file))
319                 make_dir_hier(file);
320         g_free(file);
321
322         port = g_strdup_printf("%d", cert->port);
323         file = get_certificate_path(cert->host, port, cert->fingerprint);
324
325         g_free(port);
326         fp = g_fopen(file, "wb");
327         if (fp == NULL) {
328                 g_free(file);
329                 debug_print("Can't save certificate !\n");
330                 return;
331         }
332         i2d_X509_fp(fp, cert->x509_cert);
333         g_free(file);
334         fclose(fp);
335
336 }
337
338 void ssl_certificate_destroy(SSLCertificate *cert) 
339 {
340         if (cert == NULL)
341                 return;
342
343         if (cert->x509_cert)
344 #if USE_OPENSSL
345                 X509_free(cert->x509_cert);
346 #else
347                 gnutls_x509_crt_deinit(cert->x509_cert);
348 #endif
349         g_free(cert->host);
350         g_free(cert->fingerprint);
351         g_free(cert);
352         cert = NULL;
353 }
354
355 void ssl_certificate_delete_from_disk(SSLCertificate *cert)
356 {
357         gchar *buf;
358         gchar *file;
359         buf = g_strdup_printf("%d", cert->port);
360         file = get_certificate_path(cert->host, buf, cert->fingerprint);
361         g_unlink (file);
362         g_free(file);
363         g_free(buf);
364 }
365
366 SSLCertificate *ssl_certificate_find (gchar *host, gushort port, const gchar *fingerprint)
367 {
368         return ssl_certificate_find_lookup (host, port, fingerprint, TRUE);
369 }
370
371 SSLCertificate *ssl_certificate_find_lookup (gchar *host, gushort port, const gchar *fingerprint, gboolean lookup)
372 {
373         gchar *file = NULL;
374         gchar *buf;
375         gchar *fqdn_host;
376         SSLCertificate *cert = NULL;
377 #if USE_OPENSSL
378         X509 *tmp_x509;
379 #else
380         gnutls_x509_crt tmp_x509;
381 #endif
382         FILE *fp = NULL;
383         gboolean must_rename = FALSE;
384
385         if (lookup)
386                 fqdn_host = get_fqdn(host);
387         else
388                 fqdn_host = g_strdup(host);
389
390         buf = g_strdup_printf("%d", port);
391         
392         if (fingerprint != NULL) {
393                 file = get_certificate_path(fqdn_host, buf, fingerprint);
394                 fp = g_fopen(file, "rb");
395         }
396         if (fp == NULL) {
397                 /* see if we have the old one */
398                 debug_print("didn't get %s\n", file);
399                 g_free(file);
400                 file = get_certificate_path(fqdn_host, buf, NULL);
401                 fp = g_fopen(file, "rb");
402
403                 if (fp) {
404                         debug_print("got %s\n", file);
405                         must_rename = (fingerprint != NULL);
406                 }
407         } else {
408                 debug_print("got %s first try\n", file);
409         }
410         if (fp == NULL) {
411                 g_free(file);
412                 g_free(fqdn_host);
413                 g_free(buf);
414                 return NULL;
415         }
416         
417         if ((tmp_x509 = d2i_X509_fp(fp, 0)) != NULL) {
418                 cert = ssl_certificate_new_lookup(tmp_x509, fqdn_host, port, lookup);
419                 debug_print("got cert %p\n", cert);
420 #if USE_OPENSSL
421                 X509_free(tmp_x509);
422 #else
423                 gnutls_x509_crt_deinit(tmp_x509);
424 #endif
425         }
426         fclose(fp);
427         g_free(file);
428         
429         if (must_rename) {
430                 gchar *old = get_certificate_path(fqdn_host, buf, NULL);
431                 gchar *new = get_certificate_path(fqdn_host, buf, fingerprint);
432                 if (strcmp(old, new))
433                         move_file(old, new, TRUE);
434                 g_free(old);
435                 g_free(new);
436         }
437         g_free(buf);
438         g_free(fqdn_host);
439
440         return cert;
441 }
442
443 static gboolean ssl_certificate_compare (SSLCertificate *cert_a, SSLCertificate *cert_b)
444 {
445 #ifdef USE_OPENSSL
446         if (cert_a == NULL || cert_b == NULL)
447                 return FALSE;
448         else if (!X509_cmp(cert_a->x509_cert, cert_b->x509_cert))
449                 return TRUE;
450         else
451                 return FALSE;
452 #else
453         char *output_a;
454         char *output_b;
455         size_t cert_size_a = 0, cert_size_b = 0;
456         int r;
457
458         if (cert_a == NULL || cert_b == NULL)
459                 return FALSE;
460
461         if ((r = gnutls_x509_crt_export(cert_a->x509_cert, GNUTLS_X509_FMT_DER, NULL, &cert_size_a)) 
462             != GNUTLS_E_SHORT_MEMORY_BUFFER) {
463                 g_warning("couldn't gnutls_x509_crt_export to get size a %s\n", gnutls_strerror(r));
464                 return FALSE;
465         }
466
467         if ((r = gnutls_x509_crt_export(cert_b->x509_cert, GNUTLS_X509_FMT_DER, NULL, &cert_size_b))
468             != GNUTLS_E_SHORT_MEMORY_BUFFER) {
469                 g_warning("couldn't gnutls_x509_crt_export to get size b %s\n", gnutls_strerror(r));
470                 return FALSE;
471         }
472
473         output_a = malloc(cert_size_a);
474         output_b = malloc(cert_size_b);
475         if ((r = gnutls_x509_crt_export(cert_a->x509_cert, GNUTLS_X509_FMT_DER, output_a, &cert_size_a)) < 0) {
476                 g_warning("couldn't gnutls_x509_crt_export a %s\n", gnutls_strerror(r));
477                 return FALSE;
478         }
479         if ((r = gnutls_x509_crt_export(cert_b->x509_cert, GNUTLS_X509_FMT_DER, output_b, &cert_size_b)) < 0) {
480                 g_warning("couldn't gnutls_x509_crt_export b %s\n", gnutls_strerror(r));
481                 return FALSE;
482         }
483         if (cert_size_a != cert_size_b) {
484                 g_warning("size differ %d %d\n", cert_size_a, cert_size_b);
485                 return FALSE;
486         }
487         if (memcmp(output_a, output_b, cert_size_a)) {
488                 g_warning("contents differ\n");
489                 return FALSE;
490         }
491         
492         return TRUE;
493 #endif
494 }
495
496 #if USE_OPENSSL
497 char *ssl_certificate_check_signer (X509 *cert) 
498 {
499         X509_STORE_CTX store_ctx;
500         X509_STORE *store;
501         char *err_msg = NULL;
502
503         store = X509_STORE_new();
504         if (store == NULL) {
505                 g_print("Can't create X509_STORE\n");
506                 return NULL;
507         }
508         if (!X509_STORE_set_default_paths(store)) {
509                 X509_STORE_free (store);
510                 return g_strdup(_("Couldn't load X509 default paths"));
511         }
512         
513         X509_STORE_CTX_init (&store_ctx, store, cert, NULL);
514
515         if(!X509_verify_cert (&store_ctx)) {
516                 err_msg = g_strdup(X509_verify_cert_error_string(
517                                         X509_STORE_CTX_get_error(&store_ctx)));
518                 debug_print("Can't check signer: %s\n", err_msg);
519                 X509_STORE_CTX_cleanup (&store_ctx);
520                 X509_STORE_free (store);
521                 return err_msg;
522                         
523         }
524         X509_STORE_CTX_cleanup (&store_ctx);
525         X509_STORE_free (store);
526         return NULL;
527 }
528 #else
529 char *ssl_certificate_check_signer (gnutls_x509_crt cert, guint status) 
530 {
531         if (status == (guint)-1)
532                 return g_strdup(_("Uncheckable"));
533
534         if (status & GNUTLS_CERT_INVALID) {
535                 if (gnutls_x509_crt_check_issuer(cert, cert))
536                         return g_strdup(_("Self-signed certificate"));
537         }
538         if (status & GNUTLS_CERT_REVOKED)
539                 return g_strdup(_("Revoked certificate"));
540         if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
541                 return g_strdup(_("No certificate issuer found"));
542         if (status & GNUTLS_CERT_SIGNER_NOT_CA)
543                 return g_strdup(_("Certificate issuer is not a CA"));
544
545
546         return NULL;
547 }
548 #endif
549
550 #if USE_OPENSSL
551 gboolean ssl_certificate_check (X509 *x509_cert, gchar *fqdn, gchar *host, gushort port)
552 #else
553 gboolean ssl_certificate_check (gnutls_x509_crt x509_cert, guint status, gchar *fqdn, gchar *host, gushort port)
554 #endif
555 {
556         SSLCertificate *current_cert = NULL;
557         SSLCertificate *known_cert;
558         SSLCertHookData cert_hook_data;
559         gchar *fqdn_host = NULL;        
560         gchar *fingerprint;
561         unsigned int n;
562         unsigned char md[128];  
563
564         if (fqdn)
565                 fqdn_host = g_strdup(fqdn);
566         else if (host)
567                 fqdn_host = get_fqdn(host);
568         else {
569                 g_warning("no host!\n");
570                 return FALSE;
571         }
572                 
573         current_cert = ssl_certificate_new_lookup(x509_cert, fqdn_host, port, FALSE);
574         
575         if (current_cert == NULL) {
576                 debug_print("Buggy certificate !\n");
577                 g_free(fqdn_host);
578                 return FALSE;
579         }
580
581 #if USE_GNUTLS
582         current_cert->status = status;
583 #endif
584         /* fingerprint */
585 #if USE_OPENSSL
586         X509_digest(x509_cert, EVP_md5(), md, &n);
587         fingerprint = readable_fingerprint(md, (int)n);
588 #else
589         n = 128;
590         gnutls_x509_crt_get_fingerprint(x509_cert, GNUTLS_DIG_MD5, md, &n);
591         fingerprint = readable_fingerprint(md, (int)n);
592 #endif
593
594         known_cert = ssl_certificate_find_lookup (fqdn_host, port, fingerprint, FALSE);
595
596         g_free(fingerprint);
597         g_free(fqdn_host);
598
599         if (known_cert == NULL) {
600                 cert_hook_data.cert = current_cert;
601                 cert_hook_data.old_cert = NULL;
602                 cert_hook_data.expired = FALSE;
603                 cert_hook_data.accept = FALSE;
604                 
605                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
606                 
607                 if (!cert_hook_data.accept) {
608                         ssl_certificate_destroy(current_cert);
609                         return FALSE;
610                 } else {
611                         ssl_certificate_save(current_cert);
612                         ssl_certificate_destroy(current_cert);
613                         return TRUE;
614                 }
615         } else if (!ssl_certificate_compare (current_cert, known_cert)) {
616                 cert_hook_data.cert = current_cert;
617                 cert_hook_data.old_cert = known_cert;
618                 cert_hook_data.expired = FALSE;
619                 cert_hook_data.accept = FALSE;
620                 
621                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
622
623                 if (!cert_hook_data.accept) {
624                         ssl_certificate_destroy(current_cert);
625                         ssl_certificate_destroy(known_cert);
626                         return FALSE;
627                 } else {
628                         ssl_certificate_save(current_cert);
629                         ssl_certificate_destroy(current_cert);
630                         ssl_certificate_destroy(known_cert);
631                         return TRUE;
632                 }
633 #if USE_OPENSSL
634         } else if (asn1toTime(X509_get_notAfter(current_cert->x509_cert)) < time(NULL)) {
635 #else
636         } else if (gnutls_x509_crt_get_expiration_time(current_cert->x509_cert) < time(NULL)) {
637 #endif
638                 gchar *tmp = g_strdup_printf("%s:%d", current_cert->host, current_cert->port);
639                 
640                 if (warned_expired == NULL)
641                         warned_expired = g_hash_table_new(g_str_hash, g_str_equal);
642                 
643                 if (g_hash_table_lookup(warned_expired, tmp)) {
644                         g_free(tmp);
645                         ssl_certificate_destroy(current_cert);
646                         ssl_certificate_destroy(known_cert);
647                         return TRUE;
648                 }
649                         
650                 cert_hook_data.cert = current_cert;
651                 cert_hook_data.old_cert = NULL;
652                 cert_hook_data.expired = TRUE;
653                 cert_hook_data.accept = FALSE;
654                 
655                 hooks_invoke(SSLCERT_ASK_HOOKLIST, &cert_hook_data);
656
657                 if (!cert_hook_data.accept) {
658                         g_free(tmp);
659                         ssl_certificate_destroy(current_cert);
660                         ssl_certificate_destroy(known_cert);
661                         return FALSE;
662                 } else {
663                         g_hash_table_insert(warned_expired, tmp, GINT_TO_POINTER(1));
664                         ssl_certificate_destroy(current_cert);
665                         ssl_certificate_destroy(known_cert);
666                         return TRUE;
667                 }
668         }
669
670         ssl_certificate_destroy(current_cert);
671         ssl_certificate_destroy(known_cert);
672         return TRUE;
673 }
674
675 #endif /* USE_OPENSSL */