Don't keep retrying DTLS if OpenSSL doesn't support it
[platform/upstream/openconnect.git] / dtls.c
1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008 Intel Corporation.
5  *
6  * Author: David Woodhouse <dwmw2@infradead.org>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * version 2.1, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to:
19  *
20  *   Free Software Foundation, Inc.
21  *   51 Franklin Street, Fifth Floor,
22  *   Boston, MA 02110-1301 USA
23  */
24
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netdb.h>
29 #include <unistd.h>
30 #include <openssl/err.h>
31 #include <fcntl.h>
32 #include <string.h>
33
34 #include "openconnect.h"
35
36 #if 0
37 /*
38  * Useful for catching test cases, where we want everything to be
39  * reproducible.  *NEVER* do this in the wild.
40  */
41 time_t time(time_t *t)
42 {
43         time_t x = 0x3ab2d948;
44         if (t) *t = x;
45         return x;
46 }
47
48 int RAND_pseudo_bytes(char *buf, int len)
49 {
50         memset(buf, 0x5a, len);
51         printf("FAKE PSEUDO RANDOM!\n");
52         return 1;
53         
54 }
55 int RAND_bytes(char *buf, int len)
56 {
57         static int foo = 0x5b;
58         printf("FAKE RANDOM!\n");
59         memset(buf, foo, len);
60         return 1;
61 }
62 #endif
63
64 /*
65  * The master-secret is generated randomly by the client. The server
66  * responds with a DTLS Session-ID. These, done over the HTTPS
67  * connection, are enough to 'resume' a DTLS session, bypassing all
68  * the normal setup of a normal DTLS connection.
69  *
70  * Cisco use a version of the protocol which predates RFC4347, but
71  * isn't quite the same as the pre-RFC version of the protocol which
72  * was in OpenSSL 0.9.8e -- it includes backports of some later
73  * OpenSSL patches.
74  *
75  * The openssl/ directory of this source tree should contain both a 
76  * small patch against OpenSSL 0.9.8e to make it support Cisco's 
77  * snapshot of the protocol, and a larger patch against newer OpenSSL
78  * which gives us an option to use the old protocol again.
79  *
80  * Cisco's server also seems to respond to the official version of the
81  * protocol, with a change in the ChangeCipherSpec packet which implies
82  * that it does know the difference and isn't just repeating the version
83  * number seen in the ClientHello. But although I can make the handshake
84  * complete by hacking tls1_mac() to use the _old_ protocol version
85  * number when calculating the MAC, the server still seems to be ignoring
86  * my subsequent data packets. So we use the old protocol, which is what
87  * their clients use anyway.
88  */   
89
90 static unsigned char nybble(unsigned char n)
91 {
92         if      (n >= '0' && n <= '9') return n - '0';
93         else if (n >= 'A' && n <= 'F') return n - ('A' - 10);
94         else if (n >= 'a' && n <= 'f') return n - ('a' - 10);
95         return 0;
96 }
97
98 static unsigned char hex(const char *data)
99 {
100         return (nybble(data[0]) << 4) | nybble(data[1]);
101 }
102
103 int connect_dtls_socket(struct openconnect_info *vpninfo)
104 {
105         SSL_METHOD *dtls_method;
106         SSL_CIPHER *https_cipher;
107         SSL *dtls_ssl;
108         BIO *dtls_bio;
109         int dtls_fd;
110
111         dtls_fd = socket(vpninfo->peer_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
112         if (dtls_fd < 0) {
113                 perror("Open UDP socket for DTLS:");
114                 return -EINVAL;
115         }
116         
117         if (connect(dtls_fd, vpninfo->peer_addr, vpninfo->peer_addrlen)) {
118                 perror("UDP (DTLS) connect:\n");
119                 close(dtls_fd);
120                 return -EINVAL;
121         }
122
123         fcntl(dtls_fd, F_SETFD, FD_CLOEXEC);
124         
125         https_cipher = SSL_get_current_cipher(vpninfo->https_ssl);
126
127         if (!vpninfo->dtls_ctx) {
128                 dtls_method = DTLSv1_client_method();
129                 vpninfo->dtls_ctx = SSL_CTX_new(dtls_method);
130                 if (!vpninfo->dtls_ctx) {
131                         vpninfo->progress(vpninfo, PRG_ERR, "Initialise DTLSv1 CTX failed\n");
132                         return -EINVAL;
133                 }
134
135                 /* If we don't readahead, then we do short reads and throw
136                    away the tail of data packets. */
137                 SSL_CTX_set_read_ahead(vpninfo->dtls_ctx, 1);
138         }
139
140         if (!vpninfo->dtls_session) {
141                 /* We're going to "resume" a session which never existed. Fake it... */
142                 vpninfo->dtls_session = SSL_SESSION_new();
143                 if (!vpninfo->dtls_session) {
144                         vpninfo->progress(vpninfo, PRG_ERR, "Initialise DTLSv1 session failed\n");
145                         return -EINVAL;
146                 }                       
147                 vpninfo->dtls_session->ssl_version = 0x0100; // DTLS1_BAD_VER
148
149                 vpninfo->dtls_session->master_key_length = sizeof(vpninfo->dtls_secret);
150                 memcpy(vpninfo->dtls_session->master_key, vpninfo->dtls_secret,
151                        sizeof(vpninfo->dtls_secret));
152
153                 vpninfo->dtls_session->session_id_length = sizeof(vpninfo->dtls_session_id);
154                 memcpy(vpninfo->dtls_session->session_id, vpninfo->dtls_session_id,
155                        sizeof(vpninfo->dtls_session_id));
156
157                 vpninfo->dtls_session->cipher = https_cipher;
158                 vpninfo->dtls_session->cipher_id = https_cipher->id;
159         }
160
161         dtls_ssl = SSL_new(vpninfo->dtls_ctx);
162         SSL_set_connect_state(dtls_ssl);
163         SSL_set_cipher_list(dtls_ssl, SSL_CIPHER_get_name(https_cipher));
164
165         /* Add the generated session to the SSL */
166         if (!SSL_set_session(dtls_ssl, vpninfo->dtls_session)) {
167                 vpninfo->progress(vpninfo, PRG_ERR,
168                                   "SSL_set_session() failed with old protocol version 0x%x\n"
169                                   "Your OpenSSL may lack Cisco compatibility support\n"
170                                   "See http://rt.openssl.org/Ticket/Display.html?id=1751\n"
171                                   "Use the --no-dtls command line option to avoid this message\n",
172                                   vpninfo->dtls_session->ssl_version);
173                 vpninfo->dtls_attempt_period = 0;
174                 return -EINVAL;
175         }
176
177         /* Go Go Go! */
178         dtls_bio = BIO_new_socket(dtls_fd, BIO_NOCLOSE);
179         SSL_set_bio(dtls_ssl, dtls_bio, dtls_bio);
180
181 #ifndef SSL_OP_CISCO_ANYCONNECT
182 #define SSL_OP_CISCO_ANYCONNECT 0x8000
183 #endif
184         SSL_set_options(dtls_ssl, SSL_OP_CISCO_ANYCONNECT);
185
186         /* Set non-blocking */
187         BIO_set_nbio(SSL_get_rbio(dtls_ssl),1);
188         BIO_set_nbio(SSL_get_wbio(dtls_ssl),1);
189
190         fcntl(dtls_fd, F_SETFL, fcntl(dtls_fd, F_GETFL) | O_NONBLOCK);
191
192         vpninfo->new_dtls_fd = dtls_fd;
193         vpninfo->new_dtls_ssl = dtls_ssl;
194         
195         if (vpninfo->select_nfds <= dtls_fd)
196                 vpninfo->select_nfds = dtls_fd + 1;
197
198         FD_SET(dtls_fd, &vpninfo->select_rfds);
199         FD_SET(dtls_fd, &vpninfo->select_efds);
200
201         time(&vpninfo->new_dtls_started);
202         return dtls_try_handshake(vpninfo);
203 }
204
205 int dtls_try_handshake(struct openconnect_info *vpninfo)
206 {
207         int ret = SSL_do_handshake(vpninfo->new_dtls_ssl);
208
209         if (ret == 1) {
210                 vpninfo->progress(vpninfo, PRG_INFO, "Established DTLS connection\n");
211
212                 if (vpninfo->dtls_ssl) {
213                         /* We are replacing an old connection */
214                         SSL_free(vpninfo->dtls_ssl);
215                         close(vpninfo->dtls_fd);
216                         FD_CLR(vpninfo->dtls_fd, &vpninfo->select_rfds);
217                         FD_CLR(vpninfo->dtls_fd, &vpninfo->select_wfds);
218                         FD_CLR(vpninfo->dtls_fd, &vpninfo->select_efds);
219                 }
220                 vpninfo->dtls_ssl = vpninfo->new_dtls_ssl;
221                 vpninfo->dtls_fd = vpninfo->new_dtls_fd;
222
223                 vpninfo->new_dtls_ssl = NULL;
224                 vpninfo->new_dtls_fd = -1;
225
226                 vpninfo->dtls_times.last_rekey = vpninfo->dtls_times.last_rx =
227                         vpninfo->dtls_times.last_tx = time(NULL);
228
229                 return 0;
230         }
231
232         ret = SSL_get_error(vpninfo->new_dtls_ssl, ret);
233         if (ret == SSL_ERROR_WANT_WRITE || ret == SSL_ERROR_WANT_READ) {
234                 if (time(NULL) < vpninfo->new_dtls_started + 5)
235                         return 0;
236                 vpninfo->progress(vpninfo, PRG_TRACE, "DTLS handshake timed out\n");
237         }
238
239         vpninfo->progress(vpninfo, PRG_ERR, "DTLS handshake failed: %d\n", ret);
240         ERR_print_errors_fp(stderr);
241
242         /* Kill the new (failed) connection... */
243         SSL_free(vpninfo->new_dtls_ssl);
244         FD_CLR(vpninfo->new_dtls_fd, &vpninfo->select_rfds);
245         FD_CLR(vpninfo->new_dtls_fd, &vpninfo->select_efds);
246         close(vpninfo->new_dtls_fd);
247         vpninfo->new_dtls_ssl = NULL;
248         vpninfo->new_dtls_fd = -1;
249
250         /* ... and kill the old one too. The only time there'll be a valid
251            existing session is when it was a rekey, and in that case it's
252            time for the old one to die. */
253         if (vpninfo->dtls_ssl) {
254                 SSL_free(vpninfo->dtls_ssl);
255                 close(vpninfo->dtls_fd);
256                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_rfds);
257                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_wfds);
258                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_efds);
259                 vpninfo->dtls_ssl = NULL;
260                 vpninfo->dtls_fd = -1;
261         }
262
263         time(&vpninfo->new_dtls_started);
264         return -EINVAL;
265 }
266
267 static int dtls_restart(struct openconnect_info *vpninfo)
268 {
269         if (vpninfo->dtls_ssl) {
270                 SSL_free(vpninfo->dtls_ssl);
271                 close(vpninfo->dtls_fd);
272                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_rfds);
273                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_wfds);
274                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_efds);
275                 vpninfo->dtls_ssl = NULL;
276                 vpninfo->dtls_fd = -1;
277         }
278
279         return connect_dtls_socket(vpninfo);
280 }
281
282
283 int setup_dtls(struct openconnect_info *vpninfo)
284 {
285         struct vpn_option *dtls_opt = vpninfo->dtls_options;
286         int sessid_found = 0;
287         int dtls_port = 0;
288         int i;
289
290         while (dtls_opt) {
291                 vpninfo->progress(vpninfo, PRG_TRACE,
292                                   "DTLS option %s : %s\n",
293                                   dtls_opt->option, dtls_opt->value);
294
295                 if (!strcmp(dtls_opt->option, "X-DTLS-Session-ID")) {
296                         if (strlen(dtls_opt->value) != 64) {
297                                 vpninfo->progress(vpninfo, PRG_ERR, "X-DTLS-Session-ID not 64 characters\n");
298                                 vpninfo->progress(vpninfo, PRG_ERR, "Is: %s\n", dtls_opt->value);
299                                 return -EINVAL;
300                         }
301                         for (i = 0; i < 64; i += 2)
302                                 vpninfo->dtls_session_id[i/2] = hex(dtls_opt->value + i);
303                         sessid_found = 1;
304                 } else if (!strcmp(dtls_opt->option + 7, "Port")) {
305                         dtls_port = atol(dtls_opt->value);
306                 } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) {
307                         vpninfo->dtls_times.keepalive = atol(dtls_opt->value);
308                 } else if (!strcmp(dtls_opt->option + 7, "DPD")) {
309                         vpninfo->dtls_times.dpd = atol(dtls_opt->value);
310                 } else if (!strcmp(dtls_opt->option + 7, "Rekey-Time")) {
311                         vpninfo->dtls_times.rekey = atol(dtls_opt->value);
312                 }
313                         
314                 dtls_opt = dtls_opt->next;
315         }
316         if (!sessid_found || !dtls_port)
317                 return -EINVAL;
318
319         if (vpninfo->peer_addr->sa_family == AF_INET) {
320                 struct sockaddr_in *sin = (void *)vpninfo->peer_addr;
321                 sin->sin_port = htons(dtls_port);
322         } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
323                 struct sockaddr_in6 *sin = (void *)vpninfo->peer_addr;
324                 sin->sin6_port = htons(dtls_port);
325         } else {
326                 vpninfo->progress(vpninfo, PRG_ERR, "Unknown protocol family %d. Cannot do DTLS\n",
327                         vpninfo->peer_addr->sa_family);
328                 return -EINVAL;
329         }
330
331         
332         if (connect_dtls_socket(vpninfo))
333                 return -EINVAL;
334
335         vpninfo->progress(vpninfo, PRG_TRACE,
336                           "DTLS connected. DPD %d, Keepalive %d\n",
337                           vpninfo->dtls_times.dpd, vpninfo->dtls_times.keepalive);
338
339         return 0;
340 }
341
342 int dtls_mainloop(struct openconnect_info *vpninfo, int *timeout)
343 {
344         unsigned char buf[2000];
345         int len;
346         int work_done = 0;
347         char magic_pkt;
348
349         while ( (len = SSL_read(vpninfo->dtls_ssl, buf, sizeof(buf))) > 0 ) {
350
351                 vpninfo->progress(vpninfo, PRG_TRACE,
352                                   "Received DTLS packet 0x%02x of %d bytes\n",
353                                   buf[0], len);
354
355                 vpninfo->dtls_times.last_rx = time(NULL);
356
357                 switch(buf[0]) {
358                 case AC_PKT_DATA:
359                         queue_new_packet(&vpninfo->incoming_queue, AF_INET, buf+1, len-1);
360                         work_done = 1;
361                         break;
362
363                 case AC_PKT_DPD_OUT:
364                         vpninfo->progress(vpninfo, PRG_TRACE, "Got DTLS DPD request\n");
365
366                         /* FIXME: What if the packet doesn't get through? */
367                         magic_pkt = AC_PKT_DPD_RESP;
368                         if (SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1) != 1)
369                                 vpninfo->progress(vpninfo, PRG_ERR, "Failed to send DPD response. Expect disconnect\n");
370                         continue;
371
372                 case AC_PKT_DPD_RESP:
373                         vpninfo->progress(vpninfo, PRG_TRACE, "Got DTLS DPD response\n");
374                         break;
375
376                 case AC_PKT_KEEPALIVE:
377                         vpninfo->progress(vpninfo, PRG_TRACE, "Got DTLS Keepalive\n");
378                         break;
379
380                 default:
381                         vpninfo->progress(vpninfo, PRG_ERR,
382                                           "Unknown DTLS packet type %02x, len %d\n", buf[0], len);
383                         if (1) {
384                                 /* Some versions of OpenSSL have bugs with receiving out-of-order
385                                  * packets. Not only do they wrongly decide to drop packets if 
386                                  * two packets get swapped in transit, but they also _fail_ to
387                                  * drop the packet in non-blocking mode; instead they return
388                                  * the appropriate length of garbage. So don't abort... for now. */
389                                 break;
390                         } else {
391                                 vpninfo->quit_reason = "Unknown packet received";
392                                 return 1;
393                         }
394
395                 }
396         }
397
398         switch (keepalive_action(&vpninfo->dtls_times, timeout)) {
399         case KA_REKEY:
400                 time(&vpninfo->dtls_times.last_rekey);
401                 vpninfo->progress(vpninfo, PRG_TRACE, "DTLS rekey due\n");
402                 if (connect_dtls_socket(vpninfo)) {
403                         vpninfo->progress(vpninfo, PRG_ERR, "DTLS rekey failed\n");
404                         return 1;
405                 }
406                 work_done = 1;
407                 break;
408
409
410         case KA_DPD_DEAD:
411                 vpninfo->progress(vpninfo, PRG_ERR, "DTLS Dead Peer Detection detected dead peer!\n");
412                 /* Fall back to SSL, and start a new DTLS connection */
413                 dtls_restart(vpninfo);
414                 return 1;
415
416         case KA_DPD:
417                 vpninfo->progress(vpninfo, PRG_TRACE, "Send DTLS DPD\n");
418
419                 magic_pkt = AC_PKT_DPD_OUT;
420                 SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1);
421                 /* last_dpd will just have been set */
422                 vpninfo->dtls_times.last_tx = vpninfo->dtls_times.last_dpd;
423                 work_done = 1;
424                 break;
425
426         case KA_KEEPALIVE:
427                 /* No need to send an explicit keepalive
428                    if we have real data to send */
429                 if (vpninfo->outgoing_queue)
430                         break;
431
432                 vpninfo->progress(vpninfo, PRG_TRACE, "Send DTLS Keepalive\n");
433
434                 magic_pkt = AC_PKT_KEEPALIVE;
435                 SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1);
436                 time(&vpninfo->dtls_times.last_tx);
437                 work_done = 1;
438                 break;
439
440         case KA_NONE:
441                 ;
442         }
443
444         /* Service outgoing packet queue */
445         while (vpninfo->outgoing_queue) {
446                 struct pkt *this = vpninfo->outgoing_queue;
447                 int ret;
448
449                 vpninfo->outgoing_queue = this->next;
450                 vpninfo->outgoing_qlen--;
451
452                 /* One byte of header */
453                 this->hdr[7] = AC_PKT_DATA;
454                 
455                 ret = SSL_write(vpninfo->dtls_ssl, &this->hdr[7], this->len + 1);
456                 if (ret <= 0) {
457                         ret = SSL_get_error(vpninfo->dtls_ssl, ret);
458
459                         /* If it's a real error, kill the DTLS connection and
460                            requeue the packet to be sent over SSL */
461                         if (ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE) {
462                                 vpninfo->progress(vpninfo, PRG_ERR, 
463                                                   "DTLS got write error %d. Falling back to SSL\n", ret);
464                                 ERR_print_errors_fp(stderr);
465                                 dtls_restart(vpninfo);
466                                 vpninfo->outgoing_queue = this;
467                                 vpninfo->outgoing_qlen++;
468                         }
469                         return 1;
470                 }
471                 time(&vpninfo->dtls_times.last_tx);
472                 vpninfo->progress(vpninfo, PRG_TRACE,
473                                   "Sent DTLS packet of %d bytes; SSL_write() returned %d\n",
474                                   this->len, ret);
475         }
476
477         return work_done;
478 }
479
480