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