Warn about lack of DTLS compatibility at build time
[platform/upstream/openconnect.git] / dtls.c
1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008 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         dtls_fd = socket(vpninfo->peer_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
123         if (dtls_fd < 0) {
124                 perror("Open UDP socket for DTLS:");
125                 return -EINVAL;
126         }
127
128         if (connect(dtls_fd, vpninfo->peer_addr, vpninfo->peer_addrlen)) {
129                 perror("UDP (DTLS) connect:\n");
130                 close(dtls_fd);
131                 return -EINVAL;
132         }
133
134         fcntl(dtls_fd, F_SETFD, FD_CLOEXEC);
135
136         if (!vpninfo->dtls_ctx) {
137                 dtls_method = DTLSv1_client_method();
138                 vpninfo->dtls_ctx = SSL_CTX_new(dtls_method);
139                 if (!vpninfo->dtls_ctx) {
140                         vpninfo->progress(vpninfo, PRG_ERR, "Initialise DTLSv1 CTX failed\n");
141                         vpninfo->dtls_attempt_period = 0;
142                         return -EINVAL;
143                 }
144
145                 /* If we don't readahead, then we do short reads and throw
146                    away the tail of data packets. */
147                 SSL_CTX_set_read_ahead(vpninfo->dtls_ctx, 1);
148
149                 if (!SSL_CTX_set_cipher_list(vpninfo->dtls_ctx, vpninfo->dtls_cipher)) {
150                         vpninfo->progress(vpninfo, PRG_ERR, "Set DTLS cipher list failed\n");
151                         SSL_CTX_free(vpninfo->dtls_ctx);
152                         vpninfo->dtls_ctx = NULL;
153                         vpninfo->dtls_attempt_period = 0;
154                         return -EINVAL;
155                 }
156         }
157
158         if (!vpninfo->dtls_session) {
159                 /* We're going to "resume" a session which never existed. Fake it... */
160                 vpninfo->dtls_session = SSL_SESSION_new();
161                 if (!vpninfo->dtls_session) {
162                         vpninfo->progress(vpninfo, PRG_ERR, "Initialise DTLSv1 session failed\n");
163                         vpninfo->dtls_attempt_period = 0;
164                         return -EINVAL;
165                 }
166                 vpninfo->dtls_session->ssl_version = 0x0100; // DTLS1_BAD_VER
167
168                 vpninfo->dtls_session->master_key_length = sizeof(vpninfo->dtls_secret);
169                 memcpy(vpninfo->dtls_session->master_key, vpninfo->dtls_secret,
170                        sizeof(vpninfo->dtls_secret));
171
172                 vpninfo->dtls_session->session_id_length = sizeof(vpninfo->dtls_session_id);
173                 memcpy(vpninfo->dtls_session->session_id, vpninfo->dtls_session_id,
174                        sizeof(vpninfo->dtls_session_id));
175         }
176
177         dtls_ssl = SSL_new(vpninfo->dtls_ctx);
178         SSL_set_connect_state(dtls_ssl);
179
180         ciphers = SSL_get_ciphers(dtls_ssl);
181         if (sk_SSL_CIPHER_num(ciphers) != 1) {
182                 vpninfo->progress(vpninfo, PRG_ERR, "Not precisely one DTLS cipher\n");
183                 SSL_CTX_free(vpninfo->dtls_ctx);
184                 SSL_free(dtls_ssl);
185                 SSL_SESSION_free(vpninfo->dtls_session);
186                 vpninfo->dtls_ctx = NULL;
187                 vpninfo->dtls_session = NULL;
188                 vpninfo->dtls_attempt_period = 0;
189                 return -EINVAL;
190         }
191         dtls_cipher = sk_SSL_CIPHER_value(ciphers, 0);
192
193         /* Set the appropriate cipher on our session to be resumed */
194         vpninfo->dtls_session->cipher = dtls_cipher;
195         vpninfo->dtls_session->cipher_id = dtls_cipher->id;
196
197         /* Add the generated session to the SSL */
198         if (!SSL_set_session(dtls_ssl, vpninfo->dtls_session)) {
199                 vpninfo->progress(vpninfo, PRG_ERR,
200                                   "SSL_set_session() failed with old protocol version 0x%x\n"
201                                   "Your OpenSSL may lack Cisco compatibility support\n"
202                                   "See http://rt.openssl.org/Ticket/Display.html?id=1751\n"
203                                   "Use the --no-dtls command line option to avoid this message\n",
204                                   vpninfo->dtls_session->ssl_version);
205                 vpninfo->dtls_attempt_period = 0;
206                 return -EINVAL;
207         }
208
209         /* Go Go Go! */
210         dtls_bio = BIO_new_socket(dtls_fd, BIO_NOCLOSE);
211         SSL_set_bio(dtls_ssl, dtls_bio, dtls_bio);
212
213 #ifndef SSL_OP_CISCO_ANYCONNECT
214 #warning Your version of OpenSSL does not seem to support Cisco DTLS compatibility
215 #define SSL_OP_CISCO_ANYCONNECT 0x8000
216 #endif
217         SSL_set_options(dtls_ssl, SSL_OP_CISCO_ANYCONNECT);
218
219         /* Set non-blocking */
220         BIO_set_nbio(SSL_get_rbio(dtls_ssl), 1);
221         BIO_set_nbio(SSL_get_wbio(dtls_ssl), 1);
222
223         fcntl(dtls_fd, F_SETFL, fcntl(dtls_fd, F_GETFL) | O_NONBLOCK);
224
225         vpninfo->new_dtls_fd = dtls_fd;
226         vpninfo->new_dtls_ssl = dtls_ssl;
227
228         if (vpninfo->select_nfds <= dtls_fd)
229                 vpninfo->select_nfds = dtls_fd + 1;
230
231         FD_SET(dtls_fd, &vpninfo->select_rfds);
232         FD_SET(dtls_fd, &vpninfo->select_efds);
233
234         time(&vpninfo->new_dtls_started);
235         return dtls_try_handshake(vpninfo);
236 }
237
238 int dtls_try_handshake(struct openconnect_info *vpninfo)
239 {
240         int ret = SSL_do_handshake(vpninfo->new_dtls_ssl);
241
242         if (ret == 1) {
243                 vpninfo->progress(vpninfo, PRG_INFO, "Established DTLS connection\n");
244
245                 if (vpninfo->dtls_ssl) {
246                         /* We are replacing an old connection */
247                         SSL_free(vpninfo->dtls_ssl);
248                         close(vpninfo->dtls_fd);
249                         FD_CLR(vpninfo->dtls_fd, &vpninfo->select_rfds);
250                         FD_CLR(vpninfo->dtls_fd, &vpninfo->select_wfds);
251                         FD_CLR(vpninfo->dtls_fd, &vpninfo->select_efds);
252                 }
253                 vpninfo->dtls_ssl = vpninfo->new_dtls_ssl;
254                 vpninfo->dtls_fd = vpninfo->new_dtls_fd;
255
256                 vpninfo->new_dtls_ssl = NULL;
257                 vpninfo->new_dtls_fd = -1;
258
259                 vpninfo->dtls_times.last_rekey = vpninfo->dtls_times.last_rx =
260                         vpninfo->dtls_times.last_tx = time(NULL);
261
262                 return 0;
263         }
264
265         ret = SSL_get_error(vpninfo->new_dtls_ssl, ret);
266         if (ret == SSL_ERROR_WANT_WRITE || ret == SSL_ERROR_WANT_READ) {
267                 if (time(NULL) < vpninfo->new_dtls_started + 5)
268                         return 0;
269                 vpninfo->progress(vpninfo, PRG_TRACE, "DTLS handshake timed out\n");
270         }
271
272         vpninfo->progress(vpninfo, PRG_ERR, "DTLS handshake failed: %d\n", ret);
273         report_ssl_errors(vpninfo);
274
275         /* Kill the new (failed) connection... */
276         SSL_free(vpninfo->new_dtls_ssl);
277         FD_CLR(vpninfo->new_dtls_fd, &vpninfo->select_rfds);
278         FD_CLR(vpninfo->new_dtls_fd, &vpninfo->select_efds);
279         close(vpninfo->new_dtls_fd);
280         vpninfo->new_dtls_ssl = NULL;
281         vpninfo->new_dtls_fd = -1;
282
283         /* ... and kill the old one too. The only time there'll be a valid
284            existing session is when it was a rekey, and in that case it's
285            time for the old one to die. */
286         if (vpninfo->dtls_ssl) {
287                 SSL_free(vpninfo->dtls_ssl);
288                 close(vpninfo->dtls_fd);
289                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_rfds);
290                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_wfds);
291                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_efds);
292                 vpninfo->dtls_ssl = NULL;
293                 vpninfo->dtls_fd = -1;
294         }
295
296         time(&vpninfo->new_dtls_started);
297         return -EINVAL;
298 }
299
300 static int dtls_restart(struct openconnect_info *vpninfo)
301 {
302         if (vpninfo->dtls_ssl) {
303                 SSL_free(vpninfo->dtls_ssl);
304                 close(vpninfo->dtls_fd);
305                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_rfds);
306                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_wfds);
307                 FD_CLR(vpninfo->dtls_fd, &vpninfo->select_efds);
308                 vpninfo->dtls_ssl = NULL;
309                 vpninfo->dtls_fd = -1;
310         }
311
312         return connect_dtls_socket(vpninfo);
313 }
314
315
316 int setup_dtls(struct openconnect_info *vpninfo)
317 {
318         struct vpn_option *dtls_opt = vpninfo->dtls_options;
319         int sessid_found = 0;
320         int dtls_port = 0;
321         int i;
322
323         while (dtls_opt) {
324                 vpninfo->progress(vpninfo, PRG_TRACE,
325                                   "DTLS option %s : %s\n",
326                                   dtls_opt->option, dtls_opt->value);
327
328                 if (!strcmp(dtls_opt->option, "X-DTLS-Session-ID")) {
329                         if (strlen(dtls_opt->value) != 64) {
330                                 vpninfo->progress(vpninfo, PRG_ERR, "X-DTLS-Session-ID not 64 characters\n");
331                                 vpninfo->progress(vpninfo, PRG_ERR, "Is: %s\n", dtls_opt->value);
332                                 return -EINVAL;
333                         }
334                         for (i = 0; i < 64; i += 2)
335                                 vpninfo->dtls_session_id[i/2] = hex(dtls_opt->value + i);
336                         sessid_found = 1;
337                 } else if (!strcmp(dtls_opt->option + 7, "Port")) {
338                         dtls_port = atol(dtls_opt->value);
339                 } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) {
340                         vpninfo->dtls_times.keepalive = atol(dtls_opt->value);
341                 } else if (!strcmp(dtls_opt->option + 7, "DPD")) {
342                         vpninfo->dtls_times.dpd = atol(dtls_opt->value);
343                 } else if (!strcmp(dtls_opt->option + 7, "Rekey-Time")) {
344                         vpninfo->dtls_times.rekey = atol(dtls_opt->value);
345                 } else if (!strcmp(dtls_opt->option + 7, "CipherSuite")) {
346                         vpninfo->dtls_cipher = strdup(dtls_opt->value);
347                 }
348
349                 dtls_opt = dtls_opt->next;
350         }
351         if (!sessid_found || !dtls_port)
352                 return -EINVAL;
353
354         if (vpninfo->peer_addr->sa_family == AF_INET) {
355                 struct sockaddr_in *sin = (void *)vpninfo->peer_addr;
356                 sin->sin_port = htons(dtls_port);
357         } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
358                 struct sockaddr_in6 *sin = (void *)vpninfo->peer_addr;
359                 sin->sin6_port = htons(dtls_port);
360         } else {
361                 vpninfo->progress(vpninfo, PRG_ERR, "Unknown protocol family %d. Cannot do DTLS\n",
362                         vpninfo->peer_addr->sa_family);
363                 return -EINVAL;
364         }
365
366
367         if (connect_dtls_socket(vpninfo))
368                 return -EINVAL;
369
370         vpninfo->progress(vpninfo, PRG_TRACE,
371                           "DTLS connected. DPD %d, Keepalive %d\n",
372                           vpninfo->dtls_times.dpd, vpninfo->dtls_times.keepalive);
373
374         return 0;
375 }
376
377 int dtls_mainloop(struct openconnect_info *vpninfo, int *timeout)
378 {
379         unsigned char buf[2000];
380         int len;
381         int work_done = 0;
382         char magic_pkt;
383
384         while ( (len = SSL_read(vpninfo->dtls_ssl, buf, sizeof(buf))) > 0 ) {
385
386                 vpninfo->progress(vpninfo, PRG_TRACE,
387                                   "Received DTLS packet 0x%02x of %d bytes\n",
388                                   buf[0], len);
389
390                 vpninfo->dtls_times.last_rx = time(NULL);
391
392                 switch(buf[0]) {
393                 case AC_PKT_DATA:
394                         queue_new_packet(&vpninfo->incoming_queue, buf+1, len-1);
395                         work_done = 1;
396                         break;
397
398                 case AC_PKT_DPD_OUT:
399                         vpninfo->progress(vpninfo, PRG_TRACE, "Got DTLS DPD request\n");
400
401                         /* FIXME: What if the packet doesn't get through? */
402                         magic_pkt = AC_PKT_DPD_RESP;
403                         if (SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1) != 1)
404                                 vpninfo->progress(vpninfo, PRG_ERR, "Failed to send DPD response. Expect disconnect\n");
405                         continue;
406
407                 case AC_PKT_DPD_RESP:
408                         vpninfo->progress(vpninfo, PRG_TRACE, "Got DTLS DPD response\n");
409                         break;
410
411                 case AC_PKT_KEEPALIVE:
412                         vpninfo->progress(vpninfo, PRG_TRACE, "Got DTLS Keepalive\n");
413                         break;
414
415                 default:
416                         vpninfo->progress(vpninfo, PRG_ERR,
417                                           "Unknown DTLS packet type %02x, len %d\n", buf[0], len);
418                         if (1) {
419                                 /* Some versions of OpenSSL have bugs with receiving out-of-order
420                                  * packets. Not only do they wrongly decide to drop packets if
421                                  * two packets get swapped in transit, but they also _fail_ to
422                                  * drop the packet in non-blocking mode; instead they return
423                                  * the appropriate length of garbage. So don't abort... for now. */
424                                 break;
425                         } else {
426                                 vpninfo->quit_reason = "Unknown packet received";
427                                 return 1;
428                         }
429
430                 }
431         }
432
433         switch (keepalive_action(&vpninfo->dtls_times, timeout)) {
434         case KA_REKEY:
435                 time(&vpninfo->dtls_times.last_rekey);
436                 vpninfo->progress(vpninfo, PRG_TRACE, "DTLS rekey due\n");
437                 if (connect_dtls_socket(vpninfo)) {
438                         vpninfo->progress(vpninfo, PRG_ERR, "DTLS rekey failed\n");
439                         return 1;
440                 }
441                 work_done = 1;
442                 break;
443
444
445         case KA_DPD_DEAD:
446                 vpninfo->progress(vpninfo, PRG_ERR, "DTLS Dead Peer Detection detected dead peer!\n");
447                 /* Fall back to SSL, and start a new DTLS connection */
448                 dtls_restart(vpninfo);
449                 return 1;
450
451         case KA_DPD:
452                 vpninfo->progress(vpninfo, PRG_TRACE, "Send DTLS DPD\n");
453
454                 magic_pkt = AC_PKT_DPD_OUT;
455                 SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1);
456                 /* last_dpd will just have been set */
457                 vpninfo->dtls_times.last_tx = vpninfo->dtls_times.last_dpd;
458                 work_done = 1;
459                 break;
460
461         case KA_KEEPALIVE:
462                 /* No need to send an explicit keepalive
463                    if we have real data to send */
464                 if (vpninfo->outgoing_queue)
465                         break;
466
467                 vpninfo->progress(vpninfo, PRG_TRACE, "Send DTLS Keepalive\n");
468
469                 magic_pkt = AC_PKT_KEEPALIVE;
470                 SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1);
471                 time(&vpninfo->dtls_times.last_tx);
472                 work_done = 1;
473                 break;
474
475         case KA_NONE:
476                 ;
477         }
478
479         /* Service outgoing packet queue */
480         while (vpninfo->outgoing_queue) {
481                 struct pkt *this = vpninfo->outgoing_queue;
482                 int ret;
483
484                 vpninfo->outgoing_queue = this->next;
485                 vpninfo->outgoing_qlen--;
486
487                 /* One byte of header */
488                 this->hdr[7] = AC_PKT_DATA;
489
490                 ret = SSL_write(vpninfo->dtls_ssl, &this->hdr[7], this->len + 1);
491                 if (ret <= 0) {
492                         ret = SSL_get_error(vpninfo->dtls_ssl, ret);
493
494                         /* If it's a real error, kill the DTLS connection and
495                            requeue the packet to be sent over SSL */
496                         if (ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE) {
497                                 vpninfo->progress(vpninfo, PRG_ERR,
498                                                   "DTLS got write error %d. Falling back to SSL\n", ret);
499                                 report_ssl_errors(vpninfo);
500                                 dtls_restart(vpninfo);
501                                 vpninfo->outgoing_queue = this;
502                                 vpninfo->outgoing_qlen++;
503                         }
504                         return 1;
505                 }
506                 time(&vpninfo->dtls_times.last_tx);
507                 vpninfo->progress(vpninfo, PRG_TRACE,
508                                   "Sent DTLS packet of %d bytes; SSL_write() returned %d\n",
509                                   this->len, ret);
510                 free(this);
511         }
512
513         return work_done;
514 }
515 #else /* No DTLS support in OpenSSL */
516 int setup_dtls(struct openconnect_info *vpninfo)
517 {
518         vpninfo->progress(vpninfo, PRG_ERR, "Built against OpenSSL with no DTLS support\n");
519         return -EINVAL;
520 }
521 #endif
522