3c85a1d728cfbd0c21610c0223b9be5116b2fc3b
[claws.git] / src / common / ssl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 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 #include "claws-features.h"
23 #endif
24
25 #ifdef USE_GNUTLS
26 #include "defs.h"
27
28 #include <stdlib.h>
29 #include <glib.h>
30 #include <glib/gi18n.h>
31 #include <errno.h>
32 #include <pthread.h>
33
34 #include "claws.h"
35 #include "utils.h"
36 #include "ssl.h"
37 #include "ssl_certificate.h"
38 #include "hooks.h"
39
40 #if GNUTLS_VERSION_NUMBER <= 0x020b00
41 #include <gcrypt.h>
42 GCRY_THREAD_OPTION_PTHREAD_IMPL;
43 #endif
44
45 #ifdef HAVE_LIBETPAN
46 #include <libetpan/mailstream_ssl.h>
47 #endif
48
49 #ifdef USE_PTHREAD
50 #include <pthread.h>
51 #endif
52
53 #ifdef USE_PTHREAD
54 typedef struct _thread_data {
55         gnutls_session_t ssl;
56         gboolean done;
57 } thread_data;
58 #endif
59
60 #if GNUTLS_VERSION_NUMBER < 0x030400
61 #define DEFAULT_GNUTLS_PRIORITY "NORMAL:-VERS-SSL3.0"
62 #else
63 #define DEFAULT_GNUTLS_PRIORITY "NORMAL"
64 #endif
65
66 #if GNUTLS_VERSION_NUMBER <= 0x020c00
67 static int gnutls_client_cert_cb(gnutls_session_t session,
68                                const gnutls_datum_t *req_ca_rdn, int nreqs,
69                                const gnutls_pk_algorithm_t *sign_algos,
70                                int sign_algos_length, gnutls_retr_st *st)
71 #else
72 static int gnutls_cert_cb(gnutls_session_t session,
73                                const gnutls_datum_t *req_ca_rdn, int nreqs,
74                                const gnutls_pk_algorithm_t *sign_algos,
75                                int sign_algos_length, gnutls_retr2_st *st)
76 #endif
77 {
78         SSLClientCertHookData hookdata;
79         SockInfo *sockinfo = (SockInfo *)gnutls_session_get_ptr(session);
80         gnutls_certificate_type_t type = gnutls_certificate_type_get(session);
81         gnutls_x509_crt_t crt;
82         gnutls_x509_privkey_t key;
83
84         st->ncerts = 0;
85
86         hookdata.account = sockinfo->account;
87         hookdata.cert_path = NULL;
88         hookdata.password = NULL;
89         hookdata.is_smtp = sockinfo->is_smtp;
90         hooks_invoke(SSLCERT_GET_CLIENT_CERT_HOOKLIST, &hookdata);      
91
92         if (hookdata.cert_path == NULL) {
93                 g_free(hookdata.password);
94                 return 0;
95         }
96
97         sockinfo->client_crt = ssl_certificate_get_x509_from_pem_file(hookdata.cert_path);
98         sockinfo->client_key = ssl_certificate_get_pkey_from_pem_file(hookdata.cert_path);
99         if (!(sockinfo->client_crt && sockinfo->client_key)) {
100                 /* try pkcs12 format */
101                 ssl_certificate_get_x509_and_pkey_from_p12_file(hookdata.cert_path, hookdata.password, 
102                         &crt, &key);
103                 sockinfo->client_crt = crt;
104                 sockinfo->client_key = key;
105         }
106
107         if (type == GNUTLS_CRT_X509 && sockinfo->client_crt && sockinfo->client_key) {
108                 st->ncerts = 1;
109 #if GNUTLS_VERSION_NUMBER <= 0x020c00
110                 st->type = type;
111 #else
112                 st->key_type = type;
113 #endif
114                 st->cert.x509 = &(sockinfo->client_crt);
115                 st->key.x509 = sockinfo->client_key;
116                 st->deinit_all = 0;
117                 g_free(hookdata.password);
118                 return 0;
119         }
120         g_free(hookdata.password);
121         return 0;
122 }
123
124 const gchar *claws_ssl_get_cert_file(void)
125 {
126 #ifndef G_OS_WIN32
127         const char *cert_files[]={
128                 "/etc/pki/tls/certs/ca-bundle.crt",
129                 "/etc/certs/ca-bundle.crt",
130                 "/etc/ssl/ca-bundle.pem",
131                 "/usr/share/ssl/certs/ca-bundle.crt",
132                 "/etc/ssl/certs/ca-certificates.crt",
133                 "/usr/local/ssl/certs/ca-bundle.crt",
134                 "/etc/apache/ssl.crt/ca-bundle.crt",
135                 "/usr/share/curl/curl-ca-bundle.crt",
136                 "/usr/share/curl/curl-ca-bundle.crt",
137                 "/usr/lib/ssl/cert.pem",
138                 NULL};
139         int i;
140 #endif
141
142         /* We honor this environment variable on all platforms. */
143         if (g_getenv("SSL_CERT_FILE"))
144                 return g_getenv("SSL_CERT_FILE");
145
146 #ifndef G_OS_WIN32
147         for (i = 0; cert_files[i]; i++) {
148                 if (is_file_exist(cert_files[i]))
149                         return cert_files[i];
150         }
151         return NULL;
152 #else
153         return w32_get_cert_file();
154 #endif
155 }
156
157 const gchar *claws_ssl_get_cert_dir(void)
158 {
159         const char *cert_dirs[]={
160                 "/etc/pki/tls/certs",
161                 "/etc/certs",
162                 "/usr/share/ssl/certs",
163                 "/etc/ssl/certs",
164                 "/usr/local/ssl/certs",
165                 "/etc/apache/ssl.crt",
166                 "/usr/share/curl",
167                 "/usr/lib/ssl/certs",
168                 NULL};
169         int i;
170         
171         if (g_getenv("SSL_CERT_DIR"))
172                 return g_getenv("SSL_CERT_DIR");
173 #ifndef G_OS_WIN32
174         for (i = 0; cert_dirs[i]; i++) {
175                 if (is_dir_exist(cert_dirs[i]))
176                         return cert_dirs[i];
177         }
178         return NULL;
179 #else
180         return NULL;
181 #endif
182 }
183
184 void ssl_init(void)
185 {
186 #if GNUTLS_VERSION_NUMBER <= 0x020b00
187         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
188 #endif
189 #ifdef HAVE_LIBETPAN
190         mailstream_gnutls_init_not_required();
191 #endif  
192         gnutls_global_init();
193 }
194
195 void ssl_done(void)
196 {
197         gnutls_global_deinit();
198 }
199
200 #ifdef USE_PTHREAD
201 static void *SSL_connect_thread(void *data)
202 {
203         thread_data *td = (thread_data *)data;
204         int result = -1;
205
206         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
207         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
208
209         do {
210                 result = gnutls_handshake(td->ssl);
211         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
212
213         td->done = TRUE; /* let the caller thread join() */
214         return GINT_TO_POINTER(result);
215 }
216 #endif
217
218 static gint SSL_connect_nb(gnutls_session_t ssl)
219 {
220         int result;
221 #ifdef USE_PTHREAD
222         thread_data *td = g_new0(thread_data, 1);
223         pthread_t pt;
224         pthread_attr_t pta;
225         void *res = NULL;
226         time_t start_time = time(NULL);
227         gboolean killed = FALSE;
228         
229         td->ssl  = ssl;
230         td->done = FALSE;
231         
232         /* try to create a thread to initialize the SSL connection,
233          * fallback to blocking method in case of problem 
234          */
235         if (pthread_attr_init(&pta) != 0 ||
236             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
237             pthread_create(&pt, &pta, SSL_connect_thread, td) != 0) {
238                 do {
239                         result = gnutls_handshake(td->ssl);
240                 } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
241                 return result;
242         }
243         debug_print("waiting for SSL_connect thread...\n");
244         while(!td->done) {
245                 /* don't let the interface freeze while waiting */
246                 claws_do_idle();
247                 if (time(NULL) - start_time > 30) {
248                         pthread_cancel(pt);
249                         td->done = TRUE;
250                         killed = TRUE;
251                 }
252         }
253
254         /* get the thread's return value and clean its resources */
255         pthread_join(pt, &res);
256         g_free(td);
257         
258         if (killed) {
259                 res = GINT_TO_POINTER(-1);
260         }
261         debug_print("SSL_connect thread returned %d\n", 
262                         GPOINTER_TO_INT(res));
263         
264         return GPOINTER_TO_INT(res);
265 #else /* USE_PTHREAD */
266         do {
267                 result = gnutls_handshake(ssl);
268         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
269 #endif
270 }
271
272 gnutls_x509_crt_t *ssl_get_certificate_chain(gnutls_session_t session, gint *list_len)
273 {
274         const gnutls_datum_t *raw_cert_list;
275         gnutls_x509_crt_t *certs = NULL;
276         gboolean result = TRUE;
277
278         *list_len = -1;
279         if (!session)
280                 return NULL;
281
282         raw_cert_list = gnutls_certificate_get_peers(session, list_len);
283
284         if (raw_cert_list && gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
285                 int i = 0;
286
287                 if (*list_len > 128)
288                         *list_len = 128;
289
290                 certs = g_malloc(sizeof(gnutls_x509_crt_t) * (*list_len));
291
292                 for(i = 0 ; i < (*list_len) ; i++) {
293                         int r;
294
295                         gnutls_x509_crt_init(&certs[i]);
296                         r = gnutls_x509_crt_import(certs[i], &raw_cert_list[i], GNUTLS_X509_FMT_DER);
297                         if (r < 0) {
298                                 g_warning("cert get failure: %d %s", r, gnutls_strerror(r));
299
300                                 result = FALSE;
301                                 i--;
302                                 break;
303                         }
304                 }
305                 if (!result) {
306                         for (; i >= 0; i--)
307                                 gnutls_x509_crt_deinit(certs[i]);
308
309                         g_free(certs);
310                         *list_len = -1;
311
312                         return NULL;
313                 }
314         }
315
316         return certs;
317 }
318
319 gboolean ssl_init_socket(SockInfo *sockinfo)
320 {
321         gnutls_session_t session;
322         int r, i;
323         unsigned int cert_list_length;
324         gnutls_x509_crt_t *certs = NULL;
325         gnutls_certificate_credentials_t xcred;
326
327         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
328                 return FALSE;
329
330         r = gnutls_init(&session, GNUTLS_CLIENT);
331         if (session == NULL || r != 0)
332                 return FALSE;
333
334         if (sockinfo->gnutls_priority && strlen(sockinfo->gnutls_priority)) {
335                 r = gnutls_priority_set_direct(session, sockinfo->gnutls_priority, NULL);
336                 debug_print("Setting GnuTLS priority to %s, status = %d\n",
337                             sockinfo->gnutls_priority, r);
338         }
339         else {
340                 gnutls_priority_set_direct(session, DEFAULT_GNUTLS_PRIORITY, NULL);
341         }
342
343         gnutls_record_disable_padding(session);
344
345         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
346
347         if (claws_ssl_get_cert_file()) {
348                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
349                 if (r < 0)
350                         g_warning("Can't read SSL_CERT_FILE '%s': %s",
351                                 claws_ssl_get_cert_file(), 
352                                 gnutls_strerror(r));
353         } else {
354                 debug_print("Can't find SSL ca-certificates file\n");
355         }
356         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
357
358         gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) GINT_TO_POINTER(sockinfo->sock));
359         gnutls_session_set_ptr(session, sockinfo);
360 #if GNUTLS_VERSION_NUMBER <= 0x020c00
361         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
362 #else
363         gnutls_certificate_set_retrieve_function(xcred, gnutls_cert_cb);
364 #endif
365
366         gnutls_dh_set_prime_bits(session, 512);
367
368         if ((r = SSL_connect_nb(session)) < 0) {
369                 g_warning("SSL connection failed (%s)", gnutls_strerror(r));
370                 gnutls_certificate_free_credentials(xcred);
371                 gnutls_deinit(session);
372                 return FALSE;
373         }
374
375         /* Get server's certificate (note: beware of dynamic allocation) */
376         certs = ssl_get_certificate_chain(session, &cert_list_length);
377
378         if (!certs) {
379                 gnutls_certificate_free_credentials(xcred);
380                 gnutls_deinit(session);
381                 return FALSE;
382         }
383
384         if (!ssl_certificate_check_chain(certs, cert_list_length, sockinfo->hostname, sockinfo->port,
385                                          sockinfo->ssl_cert_auto_accept)) {
386                 for (i = 0; i < cert_list_length; i++)
387                         gnutls_x509_crt_deinit(certs[i]);
388                 g_free(certs);
389                 gnutls_certificate_free_credentials(xcred);
390                 gnutls_deinit(session);
391                 return FALSE;
392         }
393
394         for (i = 0; i < cert_list_length; i++)
395                 gnutls_x509_crt_deinit(certs[i]);
396         g_free(certs);
397
398         sockinfo->ssl = session;
399         sockinfo->xcred = xcred;
400         return TRUE;
401 }
402
403 void ssl_done_socket(SockInfo *sockinfo)
404 {
405         if (sockinfo && sockinfo->ssl) {
406                 if (sockinfo->xcred)
407                         gnutls_certificate_free_credentials(sockinfo->xcred);
408                 gnutls_deinit(sockinfo->ssl);
409                 if (sockinfo->client_crt)
410                         gnutls_x509_crt_deinit(sockinfo->client_crt);
411                 if (sockinfo->client_key)
412                         gnutls_x509_privkey_deinit(sockinfo->client_key);
413                 sockinfo->client_key = NULL;
414                 sockinfo->client_crt = NULL;
415                 sockinfo->xcred = NULL;
416                 sockinfo->ssl = NULL;
417         }
418 }
419
420 #endif /* USE_GNUTLS */