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