fix gcc8 stringop-overflow warning
[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 < 0x030000
67 /* GnuTLS 3.0 introduced new API for certificate callback,
68  * gnutls_certificate_set_retrieve_function2() */
69
70 #if GNUTLS_VERSION_NUMBER <= 0x020c00
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
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
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                 "/etc/pki/tls/certs/ca-bundle.crt",
200                 "/etc/certs/ca-bundle.crt",
201                 "/etc/ssl/ca-bundle.pem",
202                 "/usr/share/ssl/certs/ca-bundle.crt",
203                 "/etc/ssl/certs/ca-certificates.crt",
204                 "/usr/local/ssl/certs/ca-bundle.crt",
205                 "/etc/apache/ssl.crt/ca-bundle.crt",
206                 "/usr/share/curl/curl-ca-bundle.crt",
207                 "/usr/share/curl/curl-ca-bundle.crt",
208                 "/usr/lib/ssl/cert.pem",
209                 NULL};
210         int i;
211 #endif
212
213         /* We honor this environment variable on all platforms. */
214         if (g_getenv("SSL_CERT_FILE"))
215                 return g_getenv("SSL_CERT_FILE");
216
217 #ifndef G_OS_WIN32
218         for (i = 0; cert_files[i]; i++) {
219                 if (is_file_exist(cert_files[i]))
220                         return cert_files[i];
221         }
222         return NULL;
223 #else
224         return w32_get_cert_file();
225 #endif
226 }
227
228 const gchar *claws_ssl_get_cert_dir(void)
229 {
230         if (g_getenv("SSL_CERT_DIR"))
231                 return g_getenv("SSL_CERT_DIR");
232 #ifndef G_OS_WIN32
233         const char *cert_dirs[]={
234                 "/etc/pki/tls/certs",
235                 "/etc/certs",
236                 "/usr/share/ssl/certs",
237                 "/etc/ssl/certs",
238                 "/usr/local/ssl/certs",
239                 "/etc/apache/ssl.crt",
240                 "/usr/share/curl",
241                 "/usr/lib/ssl/certs",
242                 NULL};
243         int i;
244         
245         for (i = 0; cert_dirs[i]; i++) {
246                 if (is_dir_exist(cert_dirs[i]))
247                         return cert_dirs[i];
248         }
249         return NULL;
250 #else
251         return NULL;
252 #endif
253 }
254
255 void ssl_init(void)
256 {
257 #if GNUTLS_VERSION_NUMBER <= 0x020b00
258         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
259 #endif
260 #ifdef HAVE_LIBETPAN
261         mailstream_gnutls_init_not_required();
262 #endif  
263         gnutls_global_init();
264 }
265
266 void ssl_done(void)
267 {
268         gnutls_global_deinit();
269 }
270
271 #ifdef USE_PTHREAD
272 static void *SSL_connect_thread(void *data)
273 {
274         thread_data *td = (thread_data *)data;
275         int result = -1;
276
277         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
278         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
279
280         do {
281                 result = gnutls_handshake(td->ssl);
282         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
283
284         td->done = TRUE; /* let the caller thread join() */
285         return GINT_TO_POINTER(result);
286 }
287 #endif
288
289 static gint SSL_connect_nb(gnutls_session_t ssl)
290 {
291         int result;
292 #ifdef USE_PTHREAD
293         thread_data *td = g_new0(thread_data, 1);
294         pthread_t pt;
295         void *res = NULL;
296         time_t start_time = time(NULL);
297         gboolean killed = FALSE;
298         
299         td->ssl  = ssl;
300         td->done = FALSE;
301         
302         /* try to create a thread to initialize the SSL connection,
303          * fallback to blocking method in case of problem 
304          */
305         if (pthread_create(&pt, NULL, SSL_connect_thread, td) != 0) {
306                 do {
307                         result = gnutls_handshake(td->ssl);
308                 } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
309                 return result;
310         }
311         debug_print("waiting for SSL_connect thread...\n");
312         while(!td->done) {
313                 /* don't let the interface freeze while waiting */
314                 claws_do_idle();
315                 if (time(NULL) - start_time > 30) {
316                         pthread_cancel(pt);
317                         td->done = TRUE;
318                         killed = TRUE;
319                 }
320         }
321
322         /* get the thread's return value and clean its resources */
323         pthread_join(pt, &res);
324         g_free(td);
325         
326         if (killed) {
327                 res = GINT_TO_POINTER(-1);
328         }
329         debug_print("SSL_connect thread returned %d\n", 
330                         GPOINTER_TO_INT(res));
331         
332         return GPOINTER_TO_INT(res);
333 #else /* USE_PTHREAD */
334         do {
335                 result = gnutls_handshake(ssl);
336         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
337 #endif
338 }
339
340 gnutls_x509_crt_t *ssl_get_certificate_chain(gnutls_session_t session, gint *list_len)
341 {
342         const gnutls_datum_t *raw_cert_list;
343         gnutls_x509_crt_t *certs = NULL;
344         gboolean result = TRUE;
345
346         *list_len = -1;
347         if (!session)
348                 return NULL;
349
350         raw_cert_list = gnutls_certificate_get_peers(session, list_len);
351
352         if (raw_cert_list && gnutls_certificate_type_get(session) == GNUTLS_CRT_X509) {
353                 int i = 0;
354
355                 if (*list_len > 128)
356                         *list_len = 128;
357
358                 certs = g_malloc(sizeof(gnutls_x509_crt_t) * (*list_len));
359
360                 for(i = 0 ; i < (*list_len) ; i++) {
361                         int r;
362
363                         gnutls_x509_crt_init(&certs[i]);
364                         r = gnutls_x509_crt_import(certs[i], &raw_cert_list[i], GNUTLS_X509_FMT_DER);
365                         if (r < 0) {
366                                 g_warning("cert get failure: %d %s", r, gnutls_strerror(r));
367
368                                 result = FALSE;
369                                 i--;
370                                 break;
371                         }
372                 }
373                 if (!result) {
374                         for (; i >= 0; i--)
375                                 gnutls_x509_crt_deinit(certs[i]);
376
377                         g_free(certs);
378                         *list_len = -1;
379
380                         return NULL;
381                 }
382         }
383
384         return certs;
385 }
386
387 gboolean ssl_init_socket(SockInfo *sockinfo)
388 {
389         gnutls_session_t session;
390         int r, i;
391         unsigned int cert_list_length;
392         gnutls_x509_crt_t *certs = NULL;
393         gnutls_certificate_credentials_t xcred;
394
395         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
396                 return FALSE;
397
398         r = gnutls_init(&session, GNUTLS_CLIENT);
399         if (session == NULL || r != 0)
400                 return FALSE;
401
402         if (sockinfo->gnutls_priority && strlen(sockinfo->gnutls_priority)) {
403                 r = gnutls_priority_set_direct(session, sockinfo->gnutls_priority, NULL);
404                 debug_print("Setting GnuTLS priority to %s, status = %d\n",
405                             sockinfo->gnutls_priority, r);
406         }
407         else {
408                 gnutls_priority_set_direct(session, DEFAULT_GNUTLS_PRIORITY, NULL);
409         }
410
411         gnutls_record_disable_padding(session);
412
413         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
414
415         if (claws_ssl_get_cert_file()) {
416                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
417                 if (r < 0)
418                         g_warning("Can't read SSL_CERT_FILE '%s': %s",
419                                 claws_ssl_get_cert_file(), 
420                                 gnutls_strerror(r));
421         } else {
422                 debug_print("Can't find SSL ca-certificates file\n");
423         }
424         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
425
426         gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) GINT_TO_POINTER(sockinfo->sock));
427
428         gnutls_session_set_ptr(session, sockinfo);
429
430 #if GNUTLS_VERSION_NUMBER < 0x030000
431 #  if GNUTLS_VERSION_NUMBER <= 0x020c00
432         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
433 #  else
434         gnutls_certificate_set_retrieve_function(xcred, gnutls_cert_cb);
435 #  endif
436 #else
437         debug_print("setting certificate callback function\n");
438         gnutls_certificate_set_retrieve_function2(xcred, gnutls_cert_cb);
439 #endif
440
441 #if GNUTLS_VERSION_NUMBER < 0x030107
442         /* Starting from GnuTLS 3.1.7, minimal size of the DH prime is
443          * set by the priority string. By default ("NORMAL"), it is 1008
444          * as of GnuTLS 3.3.0. */
445         gnutls_dh_set_prime_bits(session, 1008);
446 #endif
447
448         if ((r = SSL_connect_nb(session)) < 0) {
449                 g_warning("SSL/TLS connection failed (%s)", gnutls_strerror(r));
450                 gnutls_certificate_free_credentials(xcred);
451                 gnutls_deinit(session);
452                 return FALSE;
453         }
454
455         /* Get server's certificate (note: beware of dynamic allocation) */
456         certs = ssl_get_certificate_chain(session, &cert_list_length);
457
458         if (!certs) {
459                 gnutls_certificate_free_credentials(xcred);
460                 gnutls_deinit(session);
461                 return FALSE;
462         }
463
464         if (!ssl_certificate_check_chain(certs, cert_list_length, sockinfo->hostname, sockinfo->port,
465                                          sockinfo->ssl_cert_auto_accept)) {
466                 for (i = 0; i < cert_list_length; i++)
467                         gnutls_x509_crt_deinit(certs[i]);
468                 g_free(certs);
469                 gnutls_certificate_free_credentials(xcred);
470                 gnutls_deinit(session);
471                 return FALSE;
472         }
473
474         for (i = 0; i < cert_list_length; i++)
475                 gnutls_x509_crt_deinit(certs[i]);
476         g_free(certs);
477
478         sockinfo->ssl = session;
479         sockinfo->xcred = xcred;
480         return TRUE;
481 }
482
483 void ssl_done_socket(SockInfo *sockinfo)
484 {
485         if (sockinfo && sockinfo->ssl) {
486                 if (sockinfo->xcred)
487                         gnutls_certificate_free_credentials(sockinfo->xcred);
488                 gnutls_deinit(sockinfo->ssl);
489 #if GNUTLS_VERSION_NUMBER < 0x030000
490                 if (sockinfo->client_crt)
491                         gnutls_x509_crt_deinit(sockinfo->client_crt);
492                 if (sockinfo->client_key)
493                         gnutls_x509_privkey_deinit(sockinfo->client_key);
494                 sockinfo->client_key = NULL;
495                 sockinfo->client_crt = NULL;
496 #else
497                 gnutls_pcert_deinit(&sockinfo->client_crt);
498                 gnutls_privkey_deinit(sockinfo->client_key);
499 #endif
500                 sockinfo->client_key = NULL;
501                 sockinfo->xcred = NULL;
502                 sockinfo->ssl = NULL;
503         }
504 }
505
506 #endif /* USE_GNUTLS */