1c7c335ba2dbe2214789398fbb36898ff84556c4
[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 gboolean ssl_init_socket(SockInfo *sockinfo)
259 {
260         return ssl_init_socket_with_method(sockinfo, SSL_METHOD_SSLv23);
261 }
262
263 gnutls_x509_crt_t *ssl_get_certificate_chain(gnutls_session_t session, gint *list_len)
264 {
265         const gnutls_datum_t *raw_cert_list;
266         gnutls_x509_crt_t *certs = NULL;
267         gboolean result = TRUE;
268
269         *list_len = -1;
270         if (!session)
271                 return NULL;
272
273         raw_cert_list = gnutls_certificate_get_peers(session, list_len);
274
275         if (raw_cert_list && gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
276                 int i = 0;
277
278                 certs = g_malloc(sizeof(gnutls_x509_crt_t) * (*list_len));
279
280                 for(i = 0 ; i < (*list_len) ; i++) {
281                         int r;
282
283                         gnutls_x509_crt_init(&certs[i]);
284                         r = gnutls_x509_crt_import(certs[i], &raw_cert_list[i], GNUTLS_X509_FMT_DER);
285                         if (r < 0) {
286                                 g_warning("cert get failure: %d %s\n", r, gnutls_strerror(r));
287
288                                 result = FALSE;
289                                 i--;
290                                 break;
291                         }
292                 }
293                 if (!result) {
294                         for (; i >= 0; i--)
295                                 gnutls_x509_crt_deinit(certs[i]);
296
297                         g_free(certs);
298                         *list_len = -1;
299
300                         return NULL;
301                 }
302         }
303
304         return certs;
305 }
306
307 gboolean ssl_init_socket_with_method(SockInfo *sockinfo, SSLMethod method)
308 {
309         gnutls_session_t session;
310         int r, i;
311         unsigned int cert_list_length;
312         gnutls_x509_crt_t *certs = NULL;
313         gnutls_certificate_credentials_t xcred;
314
315         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
316                 return FALSE;
317
318         r = gnutls_init(&session, GNUTLS_CLIENT);
319         if (session == NULL || r != 0)
320                 return FALSE;
321
322         if (sockinfo->gnutls_priority && strlen(sockinfo->gnutls_priority)) {
323                 r = gnutls_priority_set_direct(session, sockinfo->gnutls_priority, NULL);
324                 debug_print("Setting GnuTLS priority to %s, status = %d\n",
325                             sockinfo->gnutls_priority, r);
326         }
327         else {
328                 if (method == 0)
329                         gnutls_priority_set_direct(session, "NORMAL:-VERS-TLS1.0:-VERS-TLS1.1:-VERS-TLS1.2", NULL);
330                 else
331                         gnutls_priority_set_direct(session, "NORMAL", NULL);
332         }
333         gnutls_record_disable_padding(session);
334
335         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
336
337         if (claws_ssl_get_cert_file()) {
338                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
339                 if (r < 0)
340                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
341                                 claws_ssl_get_cert_file(), 
342                                 gnutls_strerror(r));
343         } else {
344                 debug_print("Can't find SSL ca-certificates file\n");
345         }
346         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
347
348         gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) GINT_TO_POINTER(sockinfo->sock));
349         gnutls_session_set_ptr(session, sockinfo);
350 #if GNUTLS_VERSION_NUMBER <= 0x020c00
351         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
352 #else
353         gnutls_certificate_set_retrieve_function(xcred, gnutls_cert_cb);
354 #endif
355
356         gnutls_dh_set_prime_bits(session, 512);
357
358         if ((r = SSL_connect_nb(session)) < 0) {
359                 g_warning("SSL connection failed (%s)", gnutls_strerror(r));
360                 gnutls_certificate_free_credentials(xcred);
361                 gnutls_deinit(session);
362                 return FALSE;
363         }
364
365         /* Get server's certificate (note: beware of dynamic allocation) */
366         certs = ssl_get_certificate_chain(session, &cert_list_length);
367
368         if (!certs) {
369                 gnutls_certificate_free_credentials(xcred);
370                 gnutls_deinit(session);
371                 return FALSE;
372         }
373
374         if (!ssl_certificate_check_chain(certs, cert_list_length, sockinfo->hostname, sockinfo->port,
375                                          sockinfo->ssl_cert_auto_accept)) {
376                 for (i = 0; i < cert_list_length; i++)
377                         gnutls_x509_crt_deinit(certs[i]);
378                 g_free(certs);
379                 gnutls_certificate_free_credentials(xcred);
380                 gnutls_deinit(session);
381                 return FALSE;
382         }
383
384         for (i = 0; i < cert_list_length; i++)
385                 gnutls_x509_crt_deinit(certs[i]);
386         g_free(certs);
387
388         sockinfo->ssl = session;
389         sockinfo->xcred = xcred;
390         return TRUE;
391 }
392
393 void ssl_done_socket(SockInfo *sockinfo)
394 {
395         if (sockinfo && sockinfo->ssl) {
396                 if (sockinfo->xcred)
397                         gnutls_certificate_free_credentials(sockinfo->xcred);
398                 gnutls_deinit(sockinfo->ssl);
399                 if (sockinfo->client_crt)
400                         gnutls_x509_crt_deinit(sockinfo->client_crt);
401                 if (sockinfo->client_key)
402                         gnutls_x509_privkey_deinit(sockinfo->client_key);
403                 sockinfo->client_key = NULL;
404                 sockinfo->client_crt = NULL;
405                 sockinfo->xcred = NULL;
406                 sockinfo->ssl = NULL;
407         }
408 }
409
410 #endif /* USE_GNUTLS */