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