2008-10-10 [colin] 3.6.0cvs25
[claws.git] / src / common / ssl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29
30 #include "claws.h"
31 #include "utils.h"
32 #include "ssl.h"
33 #include "ssl_certificate.h"
34 #include "hooks.h"
35
36 #ifdef HAVE_LIBETPAN
37 #include <libetpan/mailstream_ssl.h>
38 #endif
39
40 #ifdef USE_PTHREAD
41 #include <pthread.h>
42 #endif
43
44 #ifdef USE_PTHREAD
45 typedef struct _thread_data {
46 #ifdef USE_OPENSSL
47         SSL *ssl;
48 #else
49         gnutls_session ssl;
50 #endif
51         gboolean done;
52 } thread_data;
53 #endif
54
55
56 #ifdef USE_OPENSSL
57 static SSL_CTX *ssl_ctx;
58 #endif
59
60 #ifdef USE_OPENSSL
61 static int openssl_client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
62 {
63         SSLClientCertHookData hookdata;
64         SockInfo *sockinfo = (SockInfo *)SSL_CTX_get_app_data(ssl->ctx);
65         
66         if (x509 == NULL || pkey == NULL) {
67                 return 0;
68         }
69
70         if (sockinfo == NULL)
71                 return 0;
72
73         hookdata.account = sockinfo->account;
74         hookdata.cert_path = NULL;
75         hookdata.password = NULL;
76         hookdata.is_smtp = sockinfo->is_smtp;
77         hooks_invoke(SSLCERT_GET_CLIENT_CERT_HOOKLIST, &hookdata);      
78
79         if (hookdata.cert_path == NULL)
80                 return 0;
81
82         *x509 = ssl_certificate_get_x509_from_pem_file(hookdata.cert_path);
83         *pkey = ssl_certificate_get_pkey_from_pem_file(hookdata.cert_path);
84         if (!(*x509 && *pkey)) {
85                 /* try pkcs12 format */
86                 ssl_certificate_get_x509_and_pkey_from_p12_file(hookdata.cert_path, hookdata.password, x509, pkey);
87         }
88         if (*x509 && *pkey)
89                 return 1;
90         else
91                 return 0;
92 }
93 #endif
94 #ifdef USE_GNUTLS
95 static int gnutls_client_cert_cb(gnutls_session session,
96                                const gnutls_datum *req_ca_rdn, int nreqs,
97                                const gnutls_pk_algorithm *sign_algos,
98                                int sign_algos_length, gnutls_retr_st *st)
99 {
100         SSLClientCertHookData hookdata;
101         SockInfo *sockinfo = (SockInfo *)gnutls_session_get_ptr(session);
102         gnutls_certificate_type type = gnutls_certificate_type_get(session);
103         gnutls_x509_crt crt;
104         gnutls_x509_privkey key;
105
106         st->ncerts = 0;
107
108         hookdata.account = sockinfo->account;
109         hookdata.cert_path = NULL;
110         hookdata.password = NULL;
111         hookdata.is_smtp = sockinfo->is_smtp;
112         hooks_invoke(SSLCERT_GET_CLIENT_CERT_HOOKLIST, &hookdata);      
113
114         if (hookdata.cert_path == NULL)
115                 return 0;
116
117         sockinfo->client_crt = ssl_certificate_get_x509_from_pem_file(hookdata.cert_path);
118         sockinfo->client_key = ssl_certificate_get_pkey_from_pem_file(hookdata.cert_path);
119         if (!(sockinfo->client_crt && sockinfo->client_key)) {
120                 /* try pkcs12 format */
121                 ssl_certificate_get_x509_and_pkey_from_p12_file(hookdata.cert_path, hookdata.password, 
122                         &crt, &key);
123                 sockinfo->client_crt = crt;
124                 sockinfo->client_key = key;
125         }
126
127         if (type == GNUTLS_CRT_X509 && sockinfo->client_crt && sockinfo->client_key) {
128                 st->ncerts = 1;
129                 st->type = type;
130                 st->cert.x509 = &(sockinfo->client_crt);
131                 st->key.x509 = sockinfo->client_key;
132                 st->deinit_all = 0;
133                 return 0;
134         }
135         return 0;
136 }
137 #endif
138
139 #ifdef USE_OPENSSL
140 SSL_CTX *ssl_get_ctx(void)
141 {
142         return ssl_ctx;
143 }
144 #endif
145
146 const gchar *claws_ssl_get_cert_file(void)
147 {
148         const char *cert_files[]={
149                 "/etc/pki/tls/certs/ca-bundle.crt",
150                 "/etc/certs/ca-bundle.crt",
151                 "/usr/share/ssl/certs/ca-bundle.crt",
152                 "/etc/ssl/certs/ca-certificates.crt",
153                 "/usr/local/ssl/certs/ca-bundle.crt",
154                 "/etc/apache/ssl.crt/ca-bundle.crt",
155                 "/usr/share/curl/curl-ca-bundle.crt",
156                 "/usr/share/curl/curl-ca-bundle.crt",
157                 "/usr/lib/ssl/cert.pem",
158                 NULL};
159         int i;
160         
161         if (g_getenv("SSL_CERT_FILE"))
162                 return g_getenv("SSL_CERT_FILE");
163 #ifndef G_OS_WIN32
164         for (i = 0; cert_files[i]; i++) {
165                 if (is_file_exist(cert_files[i]))
166                         return cert_files[i];
167         }
168         return NULL;
169 #else
170         return "put_what_s_needed_here";
171 #endif
172 }
173
174 const gchar *claws_ssl_get_cert_dir(void)
175 {
176         const char *cert_dirs[]={
177                 "/etc/pki/tls/certs",
178                 "/etc/certs",
179                 "/usr/share/ssl/certs",
180                 "/etc/ssl/certs",
181                 "/usr/local/ssl/certs",
182                 "/etc/apache/ssl.crt",
183                 "/usr/share/curl",
184                 "/usr/lib/ssl/certs",
185                 NULL};
186         int i;
187         
188         if (g_getenv("SSL_CERT_DIR"))
189                 return g_getenv("SSL_CERT_DIR");
190 #ifndef G_OS_WIN32
191         for (i = 0; cert_dirs[i]; i++) {
192                 if (is_dir_exist(cert_dirs[i]))
193                         return cert_dirs[i];
194         }
195         return NULL;
196 #else
197         return "put_what_s_needed_here";
198 #endif
199 }
200
201 void ssl_init(void)
202 {
203 #ifdef USE_OPENSSL
204         SSL_METHOD *meth;
205
206         /* Global system initialization*/
207         SSL_library_init();
208         SSL_load_error_strings();
209         OpenSSL_add_all_algorithms();
210         OpenSSL_add_all_ciphers();
211         OpenSSL_add_all_digests();
212
213 #ifdef HAVE_LIBETPAN
214         mailstream_openssl_init_not_required();
215 #endif  
216
217         /* Create our context*/
218         meth = SSLv23_client_method();
219         ssl_ctx = SSL_CTX_new(meth);
220
221         
222         SSL_CTX_set_client_cert_cb(ssl_ctx, openssl_client_cert_cb);
223
224         /* Set default certificate paths */
225         if (claws_ssl_get_cert_file() || claws_ssl_get_cert_dir()) {
226                 int r = SSL_CTX_load_verify_locations(ssl_ctx, claws_ssl_get_cert_file(), claws_ssl_get_cert_dir());
227                 if (r != 1) {
228                         g_warning("can't set cert file %s dir %s: %s\n",
229                                         claws_ssl_get_cert_file(), claws_ssl_get_cert_dir(), ERR_error_string(ERR_get_error(), NULL));
230                         SSL_CTX_set_default_verify_paths(ssl_ctx);
231                 }
232         } else {
233                 g_warning("cant");
234                 SSL_CTX_set_default_verify_paths(ssl_ctx);
235         }
236 #if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
237         SSL_CTX_set_verify_depth(ssl_ctx,1);
238 #endif
239 #else
240 #ifdef HAVE_LIBETPAN
241         mailstream_gnutls_init_not_required();
242 #endif  
243         gnutls_global_init();
244 #endif
245 }
246
247 void ssl_done(void)
248 {
249 #if USE_OPENSSL
250         if (!ssl_ctx)
251                 return;
252         
253         SSL_CTX_free(ssl_ctx);
254 #else
255         gnutls_global_deinit();
256 #endif
257 }
258
259 #ifdef USE_PTHREAD
260 static void *SSL_connect_thread(void *data)
261 {
262         thread_data *td = (thread_data *)data;
263         int result = -1;
264
265         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
266         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
267
268 #ifdef USE_OPENSSL
269         result = SSL_connect(td->ssl);
270 #else
271         do {
272                 result = gnutls_handshake(td->ssl);
273         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
274 #endif
275         td->done = TRUE; /* let the caller thread join() */
276         return GINT_TO_POINTER(result);
277 }
278 #endif
279
280 #ifdef USE_OPENSSL
281 static gint SSL_connect_nb(SSL *ssl)
282 #else
283 static gint SSL_connect_nb(gnutls_session ssl)
284 #endif
285 {
286 #ifdef USE_GNUTLS
287         int result;
288 #endif
289 #ifdef USE_PTHREAD
290         thread_data *td = g_new0(thread_data, 1);
291         pthread_t pt;
292         pthread_attr_t pta;
293         void *res = NULL;
294         time_t start_time = time(NULL);
295         gboolean killed = FALSE;
296         
297         td->ssl  = ssl;
298         td->done = FALSE;
299         
300         /* try to create a thread to initialize the SSL connection,
301          * fallback to blocking method in case of problem 
302          */
303         if (pthread_attr_init(&pta) != 0 ||
304             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
305             pthread_create(&pt, &pta, SSL_connect_thread, td) != 0) {
306 #ifdef USE_OPENSSL
307                 return SSL_connect(ssl);
308 #else
309                 do {
310                         result = gnutls_handshake(td->ssl);
311                 } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
312                 return result;
313 #endif
314         }
315         debug_print("waiting for SSL_connect thread...\n");
316         while(!td->done) {
317                 /* don't let the interface freeze while waiting */
318                 claws_do_idle();
319                 if (time(NULL) - start_time > 30) {
320                         pthread_cancel(pt);
321                         td->done = TRUE;
322                         killed = TRUE;
323                 }
324         }
325
326         /* get the thread's return value and clean its resources */
327         pthread_join(pt, &res);
328         g_free(td);
329         
330         if (killed) {
331                 res = GINT_TO_POINTER(-1);
332         }
333         debug_print("SSL_connect thread returned %d\n", 
334                         GPOINTER_TO_INT(res));
335         
336         return GPOINTER_TO_INT(res);
337 #else /* USE_PTHREAD */
338 #ifdef USE_OPENSSL
339         return SSL_connect(ssl);
340 #else
341         do {
342                 result = gnutls_handshake(ssl);
343         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
344 #endif
345 #endif
346 }
347
348 gboolean ssl_init_socket(SockInfo *sockinfo)
349 {
350         return ssl_init_socket_with_method(sockinfo, SSL_METHOD_SSLv23);
351 }
352
353 gboolean ssl_init_socket_with_method(SockInfo *sockinfo, SSLMethod method)
354 {
355 #ifdef USE_OPENSSL
356         X509 *server_cert;
357         SSL *ssl;
358
359         ssl = SSL_new(ssl_ctx);
360         if (ssl == NULL) {
361                 g_warning(_("Error creating ssl context\n"));
362                 return FALSE;
363         }
364
365         switch (method) {
366         case SSL_METHOD_SSLv23:
367                 debug_print("Setting SSLv23 client method\n");
368                 SSL_set_ssl_method(ssl, SSLv23_client_method());
369                 break;
370         case SSL_METHOD_TLSv1:
371                 debug_print("Setting TLSv1 client method\n");
372                 SSL_set_ssl_method(ssl, TLSv1_client_method());
373                 break;
374         default:
375                 break;
376         }
377
378         SSL_CTX_set_app_data(ssl_ctx, sockinfo);
379         SSL_set_fd(ssl, sockinfo->sock);
380         if (SSL_connect_nb(ssl) == -1) {
381                 g_warning(_("SSL connect failed (%s)\n"),
382                             ERR_error_string(ERR_get_error(), NULL));
383                 SSL_free(ssl);
384                 return FALSE;
385         }
386
387         /* Get the cipher */
388
389         debug_print("SSL connection using %s\n", SSL_get_cipher(ssl));
390
391         /* Get server's certificate (note: beware of dynamic allocation) */
392         if ((server_cert = SSL_get_peer_certificate(ssl)) == NULL) {
393                 debug_print("server_cert is NULL ! this _should_not_ happen !\n");
394                 SSL_free(ssl);
395                 return FALSE;
396         }
397
398
399         if (!ssl_certificate_check(server_cert, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
400                 X509_free(server_cert);
401                 SSL_free(ssl);
402                 return FALSE;
403         }
404
405
406         X509_free(server_cert);
407         sockinfo->ssl = ssl;
408         
409 #else
410         gnutls_session session;
411         int r;
412         const int cipher_prio[] = { GNUTLS_CIPHER_AES_128_CBC,
413                                 GNUTLS_CIPHER_3DES_CBC,
414                                 GNUTLS_CIPHER_AES_256_CBC,
415                                 GNUTLS_CIPHER_ARCFOUR_128, 0 };
416         const int kx_prio[] = { GNUTLS_KX_DHE_RSA,
417                            GNUTLS_KX_RSA, 
418                            GNUTLS_KX_DHE_DSS, 0 };
419         const int mac_prio[] = { GNUTLS_MAC_SHA1,
420                                 GNUTLS_MAC_MD5, 0 };
421         const int proto_prio[] = { GNUTLS_TLS1,
422                                   GNUTLS_SSL3, 0 };
423         const gnutls_datum *raw_cert_list;
424         unsigned int raw_cert_list_length;
425         gnutls_x509_crt cert = NULL;
426         guint status;
427         gnutls_certificate_credentials_t xcred;
428
429         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
430                 return FALSE;
431
432         r = gnutls_init(&session, GNUTLS_CLIENT);
433         if (session == NULL || r != 0)
434                 return FALSE;
435   
436         gnutls_set_default_priority(session);
437         gnutls_protocol_set_priority (session, proto_prio);
438         gnutls_cipher_set_priority (session, cipher_prio);
439         gnutls_kx_set_priority (session, kx_prio);
440         gnutls_mac_set_priority (session, mac_prio);
441
442         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
443
444         if (claws_ssl_get_cert_file()) {
445                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
446                 if (r < 0)
447                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
448                                 claws_ssl_get_cert_file(), 
449                                 gnutls_strerror(r));
450         } else {
451                 debug_print("Can't find SSL ca-certificates file\n");
452         }
453         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
454
455         gnutls_transport_set_ptr(session, (gnutls_transport_ptr) sockinfo->sock);
456         gnutls_session_set_ptr(session, sockinfo);
457         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
458
459         gnutls_dh_set_prime_bits(session, 512);
460
461         if ((r = SSL_connect_nb(session)) < 0) {
462                 g_warning("SSL connection failed (%s)", gnutls_strerror(r));
463                 gnutls_certificate_free_credentials(xcred);
464                 gnutls_deinit(session);
465                 return FALSE;
466         }
467
468         /* Get server's certificate (note: beware of dynamic allocation) */
469         raw_cert_list = gnutls_certificate_get_peers(session, &raw_cert_list_length);
470
471         if (!raw_cert_list 
472         ||  gnutls_certificate_type_get(session) != GNUTLS_CRT_X509
473         ||  (r = gnutls_x509_crt_init(&cert)) < 0
474         ||  (r = gnutls_x509_crt_import(cert, &raw_cert_list[0], GNUTLS_X509_FMT_DER)) < 0) {
475                 g_warning("cert get failure: %d %s\n", r, gnutls_strerror(r));
476                 gnutls_certificate_free_credentials(xcred);
477                 gnutls_deinit(session);
478                 return FALSE;
479         }
480
481         r = gnutls_certificate_verify_peers2(session, &status);
482
483         if (!ssl_certificate_check(cert, status, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
484                 gnutls_x509_crt_deinit(cert);
485                 gnutls_certificate_free_credentials(xcred);
486                 gnutls_deinit(session);
487                 return FALSE;
488         }
489
490         gnutls_x509_crt_deinit(cert);
491
492         sockinfo->ssl = session;
493         sockinfo->xcred = xcred;
494 #endif
495         return TRUE;
496 }
497
498 void ssl_done_socket(SockInfo *sockinfo)
499 {
500         if (sockinfo && sockinfo->ssl) {
501 #ifdef USE_OPENSSL
502                 SSL_free(sockinfo->ssl);
503 #else
504                 gnutls_certificate_free_credentials(sockinfo->xcred);
505                 gnutls_deinit(sockinfo->ssl);
506                 if (sockinfo->client_crt)
507                         gnutls_x509_crt_deinit(sockinfo->client_crt);
508                 if (sockinfo->client_key)
509                         gnutls_x509_privkey_deinit(sockinfo->client_key);
510                 sockinfo->client_key = NULL;
511                 sockinfo->client_crt = NULL;
512 #endif
513                 sockinfo->ssl = NULL;
514         }
515 }
516
517 #endif /* USE_OPENSSL */