Clean up messages a little
[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_CTX *dtls_ctx;
74         SSL_SESSION *dtls_session;
75         SSL_CIPHER *https_cipher;
76         SSL *dtls_ssl;
77         BIO *dtls_bio;
78         int dtls_fd;
79         int ret;
80
81         dtls_fd = socket(vpninfo->peer_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
82         if (dtls_fd < 0) {
83                 perror("Open UDP socket for DTLS:");
84                 return -EINVAL;
85         }
86         
87         if (connect(dtls_fd, vpninfo->peer_addr, vpninfo->peer_addrlen)) {
88                 perror("UDP (DTLS) connect:\n");
89                 close(dtls_fd);
90                 return -EINVAL;
91         }
92
93         fcntl(dtls_fd, F_SETFD, FD_CLOEXEC);
94
95         dtls_method = DTLSv1_client_method();
96         dtls_ctx = SSL_CTX_new(dtls_method);
97         SSL_CTX_set_read_ahead(dtls_ctx, 1);
98         https_cipher = SSL_get_current_cipher(vpninfo->https_ssl);
99
100         dtls_ssl = SSL_new(dtls_ctx);
101         SSL_set_connect_state(dtls_ssl);
102         SSL_set_cipher_list(dtls_ssl, SSL_CIPHER_get_name(https_cipher));
103
104         if (verbose)
105                 printf("SSL_SESSION is %zd bytes\n", sizeof(*dtls_session));
106         /* We're going to "resume" a session which never existed. Fake it... */
107         dtls_session = SSL_SESSION_new();
108
109         dtls_session->ssl_version = 0x0100; // DTLS1_BAD_VER
110
111         dtls_session->master_key_length = sizeof(vpninfo->dtls_secret);
112         memcpy(dtls_session->master_key, vpninfo->dtls_secret,
113                sizeof(vpninfo->dtls_secret));
114
115         dtls_session->session_id_length = sizeof(vpninfo->dtls_session_id);
116         memcpy(dtls_session->session_id, vpninfo->dtls_session_id,
117                sizeof(vpninfo->dtls_session_id));
118
119         dtls_session->cipher = https_cipher;
120         dtls_session->cipher_id = https_cipher->id;
121
122         /* Having faked a session, add it to the CTX and the SSL */
123         if (!SSL_set_session(dtls_ssl, dtls_session)) {
124                 printf("SSL_set_session() failed with old protocol version 0x%x\n", dtls_session->ssl_version);
125                 printf("Trying the official version %x\n", 0xfeff);
126                 dtls_session->ssl_version = 0xfeff;
127                 if (!SSL_set_session(dtls_ssl, dtls_session)) {
128                         printf("SSL_set_session() failed still. Is your build ABI-compatible with your libssl?\n");
129                         return -EINVAL;
130                 }
131         }
132         if (!SSL_CTX_add_session(dtls_ctx, dtls_session))
133                 printf("SSL_CTX_add_session() failed\n");
134
135
136         /* Go Go Go! */
137         dtls_bio = BIO_new_socket(dtls_fd, BIO_NOCLOSE);
138         SSL_set_bio(dtls_ssl, dtls_bio, dtls_bio);
139
140 #ifndef SSL_OP_CISCO_ANYCONNECT
141 #define SSL_OP_CISCO_ANYCONNECT 0x8000
142 #endif
143         SSL_set_options(dtls_ssl, SSL_OP_CISCO_ANYCONNECT);
144         ret = SSL_do_handshake(dtls_ssl);
145         
146         if (ret != 1) {
147                 fprintf(stderr, "DTLS connection returned %d\n", ret);
148                 if (ret < 0)
149                         fprintf(stderr, "DTLS handshake error: %d\n", SSL_get_error(dtls_ssl, ret));
150                 ERR_print_errors_fp(stderr);
151                 SSL_free(dtls_ssl);
152                 SSL_CTX_free(dtls_ctx);
153                 close(dtls_fd);
154                 return -EINVAL;
155         }
156
157         BIO_set_nbio(SSL_get_rbio(dtls_ssl),1);
158         BIO_set_nbio(SSL_get_wbio(dtls_ssl),1);
159
160         fcntl(dtls_fd, F_SETFL, fcntl(dtls_fd, F_GETFL) | O_NONBLOCK);
161
162         *ret_fd = dtls_fd;
163         *ret_ssl = dtls_ssl;
164
165         return 0;
166 }
167
168 static int dtls_rekey(struct anyconnect_info *vpninfo)
169 {
170         SSL *dtls_ssl;
171         int dtls_fd;
172
173         /* To rekey, we just 'resume' the session again */
174         if (connect_dtls_socket(vpninfo, &dtls_ssl, &dtls_fd))
175                 return -EINVAL;
176
177         vpninfo->pfds[vpninfo->dtls_pfd].fd = dtls_fd;
178
179         SSL_free(vpninfo->dtls_ssl);
180         close(vpninfo->dtls_fd);
181
182         vpninfo->dtls_ssl = dtls_ssl;
183         vpninfo->dtls_fd = dtls_fd;
184
185         return 0;
186 }
187
188 int setup_dtls(struct anyconnect_info *vpninfo)
189 {
190         struct vpn_option *dtls_opt = vpninfo->dtls_options;
191         int sessid_found = 0;
192         int dtls_port = 0;
193         int i;
194
195         while (dtls_opt) {
196                 if (verbose)
197                         printf("DTLS option %s : %s\n", dtls_opt->option, dtls_opt->value);
198
199                 if (!strcmp(dtls_opt->option, "X-DTLS-Session-ID")) {
200                         if (strlen(dtls_opt->value) != 64) {
201                                 fprintf(stderr, "X-DTLS-Session-ID not 64 characters\n");
202                                 fprintf(stderr, "Is: %s\n", dtls_opt->value);
203                                 return -EINVAL;
204                         }
205                         for (i = 0; i < 64; i += 2)
206                                 vpninfo->dtls_session_id[i/2] = hex(dtls_opt->value + i);
207                         sessid_found = 1;
208                 } else if (!strcmp(dtls_opt->option + 7, "Port")) {
209                         dtls_port = atol(dtls_opt->value);
210                 } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) {
211                         vpninfo->dtls_keepalive = atol(dtls_opt->value);
212                 } else if (!strcmp(dtls_opt->option + 7, "DPD")) {
213                         vpninfo->dtls_dpd = atol(dtls_opt->value);
214                 } else if (!strcmp(dtls_opt->option + 7, "Rekey-Time")) {
215                         vpninfo->dtls_rekey = atol(dtls_opt->value);
216                 }
217                         
218                 dtls_opt = dtls_opt->next;
219         }
220         if (!sessid_found || !dtls_port)
221                 return -EINVAL;
222
223         if (vpninfo->peer_addr->sa_family == AF_INET) {
224                 struct sockaddr_in *sin = (void *)vpninfo->peer_addr;
225                 sin->sin_port = htons(dtls_port);
226         } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
227                 struct sockaddr_in6 *sin = (void *)vpninfo->peer_addr;
228                 sin->sin6_port = htons(dtls_port);
229         } else {
230                 fprintf(stderr, "Unknown protocol family %d. Cannot do DTLS\n",
231                         vpninfo->peer_addr->sa_family);
232                 return -EINVAL;
233         }
234
235         if (connect_dtls_socket(vpninfo, &vpninfo->dtls_ssl, &vpninfo->dtls_fd))
236                 return -EINVAL;
237
238         vpninfo->dtls_pfd = vpn_add_pollfd(vpninfo, vpninfo->dtls_fd,
239                                            POLLIN|POLLHUP|POLLERR);
240         vpninfo->last_dtls_rekey = vpninfo->last_dtls_rx =
241                 vpninfo->last_dtls_tx = time(NULL);
242
243         if (verbose)
244                 printf("DTLS connected. DPD %d, Keepalive %d\n",
245                        vpninfo->dtls_dpd, vpninfo->dtls_keepalive);
246
247         return 0;
248 }
249
250 int dtls_mainloop(struct anyconnect_info *vpninfo, int *timeout)
251 {
252         unsigned char buf[2000];
253         int len;
254         int work_done = 0;
255
256         while ( (len = SSL_read(vpninfo->dtls_ssl, buf, sizeof(buf))) > 0 ) {
257                 if (verbose)
258                         printf("Received DTLS packet 0x%02x of %d bytes\n",
259                                len, buf[0]);
260
261                 vpninfo->last_dtls_rx = time(NULL);
262
263                 switch(buf[0]) {
264                 case 0:
265                         queue_new_packet(&vpninfo->incoming_queue, AF_INET, buf+1, len-1);
266                         work_done = 1;
267                         break;
268
269                 case 4: /* DPD response */
270                         if (verbose)
271                                 printf("Got DTLS DPD response\n");
272                         break;
273
274                 default:
275                         fprintf(stderr, "Unknown DTLS packet type %02x\n", buf[0]);
276                         vpninfo->quit_reason = "Unknown packet received";
277                         return 1;
278                 }
279         }
280         while (vpninfo->outgoing_queue) {
281                 struct pkt *this = vpninfo->outgoing_queue;
282                 int ret;
283
284                 vpninfo->outgoing_queue = this->next;
285
286                 buf[0] = 0;
287                 memcpy(buf + 1, this->data, this->len);
288                 
289                 ret = SSL_write(vpninfo->dtls_ssl, buf, this->len + 1);
290                 vpninfo->last_dtls_tx = time(NULL);
291                 if (verbose) {
292                         printf("Sent DTLS packet of %d bytes; SSL_write() returned %d\n",
293                                this->len, ret);
294                 }
295         }
296
297         /* DPD is bidirectional -- PKT 3 out, PKT 4 back */
298         if (vpninfo->dtls_dpd) {
299                 time_t now = time(NULL);
300                 time_t due = vpninfo->last_dtls_rx + vpninfo->dtls_dpd;
301                 time_t overdue = vpninfo->last_dtls_rx + (5 * vpninfo->dtls_dpd);
302
303                 /* If we already have DPD outstanding, don't flood */
304                 if (vpninfo->last_dtls_dpd > vpninfo->last_dtls_rx)
305                         due = vpninfo->last_dtls_dpd + vpninfo->dtls_dpd;
306                         
307                 if (now > overdue) {
308                         fprintf(stderr, "DTLS Dead Peer Detection detected dead peer!\n");
309                         /* Fall back to SSL */
310                         SSL_free(vpninfo->dtls_ssl);
311                         close(vpninfo->dtls_fd);
312                         vpninfo->dtls_ssl = NULL;
313                         vpninfo->dtls_fd = -1;
314                         return 1;
315                 }
316                 if (now >= due) {
317                         static unsigned char dtls_dpd_pkt[1] = { 3 };
318                         /* Haven't heard anything from the other end for a while.
319                            Check if it's still there */
320                         /* FIXME: If isn't, we should act on that */
321                         SSL_write(vpninfo->dtls_ssl, dtls_dpd_pkt, 1);
322                         vpninfo->last_dtls_tx = now;
323
324                         due = now + vpninfo->dtls_dpd;
325                         if (verbose)
326                                 printf("Sent DTLS DPD\n");
327                 }
328
329                 if (verbose)
330                         printf("Next DTLS DPD due in %ld seconds\n", (due - now));
331                 if (*timeout > (due - now) * 1000)
332                         *timeout = (due - now) * 1000;
333         }
334
335         /* Keepalive is just client -> server */
336         if (vpninfo->dtls_keepalive) {
337                 time_t now = time(NULL);
338                 time_t due = vpninfo->last_dtls_tx + vpninfo->dtls_keepalive;
339
340                 if (now >= due) {
341                         static unsigned char dtls_keepalive_pkt[1] = { 7 };
342
343                         /* Send something (which is discarded), to keep
344                            the connection alive. */
345                         SSL_write(vpninfo->dtls_ssl, dtls_keepalive_pkt, 1);
346                         vpninfo->last_dtls_tx = now;
347
348                         due = now + vpninfo->dtls_keepalive;
349                         if (verbose)
350                                 printf("Sent DTLS Keepalive\n");
351                 }
352
353                 if (verbose)
354                         printf("Next DTLS Keepalive due in %ld seconds\n", (due - now));
355                 if (*timeout > (due - now) * 1000)
356                         *timeout = (due - now) * 1000;
357         }
358
359         if (vpninfo->dtls_rekey) {
360                 time_t now = time(NULL);
361                 time_t due = vpninfo->last_dtls_rekey + vpninfo->dtls_rekey;
362
363                 if (now >= due) {
364                         if (verbose)
365                                 printf("DTLS rekey due\n");
366                         if (dtls_rekey(vpninfo)) {
367                                 fprintf(stderr, "DTLS rekey failed\n");
368                                 /* Fall back to SSL */
369                                 SSL_free(vpninfo->dtls_ssl);
370                                 close(vpninfo->dtls_fd);
371                                 vpninfo->dtls_ssl = NULL;
372                                 vpninfo->dtls_fd = -1;
373                                 return 1;
374                         }
375                         vpninfo->last_dtls_rekey = time(NULL);
376                         due = vpninfo->last_dtls_rekey + vpninfo->dtls_rekey;
377                 }
378                 if (verbose)
379                         printf("Next DTLS rekey due in %ld seconds\n", (due - now));
380                 if (*timeout > (due - now) * 1000)
381                         *timeout = (due - now) * 1000;
382         }
383
384         return work_done;
385 }
386
387