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