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