2008-07-05 [colin] 3.5.0cvs7
[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 -1;
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                 NULL};
157         int i;
158
159         if (g_getenv("SSL_CERT_FILE"))
160                 return g_getenv("SSL_CERT_FILE");
161 #ifndef G_OS_WIN32
162         for (i = 0; cert_files[i]; i++) {
163                 if (is_file_exist(cert_files[i]))
164                         return cert_files[i];
165         }
166         return NULL;
167 #else
168         return "put_what_s_needed_here";
169 #endif
170 }
171
172 const gchar *claws_ssl_get_cert_dir(void)
173 {
174         const char *cert_dirs[]={
175                 "/etc/pki/tls/certs",
176                 "/etc/certs",
177                 "/usr/share/ssl/certs",
178                 "/etc/ssl/certs",
179                 "/usr/local/ssl/certs",
180                 "/etc/apache/ssl.crt",
181                 "/usr/share/curl",
182                 NULL};
183         int i;
184
185         if (g_getenv("SSL_CERT_FILE"))
186                 return g_getenv("SSL_CERT_FILE");
187 #ifndef G_OS_WIN32
188         for (i = 0; cert_dirs[i]; i++) {
189                 if (is_dir_exist(cert_dirs[i]))
190                         return cert_dirs[i];
191         }
192         return NULL;
193 #else
194         return "put_what_s_needed_here";
195 #endif
196 }
197
198 void ssl_init(void)
199 {
200 #ifdef USE_OPENSSL
201         SSL_METHOD *meth;
202
203         /* Global system initialization*/
204         SSL_library_init();
205         SSL_load_error_strings();
206         OpenSSL_add_all_algorithms();
207         OpenSSL_add_all_ciphers();
208         OpenSSL_add_all_digests();
209
210 #ifdef HAVE_LIBETPAN
211         mailstream_openssl_init_not_required();
212 #endif  
213
214         /* Create our context*/
215         meth = SSLv23_client_method();
216         ssl_ctx = SSL_CTX_new(meth);
217
218         
219         SSL_CTX_set_client_cert_cb(ssl_ctx, openssl_client_cert_cb);
220
221         /* Set default certificate paths */
222         if (claws_ssl_get_cert_file() || claws_ssl_get_cert_dir()) {
223                 int r = SSL_CTX_load_verify_locations(ssl_ctx, claws_ssl_get_cert_file(), claws_ssl_get_cert_dir());
224                 if (r != 1) {
225                         g_warning("can't set cert file %s dir %s: %s\n",
226                                         claws_ssl_get_cert_file(), claws_ssl_get_cert_dir(), ERR_error_string(ERR_get_error(), NULL));
227                         SSL_CTX_set_default_verify_paths(ssl_ctx);
228                 }
229         } else {
230                 g_warning("cant");
231                 SSL_CTX_set_default_verify_paths(ssl_ctx);
232         }
233 #if (OPENSSL_VERSION_NUMBER < 0x0090600fL)
234         SSL_CTX_set_verify_depth(ssl_ctx,1);
235 #endif
236 #else
237         gnutls_global_init();
238 #endif
239 }
240
241 void ssl_done(void)
242 {
243 #if USE_OPENSSL
244         if (!ssl_ctx)
245                 return;
246         
247         SSL_CTX_free(ssl_ctx);
248 #else
249         gnutls_global_deinit();
250 #endif
251 }
252
253 #ifdef USE_PTHREAD
254 static void *SSL_connect_thread(void *data)
255 {
256         thread_data *td = (thread_data *)data;
257         int result = -1;
258
259         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
260         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
261
262 #ifdef USE_OPENSSL
263         result = SSL_connect(td->ssl);
264 #else
265         do {
266                 result = gnutls_handshake(td->ssl);
267         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
268 #endif
269         td->done = TRUE; /* let the caller thread join() */
270         return GINT_TO_POINTER(result);
271 }
272 #endif
273
274 #ifdef USE_OPENSSL
275 static gint SSL_connect_nb(SSL *ssl)
276 #else
277 static gint SSL_connect_nb(gnutls_session ssl)
278 #endif
279 {
280 #ifdef USE_GNUTLS
281         int result;
282 #endif
283 #ifdef USE_PTHREAD
284         thread_data *td = g_new0(thread_data, 1);
285         pthread_t pt;
286         pthread_attr_t pta;
287         void *res = NULL;
288         time_t start_time = time(NULL);
289         gboolean killed = FALSE;
290         
291         td->ssl  = ssl;
292         td->done = FALSE;
293         
294         /* try to create a thread to initialize the SSL connection,
295          * fallback to blocking method in case of problem 
296          */
297         if (pthread_attr_init(&pta) != 0 ||
298             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
299             pthread_create(&pt, &pta, SSL_connect_thread, td) != 0) {
300 #ifdef USE_OPENSSL
301                 return SSL_connect(ssl);
302 #else
303                 do {
304                         result = gnutls_handshake(td->ssl);
305                 } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
306                 return result;
307 #endif
308         }
309         debug_print("waiting for SSL_connect thread...\n");
310         while(!td->done) {
311                 /* don't let the interface freeze while waiting */
312                 claws_do_idle();
313                 if (time(NULL) - start_time > 30) {
314                         pthread_cancel(pt);
315                         td->done = TRUE;
316                         killed = TRUE;
317                 }
318         }
319
320         /* get the thread's return value and clean its resources */
321         pthread_join(pt, &res);
322         g_free(td);
323         
324         if (killed) {
325                 res = GINT_TO_POINTER(-1);
326         }
327         debug_print("SSL_connect thread returned %d\n", 
328                         GPOINTER_TO_INT(res));
329         
330         return GPOINTER_TO_INT(res);
331 #else /* USE_PTHREAD */
332 #ifdef USE_OPENSSL
333         return SSL_connect(ssl);
334 #else
335         do {
336                 result = gnutls_handshake(ssl);
337         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
338 #endif
339 #endif
340 }
341
342 gboolean ssl_init_socket(SockInfo *sockinfo)
343 {
344         return ssl_init_socket_with_method(sockinfo, SSL_METHOD_SSLv23);
345 }
346
347 gboolean ssl_init_socket_with_method(SockInfo *sockinfo, SSLMethod method)
348 {
349 #ifdef USE_OPENSSL
350         X509 *server_cert;
351         SSL *ssl;
352
353         ssl = SSL_new(ssl_ctx);
354         if (ssl == NULL) {
355                 g_warning(_("Error creating ssl context\n"));
356                 return FALSE;
357         }
358
359         switch (method) {
360         case SSL_METHOD_SSLv23:
361                 debug_print("Setting SSLv23 client method\n");
362                 SSL_set_ssl_method(ssl, SSLv23_client_method());
363                 break;
364         case SSL_METHOD_TLSv1:
365                 debug_print("Setting TLSv1 client method\n");
366                 SSL_set_ssl_method(ssl, TLSv1_client_method());
367                 break;
368         default:
369                 break;
370         }
371
372         SSL_CTX_set_app_data(ssl_ctx, sockinfo);
373         SSL_set_fd(ssl, sockinfo->sock);
374         if (SSL_connect_nb(ssl) == -1) {
375                 g_warning(_("SSL connect failed (%s)\n"),
376                             ERR_error_string(ERR_get_error(), NULL));
377                 SSL_free(ssl);
378                 return FALSE;
379         }
380
381         /* Get the cipher */
382
383         debug_print("SSL connection using %s\n", SSL_get_cipher(ssl));
384
385         /* Get server's certificate (note: beware of dynamic allocation) */
386         if ((server_cert = SSL_get_peer_certificate(ssl)) == NULL) {
387                 debug_print("server_cert is NULL ! this _should_not_ happen !\n");
388                 SSL_free(ssl);
389                 return FALSE;
390         }
391
392
393         if (!ssl_certificate_check(server_cert, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
394                 X509_free(server_cert);
395                 SSL_free(ssl);
396                 return FALSE;
397         }
398
399
400         X509_free(server_cert);
401         sockinfo->ssl = ssl;
402         
403 #else
404         gnutls_session session;
405         int r;
406         const int cipher_prio[] = { GNUTLS_CIPHER_AES_128_CBC,
407                                 GNUTLS_CIPHER_3DES_CBC,
408                                 GNUTLS_CIPHER_AES_256_CBC,
409                                 GNUTLS_CIPHER_ARCFOUR_128, 0 };
410         const int kx_prio[] = { GNUTLS_KX_DHE_RSA,
411                            GNUTLS_KX_RSA, 
412                            GNUTLS_KX_DHE_DSS, 0 };
413         const int mac_prio[] = { GNUTLS_MAC_SHA1,
414                                 GNUTLS_MAC_MD5, 0 };
415         const int proto_prio[] = { GNUTLS_TLS1,
416                                   GNUTLS_SSL3, 0 };
417         const gnutls_datum *raw_cert_list;
418         unsigned int raw_cert_list_length;
419         gnutls_x509_crt cert = NULL;
420         guint status;
421         gnutls_certificate_credentials_t xcred;
422
423         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
424                 return FALSE;
425
426         r = gnutls_init(&session, GNUTLS_CLIENT);
427         if (session == NULL || r != 0)
428                 return FALSE;
429   
430         gnutls_set_default_priority(session);
431         gnutls_protocol_set_priority (session, proto_prio);
432         gnutls_cipher_set_priority (session, cipher_prio);
433         gnutls_kx_set_priority (session, kx_prio);
434         gnutls_mac_set_priority (session, mac_prio);
435
436         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
437
438         if (claws_ssl_get_cert_file()) {
439                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
440                 if (r < 0)
441                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
442                                 claws_ssl_get_cert_file(), 
443                                 gnutls_strerror(r));
444         } else {
445                 debug_print("Can't find SSL ca-certificates file\n");
446         }
447         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
448
449         gnutls_transport_set_ptr(session, (gnutls_transport_ptr) sockinfo->sock);
450         gnutls_session_set_ptr(session, sockinfo);
451         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
452
453         gnutls_dh_set_prime_bits(session, 512);
454
455         if ((r = SSL_connect_nb(session)) < 0) {
456                 g_warning("SSL connection failed (%s)", gnutls_strerror(r));
457                 gnutls_certificate_free_credentials(xcred);
458                 gnutls_deinit(session);
459                 return FALSE;
460         }
461
462         /* Get server's certificate (note: beware of dynamic allocation) */
463         raw_cert_list = gnutls_certificate_get_peers(session, &raw_cert_list_length);
464
465         if (!raw_cert_list 
466         ||  gnutls_certificate_type_get(session) != GNUTLS_CRT_X509
467         ||  (r = gnutls_x509_crt_init(&cert)) < 0
468         ||  (r = gnutls_x509_crt_import(cert, &raw_cert_list[0], GNUTLS_X509_FMT_DER)) < 0) {
469                 g_warning("cert get failure: %d %s\n", r, gnutls_strerror(r));
470                 gnutls_certificate_free_credentials(xcred);
471                 gnutls_deinit(session);
472                 return FALSE;
473         }
474
475         r = gnutls_certificate_verify_peers2(session, &status);
476
477         if (!ssl_certificate_check(cert, status, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
478                 gnutls_x509_crt_deinit(cert);
479                 gnutls_certificate_free_credentials(xcred);
480                 gnutls_deinit(session);
481                 return FALSE;
482         }
483
484         gnutls_x509_crt_deinit(cert);
485
486         sockinfo->ssl = session;
487         sockinfo->xcred = xcred;
488 #endif
489         return TRUE;
490 }
491
492 void ssl_done_socket(SockInfo *sockinfo)
493 {
494         if (sockinfo && sockinfo->ssl) {
495 #ifdef USE_OPENSSL
496                 SSL_free(sockinfo->ssl);
497 #else
498                 gnutls_certificate_free_credentials(sockinfo->xcred);
499                 gnutls_deinit(sockinfo->ssl);
500                 if (sockinfo->client_crt)
501                         gnutls_x509_crt_deinit(sockinfo->client_crt);
502                 if (sockinfo->client_key)
503                         gnutls_x509_privkey_deinit(sockinfo->client_key);
504                 sockinfo->client_key = NULL;
505                 sockinfo->client_crt = NULL;
506 #endif
507                 sockinfo->ssl = NULL;
508         }
509 }
510
511 #endif /* USE_OPENSSL */