reconnect on dtls dpd
[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.
54  */   
55
56 static unsigned char nybble(unsigned char n)
57 {
58         if      (n >= '0' && n <= '9') return n - '0';
59         else if (n >= 'A' && n <= 'F') return n - ('A' - 10);
60         else if (n >= 'a' && n <= 'f') return n - ('a' - 10);
61         return 0;
62 }
63
64 static unsigned char hex(const char *data)
65 {
66         return (nybble(data[0]) << 4) | nybble(data[1]);
67 }
68
69 static int connect_dtls_socket(struct anyconnect_info *vpninfo, SSL **ret_ssl,
70                                int *ret_fd)
71 {
72         SSL_METHOD *dtls_method;
73         SSL_CIPHER *https_cipher;
74         SSL *dtls_ssl;
75         BIO *dtls_bio;
76         int dtls_fd;
77         int ret;
78
79         dtls_fd = socket(vpninfo->peer_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
80         if (dtls_fd < 0) {
81                 perror("Open UDP socket for DTLS:");
82                 return -EINVAL;
83         }
84         
85         if (connect(dtls_fd, vpninfo->peer_addr, vpninfo->peer_addrlen)) {
86                 perror("UDP (DTLS) connect:\n");
87                 close(dtls_fd);
88                 return -EINVAL;
89         }
90
91         fcntl(dtls_fd, F_SETFD, FD_CLOEXEC);
92         
93         https_cipher = SSL_get_current_cipher(vpninfo->https_ssl);
94
95         if (!vpninfo->dtls_ctx) {
96                 dtls_method = DTLSv1_client_method();
97                 vpninfo->dtls_ctx = SSL_CTX_new(dtls_method);
98                 if (!vpninfo->dtls_ctx) {
99                         fprintf(stderr, "Initialise DTLSv1 CTX failed\n");
100                         return -EINVAL;
101                 }
102
103                 /* If we don't readahead, then we do short reads and throw
104                    away the tail of data packets. */
105                 SSL_CTX_set_read_ahead(vpninfo->dtls_ctx, 1);
106         }
107
108         if (!vpninfo->dtls_session) {
109                 /* We're going to "resume" a session which never existed. Fake it... */
110                 vpninfo->dtls_session = SSL_SESSION_new();
111                 if (!vpninfo->dtls_session) {
112                         fprintf(stderr, "Initialise DTLSv1 session failed\n");
113                         return -EINVAL;
114                 }                       
115                 vpninfo->dtls_session->ssl_version = 0x0100; // DTLS1_BAD_VER
116
117                 vpninfo->dtls_session->master_key_length = sizeof(vpninfo->dtls_secret);
118                 memcpy(vpninfo->dtls_session->master_key, vpninfo->dtls_secret,
119                        sizeof(vpninfo->dtls_secret));
120
121                 vpninfo->dtls_session->session_id_length = sizeof(vpninfo->dtls_session_id);
122                 memcpy(vpninfo->dtls_session->session_id, vpninfo->dtls_session_id,
123                        sizeof(vpninfo->dtls_session_id));
124
125                 vpninfo->dtls_session->cipher = https_cipher;
126                 vpninfo->dtls_session->cipher_id = https_cipher->id;
127         }
128
129         dtls_ssl = SSL_new(vpninfo->dtls_ctx);
130         SSL_set_connect_state(dtls_ssl);
131         SSL_set_cipher_list(dtls_ssl, SSL_CIPHER_get_name(https_cipher));
132
133         /* Add the generated session to the SSL */
134         if (!SSL_set_session(dtls_ssl, vpninfo->dtls_session)) {
135                 printf("SSL_set_session() failed with old protocol version 0x%x\n",
136                        vpninfo->dtls_session->ssl_version);
137                 printf("Your OpenSSL may lack Cisco compatibility support\n");
138                 printf("See http://rt.openssl.org/Ticket/Display.html?id=1751\n");
139                 printf("Use the --no-dtls command line option to avoid this message\n");
140                 return -EINVAL;
141         }
142
143         /* Go Go Go! */
144         dtls_bio = BIO_new_socket(dtls_fd, BIO_NOCLOSE);
145         SSL_set_bio(dtls_ssl, dtls_bio, dtls_bio);
146
147         /* XXX Cargo cult programming. Other DTLS code does this, and it might
148            avoid http://rt.openssl.org/Ticket/Display.html?id=1703 */
149         BIO_ctrl(dtls_bio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL);
150
151 #ifndef SSL_OP_CISCO_ANYCONNECT
152 #define SSL_OP_CISCO_ANYCONNECT 0x8000
153 #endif
154         SSL_set_options(dtls_ssl, SSL_OP_CISCO_ANYCONNECT);
155         ret = SSL_do_handshake(dtls_ssl);
156         
157         if (ret != 1) {
158                 fprintf(stderr, "DTLS connection returned %d\n", ret);
159                 if (ret < 0)
160                         fprintf(stderr, "DTLS handshake error: %d\n", SSL_get_error(dtls_ssl, ret));
161                 ERR_print_errors_fp(stderr);
162                 SSL_free(dtls_ssl);
163                 SSL_CTX_free(vpninfo->dtls_ctx);
164                 vpninfo->dtls_ctx = NULL;
165                 close(dtls_fd);
166                 return -EINVAL;
167         }
168
169         BIO_set_nbio(SSL_get_rbio(dtls_ssl),1);
170         BIO_set_nbio(SSL_get_wbio(dtls_ssl),1);
171
172         fcntl(dtls_fd, F_SETFL, fcntl(dtls_fd, F_GETFL) | O_NONBLOCK);
173
174         vpninfo->dtls_times.last_rekey = vpninfo->dtls_times.last_rx =
175                 vpninfo->dtls_times.last_tx = time(NULL);
176
177         *ret_fd = dtls_fd;
178         *ret_ssl = dtls_ssl;
179
180         return 0;
181 }
182
183 static int dtls_rekey(struct anyconnect_info *vpninfo)
184 {
185         SSL *dtls_ssl;
186         int dtls_fd;
187
188         /* To rekey, we just 'resume' the session again */
189         if (connect_dtls_socket(vpninfo, &dtls_ssl, &dtls_fd)) {
190                 /* Fall back to SSL */
191                 SSL_free(vpninfo->dtls_ssl);
192                 close(vpninfo->dtls_fd);
193                 vpninfo->pfds[vpninfo->dtls_pfd].fd = -1;
194                 vpninfo->dtls_ssl = NULL;
195                 vpninfo->dtls_fd = -1;
196                 return -EINVAL;
197         }
198
199         vpninfo->pfds[vpninfo->dtls_pfd].fd = dtls_fd;
200
201         SSL_free(vpninfo->dtls_ssl);
202         close(vpninfo->dtls_fd);
203
204         vpninfo->dtls_ssl = dtls_ssl;
205         vpninfo->dtls_fd = dtls_fd;
206
207         return 0;
208 }
209
210 int setup_dtls(struct anyconnect_info *vpninfo)
211 {
212         struct vpn_option *dtls_opt = vpninfo->dtls_options;
213         int sessid_found = 0;
214         int dtls_port = 0;
215         int i;
216
217         while (dtls_opt) {
218                 if (verbose)
219                         printf("DTLS option %s : %s\n", dtls_opt->option, dtls_opt->value);
220
221                 if (!strcmp(dtls_opt->option, "X-DTLS-Session-ID")) {
222                         if (strlen(dtls_opt->value) != 64) {
223                                 fprintf(stderr, "X-DTLS-Session-ID not 64 characters\n");
224                                 fprintf(stderr, "Is: %s\n", dtls_opt->value);
225                                 return -EINVAL;
226                         }
227                         for (i = 0; i < 64; i += 2)
228                                 vpninfo->dtls_session_id[i/2] = hex(dtls_opt->value + i);
229                         sessid_found = 1;
230                 } else if (!strcmp(dtls_opt->option + 7, "Port")) {
231                         dtls_port = atol(dtls_opt->value);
232                 } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) {
233                         vpninfo->dtls_times.keepalive = atol(dtls_opt->value);
234                 } else if (!strcmp(dtls_opt->option + 7, "DPD")) {
235                         vpninfo->dtls_times.dpd = 10;//atol(dtls_opt->value);
236                 } else if (!strcmp(dtls_opt->option + 7, "Rekey-Time")) {
237                         vpninfo->dtls_times.rekey = atol(dtls_opt->value);
238                 }
239                         
240                 dtls_opt = dtls_opt->next;
241         }
242         if (!sessid_found || !dtls_port)
243                 return -EINVAL;
244
245         if (vpninfo->peer_addr->sa_family == AF_INET) {
246                 struct sockaddr_in *sin = (void *)vpninfo->peer_addr;
247                 sin->sin_port = htons(dtls_port);
248         } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
249                 struct sockaddr_in6 *sin = (void *)vpninfo->peer_addr;
250                 sin->sin6_port = htons(dtls_port);
251         } else {
252                 fprintf(stderr, "Unknown protocol family %d. Cannot do DTLS\n",
253                         vpninfo->peer_addr->sa_family);
254                 return -EINVAL;
255         }
256
257         if (connect_dtls_socket(vpninfo, &vpninfo->dtls_ssl, &vpninfo->dtls_fd))
258                 return -EINVAL;
259
260         vpninfo->dtls_pfd = vpn_add_pollfd(vpninfo, vpninfo->dtls_fd,
261                                            POLLIN|POLLHUP|POLLERR);
262
263         if (verbose)
264                 printf("DTLS connected. DPD %d, Keepalive %d\n",
265                        vpninfo->dtls_times.dpd, vpninfo->dtls_times.keepalive);
266
267         return 0;
268 }
269
270 int dtls_mainloop(struct anyconnect_info *vpninfo, int *timeout)
271 {
272         unsigned char buf[2000];
273         int len;
274         int work_done = 0;
275         char magic_pkt;
276
277         while ( (len = SSL_read(vpninfo->dtls_ssl, buf, sizeof(buf))) > 0 ) {
278                 if (verbose)
279                         printf("Received DTLS packet 0x%02x of %d bytes\n",
280                                buf[0], len);
281
282                 //vpninfo->dtls_times.last_rx = time(NULL);
283
284                 switch(buf[0]) {
285                 case AC_PKT_DATA:
286                         queue_new_packet(&vpninfo->incoming_queue, AF_INET, buf+1, len-1);
287                         work_done = 1;
288                         break;
289
290                 case AC_PKT_DPD_OUT:
291                         if (verbose)
292                                 printf("Got DTLS DPD request\n");
293
294                         /* FIXME: What if the packet doesn't get through? */
295                         magic_pkt = AC_PKT_DPD_RESP;
296                         if (SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1) != 1)
297                                 fprintf(stderr, "Failed to send DPD response. Expect disconnect\n");
298                         continue;
299
300                 case AC_PKT_DPD_RESP:
301                         if (verbose)
302                                 printf("Got DTLS DPD response\n");
303                         break;
304
305                 case AC_PKT_KEEPALIVE:
306                         if (verbose)
307                                 printf("Got DTLS Keepalive\n");
308                         break;
309
310                 default:
311                         fprintf(stderr, "Unknown DTLS packet type %02x\n", buf[0]);
312                         vpninfo->quit_reason = "Unknown packet received";
313                         return 1;
314                 }
315         }
316
317         if (verbose)
318                 printf("Process DTLS keepalive...\n");
319         switch (keepalive_action(&vpninfo->dtls_times, timeout)) {
320         case KA_REKEY:
321                 if (verbose)
322                         printf("DTLS rekey due\n");
323                 if (dtls_rekey(vpninfo)) {
324                         fprintf(stderr, "DTLS rekey failed\n");
325                         return 1;
326                 }
327                 work_done = 1;
328                 break;
329
330
331         case KA_DPD_DEAD:
332                 fprintf(stderr, "DTLS Dead Peer Detection detected dead peer!\n");
333                 if (dtls_rekey(vpninfo)) {
334                         fprintf(stderr, "DTLS reconnect failed\n");
335                         return 1;
336                 }
337                 work_done = 1;
338                 break;
339
340         case KA_DPD:
341                 if (verbose)
342                         printf("Send DTLS DPD\n");
343
344                 magic_pkt = AC_PKT_DPD_OUT;
345                 SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1);
346                 /* last_dpd will just have been set */
347                 vpninfo->dtls_times.last_tx = vpninfo->dtls_times.last_dpd;
348                 work_done = 1;
349                 break;
350
351         case KA_KEEPALIVE:
352                 /* No need to send an explicit keepalive
353                    if we have real data to send */
354                 if (vpninfo->outgoing_queue)
355                         break;
356
357                 if (verbose)
358                         printf("Send DTLS Keepalive\n");
359
360                 magic_pkt = AC_PKT_KEEPALIVE;
361                 SSL_write(vpninfo->dtls_ssl, &magic_pkt, 1);
362                 time(&vpninfo->dtls_times.last_tx);
363                 work_done = 1;
364                 break;
365
366         case KA_NONE:
367                 ;
368         }
369
370         /* Service outgoing packet queue */
371         while (vpninfo->outgoing_queue) {
372                 struct pkt *this = vpninfo->outgoing_queue;
373                 int ret;
374
375                 vpninfo->outgoing_queue = this->next;
376
377                 /* One byte of header */
378                 this->hdr[7] = AC_PKT_DATA;
379                 
380                 ret = SSL_write(vpninfo->dtls_ssl, &this->hdr[7], this->len + 1);
381                 time(&vpninfo->dtls_times.last_tx);
382                 if (verbose) {
383                         printf("Sent DTLS packet of %d bytes; SSL_write() returned %d\n",
384                                this->len, ret);
385                 }
386         }
387
388         return work_done;
389 }
390
391