51e64c14b08e7eea06ce0342fea22b9f6f0b169d
[claws.git] / src / common / ssl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2009 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 #endif
23
24 #ifdef USE_GNUTLS
25 #include "defs.h"
26
27 #include <stdlib.h>
28 #include <glib.h>
29 #include <glib/gi18n.h>
30 #include <errno.h>
31 #include <pthread.h>
32 #include <gcrypt.h>
33 GCRY_THREAD_OPTION_PTHREAD_IMPL;
34
35 #include "claws.h"
36 #include "utils.h"
37 #include "ssl.h"
38 #include "ssl_certificate.h"
39 #include "hooks.h"
40
41 #ifdef HAVE_LIBETPAN
42 #include <libetpan/mailstream_ssl.h>
43 #endif
44
45 #ifdef USE_PTHREAD
46 #include <pthread.h>
47 #endif
48
49 #ifdef USE_PTHREAD
50 typedef struct _thread_data {
51         gnutls_session ssl;
52         gboolean done;
53 } thread_data;
54 #endif
55
56 static int gnutls_client_cert_cb(gnutls_session session,
57                                const gnutls_datum *req_ca_rdn, int nreqs,
58                                const gnutls_pk_algorithm *sign_algos,
59                                int sign_algos_length, gnutls_retr_st *st)
60 {
61         SSLClientCertHookData hookdata;
62         SockInfo *sockinfo = (SockInfo *)gnutls_session_get_ptr(session);
63         gnutls_certificate_type type = gnutls_certificate_type_get(session);
64         gnutls_x509_crt crt;
65         gnutls_x509_privkey key;
66
67         st->ncerts = 0;
68
69         hookdata.account = sockinfo->account;
70         hookdata.cert_path = NULL;
71         hookdata.password = NULL;
72         hookdata.is_smtp = sockinfo->is_smtp;
73         hooks_invoke(SSLCERT_GET_CLIENT_CERT_HOOKLIST, &hookdata);      
74
75         if (hookdata.cert_path == NULL)
76                 return 0;
77
78         sockinfo->client_crt = ssl_certificate_get_x509_from_pem_file(hookdata.cert_path);
79         sockinfo->client_key = ssl_certificate_get_pkey_from_pem_file(hookdata.cert_path);
80         if (!(sockinfo->client_crt && sockinfo->client_key)) {
81                 /* try pkcs12 format */
82                 ssl_certificate_get_x509_and_pkey_from_p12_file(hookdata.cert_path, hookdata.password, 
83                         &crt, &key);
84                 sockinfo->client_crt = crt;
85                 sockinfo->client_key = key;
86         }
87
88         if (type == GNUTLS_CRT_X509 && sockinfo->client_crt && sockinfo->client_key) {
89                 st->ncerts = 1;
90                 st->type = type;
91                 st->cert.x509 = &(sockinfo->client_crt);
92                 st->key.x509 = sockinfo->client_key;
93                 st->deinit_all = 0;
94                 return 0;
95         }
96         return 0;
97 }
98
99 const gchar *claws_ssl_get_cert_file(void)
100 {
101         const char *cert_files[]={
102                 "/etc/pki/tls/certs/ca-bundle.crt",
103                 "/etc/certs/ca-bundle.crt",
104                 "/usr/share/ssl/certs/ca-bundle.crt",
105                 "/etc/ssl/certs/ca-certificates.crt",
106                 "/usr/local/ssl/certs/ca-bundle.crt",
107                 "/etc/apache/ssl.crt/ca-bundle.crt",
108                 "/usr/share/curl/curl-ca-bundle.crt",
109                 "/usr/share/curl/curl-ca-bundle.crt",
110                 "/usr/lib/ssl/cert.pem",
111                 NULL};
112         int i;
113         
114         if (g_getenv("SSL_CERT_FILE"))
115                 return g_getenv("SSL_CERT_FILE");
116 #ifndef G_OS_WIN32
117         for (i = 0; cert_files[i]; i++) {
118                 if (is_file_exist(cert_files[i]))
119                         return cert_files[i];
120         }
121         return NULL;
122 #else
123         return get_cert_file();
124 #endif
125 }
126
127 const gchar *claws_ssl_get_cert_dir(void)
128 {
129         const char *cert_dirs[]={
130                 "/etc/pki/tls/certs",
131                 "/etc/certs",
132                 "/usr/share/ssl/certs",
133                 "/etc/ssl/certs",
134                 "/usr/local/ssl/certs",
135                 "/etc/apache/ssl.crt",
136                 "/usr/share/curl",
137                 "/usr/lib/ssl/certs",
138                 NULL};
139         int i;
140         
141         if (g_getenv("SSL_CERT_DIR"))
142                 return g_getenv("SSL_CERT_DIR");
143 #ifndef G_OS_WIN32
144         for (i = 0; cert_dirs[i]; i++) {
145                 if (is_dir_exist(cert_dirs[i]))
146                         return cert_dirs[i];
147         }
148         return NULL;
149 #else
150         return "put_what_s_needed_here";
151 #endif
152 }
153
154 void ssl_init(void)
155 {
156         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
157 #ifdef HAVE_LIBETPAN
158         mailstream_gnutls_init_not_required();
159 #endif  
160         gnutls_global_init();
161 }
162
163 void ssl_done(void)
164 {
165         gnutls_global_deinit();
166 }
167
168 #ifdef USE_PTHREAD
169 static void *SSL_connect_thread(void *data)
170 {
171         thread_data *td = (thread_data *)data;
172         int result = -1;
173
174         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
175         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
176
177         do {
178                 result = gnutls_handshake(td->ssl);
179         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
180
181         td->done = TRUE; /* let the caller thread join() */
182         return GINT_TO_POINTER(result);
183 }
184 #endif
185
186 static gint SSL_connect_nb(gnutls_session ssl)
187 {
188         int result;
189 #ifdef USE_PTHREAD
190         thread_data *td = g_new0(thread_data, 1);
191         pthread_t pt;
192         pthread_attr_t pta;
193         void *res = NULL;
194         time_t start_time = time(NULL);
195         gboolean killed = FALSE;
196         
197         td->ssl  = ssl;
198         td->done = FALSE;
199         
200         /* try to create a thread to initialize the SSL connection,
201          * fallback to blocking method in case of problem 
202          */
203         if (pthread_attr_init(&pta) != 0 ||
204             pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE) != 0 ||
205             pthread_create(&pt, &pta, SSL_connect_thread, td) != 0) {
206                 do {
207                         result = gnutls_handshake(td->ssl);
208                 } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
209                 return result;
210         }
211         debug_print("waiting for SSL_connect thread...\n");
212         while(!td->done) {
213                 /* don't let the interface freeze while waiting */
214                 claws_do_idle();
215                 if (time(NULL) - start_time > 30) {
216                         pthread_cancel(pt);
217                         td->done = TRUE;
218                         killed = TRUE;
219                 }
220         }
221
222         /* get the thread's return value and clean its resources */
223         pthread_join(pt, &res);
224         g_free(td);
225         
226         if (killed) {
227                 res = GINT_TO_POINTER(-1);
228         }
229         debug_print("SSL_connect thread returned %d\n", 
230                         GPOINTER_TO_INT(res));
231         
232         return GPOINTER_TO_INT(res);
233 #else /* USE_PTHREAD */
234         do {
235                 result = gnutls_handshake(ssl);
236         } while (result == GNUTLS_E_AGAIN || result == GNUTLS_E_INTERRUPTED);
237 #endif
238 }
239
240 gboolean ssl_init_socket(SockInfo *sockinfo)
241 {
242         return ssl_init_socket_with_method(sockinfo, SSL_METHOD_SSLv23);
243 }
244
245 gboolean ssl_init_socket_with_method(SockInfo *sockinfo, SSLMethod method)
246 {
247         gnutls_session session;
248         int r;
249         const int cipher_prio[] = { GNUTLS_CIPHER_AES_128_CBC,
250                                 GNUTLS_CIPHER_3DES_CBC,
251                                 GNUTLS_CIPHER_AES_256_CBC,
252                                 GNUTLS_CIPHER_ARCFOUR_128, 0 };
253         const int kx_prio[] = { GNUTLS_KX_DHE_RSA,
254                            GNUTLS_KX_RSA, 
255                            GNUTLS_KX_DHE_DSS, 0 };
256         const int mac_prio[] = { GNUTLS_MAC_SHA1,
257                                 GNUTLS_MAC_MD5, 0 };
258         const int proto_prio[] = { GNUTLS_TLS1,
259                                   GNUTLS_SSL3, 0 };
260         const gnutls_datum *raw_cert_list;
261         unsigned int raw_cert_list_length;
262         gnutls_x509_crt cert = NULL;
263         guint status;
264         gnutls_certificate_credentials_t xcred;
265
266         if (gnutls_certificate_allocate_credentials (&xcred) != 0)
267                 return FALSE;
268
269         r = gnutls_init(&session, GNUTLS_CLIENT);
270         if (session == NULL || r != 0)
271                 return FALSE;
272   
273         gnutls_priority_set_direct(session, "NORMAL:%COMPAT", NULL);
274         gnutls_protocol_set_priority (session, proto_prio);
275         gnutls_cipher_set_priority (session, cipher_prio);
276         gnutls_kx_set_priority (session, kx_prio);
277         gnutls_mac_set_priority (session, mac_prio);
278
279         gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, xcred);
280
281         if (claws_ssl_get_cert_file()) {
282                 r = gnutls_certificate_set_x509_trust_file(xcred, claws_ssl_get_cert_file(),  GNUTLS_X509_FMT_PEM);
283                 if (r < 0)
284                         g_warning("Can't read SSL_CERT_FILE %s: %s\n",
285                                 claws_ssl_get_cert_file(), 
286                                 gnutls_strerror(r));
287         } else {
288                 debug_print("Can't find SSL ca-certificates file\n");
289         }
290         gnutls_certificate_set_verify_flags (xcred, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
291
292         gnutls_transport_set_ptr(session, (gnutls_transport_ptr) sockinfo->sock);
293         gnutls_session_set_ptr(session, sockinfo);
294         gnutls_certificate_client_set_retrieve_function(xcred, gnutls_client_cert_cb);
295
296         gnutls_dh_set_prime_bits(session, 512);
297
298         if ((r = SSL_connect_nb(session)) < 0) {
299                 g_warning("SSL connection failed (%s)", gnutls_strerror(r));
300                 gnutls_certificate_free_credentials(xcred);
301                 gnutls_deinit(session);
302                 return FALSE;
303         }
304
305         /* Get server's certificate (note: beware of dynamic allocation) */
306         raw_cert_list = gnutls_certificate_get_peers(session, &raw_cert_list_length);
307
308         if (!raw_cert_list 
309         ||  gnutls_certificate_type_get(session) != GNUTLS_CRT_X509
310         ||  (r = gnutls_x509_crt_init(&cert)) < 0
311         ||  (r = gnutls_x509_crt_import(cert, &raw_cert_list[0], GNUTLS_X509_FMT_DER)) < 0) {
312                 g_warning("cert get failure: %d %s\n", r, gnutls_strerror(r));
313                 gnutls_certificate_free_credentials(xcred);
314                 gnutls_deinit(session);
315                 return FALSE;
316         }
317
318         r = gnutls_certificate_verify_peers2(session, &status);
319
320         if (!ssl_certificate_check(cert, status, sockinfo->canonical_name, sockinfo->hostname, sockinfo->port)) {
321                 gnutls_x509_crt_deinit(cert);
322                 gnutls_certificate_free_credentials(xcred);
323                 gnutls_deinit(session);
324                 return FALSE;
325         }
326
327         gnutls_x509_crt_deinit(cert);
328
329         sockinfo->ssl = session;
330         sockinfo->xcred = xcred;
331         return TRUE;
332 }
333
334 void ssl_done_socket(SockInfo *sockinfo)
335 {
336         if (sockinfo && sockinfo->ssl) {
337                 gnutls_certificate_free_credentials(sockinfo->xcred);
338                 gnutls_deinit(sockinfo->ssl);
339                 if (sockinfo->client_crt)
340                         gnutls_x509_crt_deinit(sockinfo->client_crt);
341                 if (sockinfo->client_key)
342                         gnutls_x509_privkey_deinit(sockinfo->client_key);
343                 sockinfo->client_key = NULL;
344                 sockinfo->client_crt = NULL;
345                 sockinfo->ssl = NULL;
346         }
347 }
348
349 #endif /* USE_GNUTLS */