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