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