262bddb31c59d09500afc78dc87a2e89c9e1e6de
[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                 "/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_FILE"))
189                 return g_getenv("SSL_CERT_FILE");
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         gnutls_global_init();
241 #endif
242 }
243
244 void ssl_done(void)
245 {
246 #if USE_OPENSSL
247         if (!ssl_ctx)
248                 return;
249         
250         SSL_CTX_free(ssl_ctx);
251 #else
252         gnutls_global_deinit();
253 #endif
254 }
255
256 #ifdef USE_PTHREAD
257 static void *SSL_connect_thread(void *data)
258 {
259         thread_data *td = (thread_data *)data;
260         int result = -1;
261
262         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
263         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
264
265 #ifdef USE_OPENSSL
266         result = SSL_connect(td->ssl);
267 #else
268         do {
269                 result = gnutls_handshake(td->ssl);
270         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
271 #endif
272         td->done = TRUE; /* let the caller thread join() */
273         return GINT_TO_POINTER(result);
274 }
275 #endif
276
277 #ifdef USE_OPENSSL
278 static gint SSL_connect_nb(SSL *ssl)
279 #else
280 static gint SSL_connect_nb(gnutls_session ssl)
281 #endif
282 {
283 #ifdef USE_GNUTLS
284         int result;
285 #endif
286 #ifdef USE_PTHREAD
287         thread_data *td = g_new0(thread_data, 1);
288         pthread_t pt;
289         pthread_attr_t pta;
290         void *res = NULL;
291         time_t start_time = time(NULL);
292         gboolean killed = FALSE;
293         
294         td->ssl  = ssl;
295         td->done = FALSE;
296         
297         /* try to create a thread to initialize the SSL connection,
298          * fallback to blocking method in case of problem 
299          */
300         if (pthread_attr_init(&pta) != 0 ||
301             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
302             pthread_create(&pt, &pta, SSL_connect_thread, td) != 0) {
303 #ifdef USE_OPENSSL
304                 return SSL_connect(ssl);
305 #else
306                 do {
307                         result = gnutls_handshake(td->ssl);
308                 } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
309                 return result;
310 #endif
311         }
312         debug_print("waiting for SSL_connect thread...\n");
313         while(!td->done) {
314                 /* don't let the interface freeze while waiting */
315                 claws_do_idle();
316                 if (time(NULL) - start_time > 30) {
317                         pthread_cancel(pt);
318                         td->done = TRUE;
319                         killed = TRUE;
320                 }
321         }
322
323         /* get the thread's return value and clean its resources */
324         pthread_join(pt, &res);
325         g_free(td);
326         
327         if (killed) {
328                 res = GINT_TO_POINTER(-1);
329         }
330         debug_print("SSL_connect thread returned %d\n", 
331                         GPOINTER_TO_INT(res));
332         
333         return GPOINTER_TO_INT(res);
334 #else /* USE_PTHREAD */
335 #ifdef USE_OPENSSL
336         return SSL_connect(ssl);
337 #else
338         do {
339                 result = gnutls_handshake(ssl);
340         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
341 #endif
342 #endif
343 }
344
345 gboolean ssl_init_socket(SockInfo *sockinfo)
346 {
347         return ssl_init_socket_with_method(sockinfo, SSL_METHOD_SSLv23);
348 }
349
350 gboolean ssl_init_socket_with_method(SockInfo *sockinfo, SSLMethod method)
351 {
352 #ifdef USE_OPENSSL
353         X509 *server_cert;
354         SSL *ssl;
355
356         ssl = SSL_new(ssl_ctx);
357         if (ssl == NULL) {
358                 g_warning(_("Error creating ssl context\n"));
359                 return FALSE;
360         }
361
362         switch (method) {
363         case SSL_METHOD_SSLv23:
364                 debug_print("Setting SSLv23 client method\n");
365                 SSL_set_ssl_method(ssl, SSLv23_client_method());
366                 break;
367         case SSL_METHOD_TLSv1:
368                 debug_print("Setting TLSv1 client method\n");
369                 SSL_set_ssl_method(ssl, TLSv1_client_method());
370                 break;
371         default:
372                 break;
373         }
374
375         SSL_CTX_set_app_data(ssl_ctx, sockinfo);
376         SSL_set_fd(ssl, sockinfo->sock);
377         if (SSL_connect_nb(ssl) == -1) {
378                 g_warning(_("SSL connect failed (%s)\n"),
379                             ERR_error_string(ERR_get_error(), NULL));
380                 SSL_free(ssl);
381                 return FALSE;
382         }
383
384         /* Get the cipher */
385
386         debug_print("SSL connection using %s\n", SSL_get_cipher(ssl));
387
388         /* Get server's certificate (note: beware of dynamic allocation) */
389         if ((server_cert = SSL_get_peer_certificate(ssl)) == NULL) {
390                 debug_print("server_cert is NULL ! this _should_not_ happen !\n");
391                 SSL_free(ssl);
392                 return FALSE;
393         }
394
395
396         if (!ssl_certificate_check(server_cert, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
397                 X509_free(server_cert);
398                 SSL_free(ssl);
399                 return FALSE;
400         }
401
402
403         X509_free(server_cert);
404         sockinfo->ssl = ssl;
405         
406 #else
407         gnutls_session session;
408         int r;
409         const int cipher_prio[] = { GNUTLS_CIPHER_AES_128_CBC,
410                                 GNUTLS_CIPHER_3DES_CBC,
411                                 GNUTLS_CIPHER_AES_256_CBC,
412                                 GNUTLS_CIPHER_ARCFOUR_128, 0 };
413         const int kx_prio[] = { GNUTLS_KX_DHE_RSA,
414                            GNUTLS_KX_RSA, 
415                            GNUTLS_KX_DHE_DSS, 0 };
416         const int mac_prio[] = { GNUTLS_MAC_SHA1,
417                                 GNUTLS_MAC_MD5, 0 };
418         const int proto_prio[] = { GNUTLS_TLS1,
419                                   GNUTLS_SSL3, 0 };
420         const gnutls_datum *raw_cert_list;
421         unsigned int raw_cert_list_length;
422         gnutls_x509_crt cert = NULL;
423         guint status;
424         gnutls_certificate_credentials_t xcred;
425
426         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
427                 return FALSE;
428
429         r = gnutls_init(&session, GNUTLS_CLIENT);
430         if (session == NULL || r != 0)
431                 return FALSE;
432   
433         gnutls_set_default_priority(session);
434         gnutls_protocol_set_priority (session, proto_prio);
435         gnutls_cipher_set_priority (session, cipher_prio);
436         gnutls_kx_set_priority (session, kx_prio);
437         gnutls_mac_set_priority (session, mac_prio);
438
439         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
440
441         if (claws_ssl_get_cert_file()) {
442                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
443                 if (r < 0)
444                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
445                                 claws_ssl_get_cert_file(), 
446                                 gnutls_strerror(r));
447         } else {
448                 debug_print("Can't find SSL ca-certificates file\n");
449         }
450         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
451
452         gnutls_transport_set_ptr(session, (gnutls_transport_ptr) sockinfo->sock);
453         gnutls_session_set_ptr(session, sockinfo);
454         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
455
456         gnutls_dh_set_prime_bits(session, 512);
457
458         if ((r = SSL_connect_nb(session)) < 0) {
459                 g_warning("SSL connection failed (%s)", gnutls_strerror(r));
460                 gnutls_certificate_free_credentials(xcred);
461                 gnutls_deinit(session);
462                 return FALSE;
463         }
464
465         /* Get server's certificate (note: beware of dynamic allocation) */
466         raw_cert_list = gnutls_certificate_get_peers(session, &raw_cert_list_length);
467
468         if (!raw_cert_list 
469         ||  gnutls_certificate_type_get(session) != GNUTLS_CRT_X509
470         ||  (r = gnutls_x509_crt_init(&cert)) < 0
471         ||  (r = gnutls_x509_crt_import(cert, &raw_cert_list[0], GNUTLS_X509_FMT_DER)) < 0) {
472                 g_warning("cert get failure: %d %s\n", r, gnutls_strerror(r));
473                 gnutls_certificate_free_credentials(xcred);
474                 gnutls_deinit(session);
475                 return FALSE;
476         }
477
478         r = gnutls_certificate_verify_peers2(session, &status);
479
480         if (!ssl_certificate_check(cert, status, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
481                 gnutls_x509_crt_deinit(cert);
482                 gnutls_certificate_free_credentials(xcred);
483                 gnutls_deinit(session);
484                 return FALSE;
485         }
486
487         gnutls_x509_crt_deinit(cert);
488
489         sockinfo->ssl = session;
490         sockinfo->xcred = xcred;
491 #endif
492         return TRUE;
493 }
494
495 void ssl_done_socket(SockInfo *sockinfo)
496 {
497         if (sockinfo && sockinfo->ssl) {
498 #ifdef USE_OPENSSL
499                 SSL_free(sockinfo->ssl);
500 #else
501                 gnutls_certificate_free_credentials(sockinfo->xcred);
502                 gnutls_deinit(sockinfo->ssl);
503                 if (sockinfo->client_crt)
504                         gnutls_x509_crt_deinit(sockinfo->client_crt);
505                 if (sockinfo->client_key)
506                         gnutls_x509_privkey_deinit(sockinfo->client_key);
507                 sockinfo->client_key = NULL;
508                 sockinfo->client_crt = NULL;
509 #endif
510                 sockinfo->ssl = NULL;
511         }
512 }
513
514 #endif /* USE_OPENSSL */