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 < 0x030000
67 /* GnuTLS 3.0 introduced new API for certificate callback,
68  * gnutls_certificate_set_retrieve_function2() */
69 
70 #if GNUTLS_VERSION_NUMBER <= 0x020c00
gnutls_client_cert_cb(gnutls_session_t session,const gnutls_datum_t * req_ca_rdn,int nreqs,const gnutls_pk_algorithm_t * sign_algos,int sign_algos_length,gnutls_retr_st * st)71 static int gnutls_client_cert_cb(gnutls_session_t session,
72                                const gnutls_datum_t *req_ca_rdn, int nreqs,
73                                const gnutls_pk_algorithm_t *sign_algos,
74                                int sign_algos_length, gnutls_retr_st *st)
75 #else
76 static int gnutls_cert_cb(gnutls_session_t session,
77                                const gnutls_datum_t *req_ca_rdn, int nreqs,
78                                const gnutls_pk_algorithm_t *sign_algos,
79                                int sign_algos_length, gnutls_retr2_st *st)
80 #endif /* GNUTLS_VERSION_NUMBER <= 0x020c00 */
81 {
82 	SSLClientCertHookData hookdata;
83 	SockInfo *sockinfo = (SockInfo *)gnutls_session_get_ptr(session);
84 	gnutls_certificate_type_t type = gnutls_certificate_type_get(session);
85 	gnutls_x509_crt_t crt;
86 	gnutls_x509_privkey_t key;
87 
88 	st->ncerts = 0;
89 
90 	hookdata.account = sockinfo->account;
91 	hookdata.cert_path = NULL;
92 	hookdata.password = NULL;
93 	hookdata.is_smtp = sockinfo->is_smtp;
94 	hooks_invoke(SSLCERT_GET_CLIENT_CERT_HOOKLIST, &hookdata);
95 
96 	if (hookdata.cert_path == NULL) {
97 		g_free(hookdata.password);
98 		return 0;
99 	}
100 
101 	sockinfo->client_crt = ssl_certificate_get_x509_from_pem_file(hookdata.cert_path);
102 	sockinfo->client_key = ssl_certificate_get_pkey_from_pem_file(hookdata.cert_path);
103 	if (!(sockinfo->client_crt && sockinfo->client_key)) {
104 		/* try pkcs12 format */
105 		ssl_certificate_get_x509_and_pkey_from_p12_file(hookdata.cert_path, hookdata.password,
106 			&crt, &key);
107 		sockinfo->client_crt = crt;
108 		sockinfo->client_key = key;
109 	}
110 
111 	if (type == GNUTLS_CRT_X509 && sockinfo->client_crt && sockinfo->client_key) {
112 		st->ncerts = 1;
113 #if GNUTLS_VERSION_NUMBER <= 0x020c00
114 		st->type = type;
115 #else
116 		st->key_type = type;
117 #endif
118 		st->cert.x509 = &(sockinfo->client_crt);
119 		st->key.x509 = sockinfo->client_key;
120 		st->deinit_all = 0;
121 		g_free(hookdata.password);
122 		return 0;
123 	}
124 	g_free(hookdata.password);
125 	return 0;
126 }
127 
128 #else /* GNUTLS_VERSION_NUMBER < 0x030000 */
129 
gnutls_cert_cb(gnutls_session_t session,const gnutls_datum_t * req_ca_rdn,int nreqs,const gnutls_pk_algorithm_t * pk_algos,int pk_algos_length,gnutls_pcert_st ** pcert,unsigned int * pcert_length,gnutls_privkey_t * privkey)130 static int gnutls_cert_cb(gnutls_session_t session,
131 		const gnutls_datum_t *req_ca_rdn,
132 		int nreqs,
133 		const gnutls_pk_algorithm_t *pk_algos,
134 		int pk_algos_length,
135 		gnutls_pcert_st **pcert,
136 		unsigned int *pcert_length,
137 		gnutls_privkey_t *privkey)
138 {
139 	SSLClientCertHookData hookdata;
140 	SockInfo *sockinfo = (SockInfo *)gnutls_session_get_ptr(session);
141 	gnutls_datum_t tmp;
142 	int r;
143 
144 	hookdata.account = sockinfo->account;
145 	hookdata.cert_path = NULL;
146 	hookdata.password = NULL;
147 	hookdata.is_smtp = sockinfo->is_smtp;
148 	hooks_invoke(SSLCERT_GET_CLIENT_CERT_HOOKLIST, &hookdata);
149 
150 	if (hookdata.cert_path == NULL) {
151 		g_free(hookdata.password);
152 		return 0;
153 	}
154 
155 	if ((r = gnutls_load_file(hookdata.cert_path, &tmp)) != 0) {
156 		debug_print("couldn't load file '%s': %d\n",
157 				hookdata.cert_path, r);
158 		g_free(hookdata.password);
159 		return 0;
160 	}
161 	debug_print("trying to load client cert+key from file '%s'\n",
162 			hookdata.cert_path);
163 
164 	if ((r = gnutls_pcert_import_x509_raw(&sockinfo->client_crt, &tmp,
165 				GNUTLS_X509_FMT_PEM, 0)) != 0) {
166 		debug_print("couldn't import x509 cert from PEM file '%s': %d\n",
167 				hookdata.cert_path, r);
168 		g_free(hookdata.password);
169 		return 0;
170 	}
171 	debug_print("loaded client certificate...\n");
172 
173 	gnutls_privkey_init(&sockinfo->client_key);
174 	if ((r = gnutls_privkey_import_x509_raw(sockinfo->client_key, &tmp,
175 				GNUTLS_X509_FMT_PEM, hookdata.password, 0)) != 0) {
176 		debug_print("couldn't import x509 pkey from PEM file '%s': %d\n",
177 				hookdata.cert_path, r);
178 		g_free(hookdata.password);
179 		gnutls_privkey_deinit(sockinfo->client_key);
180 		return 0;
181 	}
182 	debug_print("loaded client private key...\n");
183 
184 	gnutls_free(tmp.data);
185 
186 	*pcert_length = 1;
187 	*pcert = &sockinfo->client_crt;
188 	*privkey = sockinfo->client_key;
189 
190 	return 0;
191 }
192 #endif /* GNUTLS_VERSION_NUMBER < 0x030000 */
193 
claws_ssl_get_cert_file(void)194 const gchar *claws_ssl_get_cert_file(void)
195 {
196 #ifndef G_OS_WIN32
197 	const char *cert_files[]={
198 		"/etc/ssl/cert.pem",
199 		// Also search in LOCALBASE directory to
200 		// workaround potential lack of /etc symlink
201 		"%%LOCALBASE%%/share/certs/ca-root-nss.crt",
202 		"/etc/pki/tls/certs/ca-bundle.crt",
203 		"/etc/certs/ca-bundle.crt",
204 		"/etc/ssl/ca-bundle.pem",
205 		"/usr/share/ssl/certs/ca-bundle.crt",
206 		"/etc/ssl/certs/ca-certificates.crt",
207 		"/usr/local/ssl/certs/ca-bundle.crt",
208 		"/etc/apache/ssl.crt/ca-bundle.crt",
209 		"/usr/share/curl/curl-ca-bundle.crt",
210 		"/usr/share/curl/curl-ca-bundle.crt",
211 		"/usr/lib/ssl/cert.pem",
212 		NULL};
213 	int i;
214 #endif
215 
216 	/* We honor this environment variable on all platforms. */
217 	if (g_getenv("SSL_CERT_FILE"))
218 		return g_getenv("SSL_CERT_FILE");
219 
220 #ifndef G_OS_WIN32
221 	for (i = 0; cert_files[i]; i++) {
222 		if (is_file_exist(cert_files[i]))
223 			return cert_files[i];
224 	}
225 	return NULL;
226 #else
227 	return w32_get_cert_file();
228 #endif
229 }
230 
claws_ssl_get_cert_dir(void)231 const gchar *claws_ssl_get_cert_dir(void)
232 {
233 	if (g_getenv("SSL_CERT_DIR"))
234 		return g_getenv("SSL_CERT_DIR");
235 #ifndef G_OS_WIN32
236 	const char *cert_dirs[]={
237 		"/etc/pki/tls/certs",
238 		"/etc/certs",
239 		"/usr/share/ssl/certs",
240 		"/etc/ssl/certs",
241 		"/usr/local/ssl/certs",
242 		"/etc/apache/ssl.crt",
243 		"/usr/share/curl",
244 		"/usr/lib/ssl/certs",
245 		NULL};
246 	int i;
247 
248 	for (i = 0; cert_dirs[i]; i++) {
249 		if (is_dir_exist(cert_dirs[i]))
250 			return cert_dirs[i];
251 	}
252 	return NULL;
253 #else
254 	return NULL;
255 #endif
256 }
257 
ssl_init(void)258 void ssl_init(void)
259 {
260 #if GNUTLS_VERSION_NUMBER <= 0x020b00
261 	gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
262 #endif
263 #ifdef HAVE_LIBETPAN
264 	mailstream_gnutls_init_not_required();
265 #endif
266 	gnutls_global_init();
267 }
268 
ssl_done(void)269 void ssl_done(void)
270 {
271 	gnutls_global_deinit();
272 }
273 
274 #ifdef USE_PTHREAD
SSL_connect_thread(void * data)275 static void *SSL_connect_thread(void *data)
276 {
277 	thread_data *td = (thread_data *)data;
278 	int result = -1;
279 
280 	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
281 	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
282 
283 	do {
284 		result = gnutls_handshake(td->ssl);
285 	} while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
286 
287 	td->done = TRUE; /* let the caller thread join() */
288 	return GINT_TO_POINTER(result);
289 }
290 #endif
291 
SSL_connect_nb(gnutls_session_t ssl)292 static gint SSL_connect_nb(gnutls_session_t ssl)
293 {
294 	int result;
295 #ifdef USE_PTHREAD
296 	thread_data *td = g_new0(thread_data, 1);
297 	pthread_t pt;
298 	void *res = NULL;
299 	time_t start_time = time(NULL);
300 	gboolean killed = FALSE;
301 
302 	td->ssl  = ssl;
303 	td->done = FALSE;
304 
305 	/* try to create a thread to initialize the SSL connection,
306 	 * fallback to blocking method in case of problem
307 	 */
308 	if (pthread_create(&pt, NULL, SSL_connect_thread, td) != 0) {
309 		do {
310 			result = gnutls_handshake(td->ssl);
311 		} while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
312 		return result;
313 	}
314 	debug_print("waiting for SSL_connect thread...\n");
315 	while(!td->done) {
316 		/* don't let the interface freeze while waiting */
317 		claws_do_idle();
318 		if (time(NULL) - start_time > 30) {
319 			pthread_cancel(pt);
320 			td->done = TRUE;
321 			killed = TRUE;
322 		}
323 	}
324 
325 	/* get the thread's return value and clean its resources */
326 	pthread_join(pt, &res);
327 	g_free(td);
328 
329 	if (killed) {
330 		res = GINT_TO_POINTER(-1);
331 	}
332 	debug_print("SSL_connect thread returned %d\n",
333 			GPOINTER_TO_INT(res));
334 
335 	return GPOINTER_TO_INT(res);
336 #else /* USE_PTHREAD */
337 	do {
338 		result = gnutls_handshake(ssl);
339 	} while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
340 #endif
341 }
342 
ssl_get_certificate_chain(gnutls_session_t session,gint * list_len)343 gnutls_x509_crt_t *ssl_get_certificate_chain(gnutls_session_t session, gint *list_len)
344 {
345 	const gnutls_datum_t *raw_cert_list;
346 	gnutls_x509_crt_t *certs = NULL;
347 	gboolean result = TRUE;
348 
349 	*list_len = -1;
350 	if (!session)
351 		return NULL;
352 
353 	raw_cert_list = gnutls_certificate_get_peers(session, list_len);
354 
355 	if (raw_cert_list && gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
356 		int i = 0;
357 
358 		if (*list_len > 128)
359 			*list_len = 128;
360 
361 		certs = g_malloc(sizeof(gnutls_x509_crt_t) * (*list_len));
362 
363 		for(i = 0 ; i < (*list_len) ; i++) {
364 			int r;
365 
366 			gnutls_x509_crt_init(&certs[i]);
367 			r = gnutls_x509_crt_import(certs[i], &raw_cert_list[i], GNUTLS_X509_FMT_DER);
368 			if (r < 0) {
369 				g_warning("cert get failure: %d %s", r, gnutls_strerror(r));
370 
371 				result = FALSE;
372 				i--;
373 				break;
374 			}
375 		}
376 		if (!result) {
377 			for (; i >= 0; i--)
378 				gnutls_x509_crt_deinit(certs[i]);
379 
380 			g_free(certs);
381 			*list_len = -1;
382 
383 			return NULL;
384 		}
385 	}
386 
387 	return certs;
388 }
389 
ssl_init_socket(SockInfo * sockinfo)390 gboolean ssl_init_socket(SockInfo *sockinfo)
391 {
392 	gnutls_session_t session;
393 	int r, i;
394 	unsigned int cert_list_length;
395 	gnutls_x509_crt_t *certs = NULL;
396 	gnutls_certificate_credentials_t xcred;
397 
398 	if (gnutls_certificate_allocate_credentials (&xcred) != 0)
399 		return FALSE;
400 
401 	r = gnutls_init(&session, GNUTLS_CLIENT);
402 	if (session == NULL || r != 0)
403 		return FALSE;
404 
405 	if (sockinfo->gnutls_priority && strlen(sockinfo->gnutls_priority)) {
406 		r = gnutls_priority_set_direct(session, sockinfo->gnutls_priority, NULL);
407 		debug_print("Setting GnuTLS priority to %s, status = %d\n",
408 			    sockinfo->gnutls_priority, r);
409 	}
410 	else {
411 		gnutls_priority_set_direct(session, DEFAULT_GNUTLS_PRIORITY, NULL);
412 	}
413 
414 	gnutls_record_disable_padding(session);
415 
416 	/* If we have a host name, rather than a numerical IP address, tell
417 	 * gnutls to send it in the server name identification extension field,
418 	 * to give the server a chance to select the correct certificate in the
419 	 * virtual hosting case where multiple domain names are hosted on the
420 	 * same IP address. */
421 	if (sockinfo->use_tls_sni &&
422 			sockinfo->hostname != NULL &&
423 			!is_numeric_host_address(sockinfo->hostname)) {
424 		r = gnutls_server_name_set(session, GNUTLS_NAME_DNS,
425 				sockinfo->hostname, strlen(sockinfo->hostname));
426 		debug_print("Set GnuTLS session server name indication to %s, status = %d\n",
427 			    sockinfo->hostname, r);
428 	}
429 
430 	gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
431 
432 	if (claws_ssl_get_cert_file()) {
433 		r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
434 		if (r < 0)
435 			g_warning("Can't read SSL_CERT_FILE '%s': %s",
436 				claws_ssl_get_cert_file(),
437 				gnutls_strerror(r));
438 	} else {
439 		debug_print("Can't find SSL ca-certificates file\n");
440 	}
441 	gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
442 
443 	gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) GINT_TO_POINTER(sockinfo->sock));
444 
445 	gnutls_session_set_ptr(session, sockinfo);
446 
447 #if GNUTLS_VERSION_NUMBER < 0x030000
448 #  if GNUTLS_VERSION_NUMBER <= 0x020c00
449 	gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
450 #  else
451 	gnutls_certificate_set_retrieve_function(xcred, gnutls_cert_cb);
452 #  endif
453 #else
454 	debug_print("setting certificate callback function\n");
455 	gnutls_certificate_set_retrieve_function2(xcred, gnutls_cert_cb);
456 #endif
457 
458 #if GNUTLS_VERSION_NUMBER < 0x030107
459 	/* Starting from GnuTLS 3.1.7, minimal size of the DH prime is
460 	 * set by the priority string. By default ("NORMAL"), it is 1008
461 	 * as of GnuTLS 3.3.0. */
462 	gnutls_dh_set_prime_bits(session, 1008);
463 #endif
464 
465 	if ((r = SSL_connect_nb(session)) < 0) {
466 		g_warning("SSL/TLS connection failed (%s)", gnutls_strerror(r));
467 		gnutls_certificate_free_credentials(xcred);
468 		gnutls_deinit(session);
469 		return FALSE;
470 	}
471 
472 	/* Get server's certificate (note: beware of dynamic allocation) */
473 	certs = ssl_get_certificate_chain(session, &cert_list_length);
474 
475 	if (!certs) {
476 		gnutls_certificate_free_credentials(xcred);
477 		gnutls_deinit(session);
478 		return FALSE;
479 	}
480 
481 	if (!ssl_certificate_check_chain(certs, cert_list_length, sockinfo->hostname, sockinfo->port,
482 					 sockinfo->ssl_cert_auto_accept)) {
483 		for (i = 0; i < cert_list_length; i++)
484 			gnutls_x509_crt_deinit(certs[i]);
485 		g_free(certs);
486 		gnutls_certificate_free_credentials(xcred);
487 		gnutls_deinit(session);
488 		return FALSE;
489 	}
490 
491 	for (i = 0; i < cert_list_length; i++)
492 		gnutls_x509_crt_deinit(certs[i]);
493 	g_free(certs);
494 
495 	sockinfo->ssl = session;
496 	sockinfo->xcred = xcred;
497 	return TRUE;
498 }
499 
ssl_done_socket(SockInfo * sockinfo)500 void ssl_done_socket(SockInfo *sockinfo)
501 {
502 	if (sockinfo && sockinfo->ssl) {
503 		if (sockinfo->xcred)
504 			gnutls_certificate_free_credentials(sockinfo->xcred);
505 		gnutls_deinit(sockinfo->ssl);
506 #if GNUTLS_VERSION_NUMBER < 0x030000
507 		if (sockinfo->client_crt)
508 			gnutls_x509_crt_deinit(sockinfo->client_crt);
509 		if (sockinfo->client_key)
510 			gnutls_x509_privkey_deinit(sockinfo->client_key);
511 		sockinfo->client_key = NULL;
512 		sockinfo->client_crt = NULL;
513 #else
514 		gnutls_pcert_deinit(&sockinfo->client_crt);
515 		gnutls_privkey_deinit(sockinfo->client_key);
516 #endif
517 		sockinfo->client_key = NULL;
518 		sockinfo->xcred = NULL;
519 		sockinfo->ssl = NULL;
520 	}
521 }
522 
523 #endif /* USE_GNUTLS */
524