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