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