silence warnings, and output
[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  * This code works when run against Cisco's own libssl.so.0.9.8, but
38  * fails (Bad Record MAC on receipt of the Server Hello) when run
39  * against my own build of OpenSSL-0.9.8f.
40  *
41  * It lookslike they've reverted _some_ of the changes beween 0.9.8e
42  * and 0.9.8f, but not all of them. In particular, they use
43  * DTLS1_BAD_VER for the protocol version.
44  *
45  * Using OpenSSL-0.9.8e, which was the last release of OpenSSL to use
46  * DTLS1_BAD_VER, also fails similarly.
47  *
48  * Hopefully they're just using something equivalent to a snapshot
49  * between 0.9.8e and 0.9.8f, and they don't have their own "special"
50  * changes on top.
51  */   
52
53 static unsigned char nybble(unsigned char n)
54 {
55         if      (n >= '0' && n <= '9') return n - '0';
56         else if (n >= 'A' && n <= 'F') return n - ('A' - 10);
57         else if (n >= 'a' && n <= 'f') return n - ('a' - 10);
58         return 0;
59 }
60
61 static unsigned char hex(const char *data)
62 {
63         return (nybble(data[0]) << 4) | nybble(data[1]);
64 }
65
66 static int connect_dtls_socket(struct anyconnect_info *vpninfo, int dtls_port)
67 {
68         SSL_METHOD *dtls_method;
69         SSL_CTX *dtls_ctx;
70         SSL_SESSION *dtls_session;
71         SSL_CIPHER *https_cipher;
72         SSL *dtls_ssl;
73         BIO *dtls_bio;
74         int dtls_fd;
75         int ret;
76
77         if (vpninfo->peer_addr->sa_family == AF_INET) {
78                 struct sockaddr_in *sin = (void *)vpninfo->peer_addr;
79                 sin->sin_port = htons(dtls_port);
80         } else if (vpninfo->peer_addr->sa_family == AF_INET6) {
81                 struct sockaddr_in6 *sin = (void *)vpninfo->peer_addr;
82                 sin->sin6_port = htons(dtls_port);
83         } else {
84                 fprintf(stderr, "Unknown protocol family %d. Cannot do DTLS\n",
85                         vpninfo->peer_addr->sa_family);
86                 return -EINVAL;
87         }
88
89         dtls_fd = socket(vpninfo->peer_addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
90         if (dtls_fd < 0) {
91                 perror("Open UDP socket for DTLS:");
92                 return -EINVAL;
93         }
94         
95         if (connect(dtls_fd, vpninfo->peer_addr, vpninfo->peer_addrlen)) {
96                 perror("UDP (DTLS) connect:\n");
97                 close(dtls_fd);
98                 return -EINVAL;
99         }
100
101         dtls_method = DTLSv1_client_method();
102         dtls_ctx = SSL_CTX_new(dtls_method);
103         SSL_CTX_set_read_ahead(dtls_ctx, 1);
104         https_cipher = SSL_get_current_cipher(vpninfo->https_ssl);
105
106         dtls_ssl = SSL_new(dtls_ctx);
107         SSL_set_connect_state(dtls_ssl);
108         SSL_set_cipher_list(dtls_ssl, SSL_CIPHER_get_name(https_cipher));
109         printf("SSL_SESSION is %d bytes\n", sizeof(*dtls_session));
110         /* We're going to "resume" a session which never existed. Fake it... */
111         dtls_session = SSL_SESSION_new();
112
113         dtls_session->ssl_version = DTLS1_BAD_VER;
114
115         dtls_session->master_key_length = sizeof(vpninfo->dtls_secret);
116         memcpy(dtls_session->master_key, vpninfo->dtls_secret,
117                sizeof(vpninfo->dtls_secret));
118
119         dtls_session->session_id_length = sizeof(vpninfo->dtls_session_id);
120         memcpy(dtls_session->session_id, vpninfo->dtls_session_id,
121                sizeof(vpninfo->dtls_session_id));
122
123         dtls_session->cipher = https_cipher;
124         dtls_session->cipher_id = https_cipher->id;
125
126         /* Having faked a session, add it to the CTX and the SSL */
127         if (!SSL_set_session(dtls_ssl, dtls_session)) {
128                 printf("SSL_set_session() failed with old protocol version 0x%x\n", dtls_session->ssl_version);
129                 printf("Trying the official version %x\n", DTLS1_VERSION);
130                 dtls_session->ssl_version = DTLS1_VERSION;
131                 if (!SSL_set_session(dtls_ssl, dtls_session)) {
132                         printf("SSL_set_session() failed still. Is your build ABI-compatible with your libssl?\n");
133                         return -EINVAL;
134                 }
135         }
136         if (!SSL_CTX_add_session(dtls_ctx, dtls_session))
137                 printf("SSL_CTX_add_session() failed\n");
138
139
140         /* Go Go Go! */
141         dtls_bio = BIO_new_socket(dtls_fd, BIO_NOCLOSE);
142         SSL_set_bio(dtls_ssl, dtls_bio, dtls_bio);
143
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         vpninfo->dtls_fd = dtls_fd;
158         vpninfo->dtls_ssl = dtls_ssl;
159
160         return 0;
161 }
162
163 int setup_dtls(struct anyconnect_info *vpninfo)
164 {
165         struct vpn_option *dtls_opt = vpninfo->dtls_options;
166         int sessid_found = 0;
167         int dtls_port = 0;
168         int i;
169
170         while (dtls_opt) {
171                 if (verbose)
172                         printf("DTLS option %s : %s\n", dtls_opt->option, dtls_opt->value);
173
174                 if (!strcmp(dtls_opt->option, "X-DTLS-Session-ID")) {
175                         if (strlen(dtls_opt->value) != 64) {
176                                 fprintf(stderr, "X-DTLS-Session-ID not 64 characters\n");
177                                 fprintf(stderr, "Is: %s\n", dtls_opt->value);
178                                 return -EINVAL;
179                         }
180                         for (i = 0; i < 64; i += 2)
181                                 vpninfo->dtls_session_id[i/2] = hex(dtls_opt->value + i);
182                         sessid_found = 1;
183                 } else if (!strcmp(dtls_opt->option + 7, "Port")) {
184                         dtls_port = atol(dtls_opt->value);
185                 } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) {
186                         vpninfo->dtls_keepalive = atol(dtls_opt->value);
187                 } else if (!strcmp(dtls_opt->option + 7, "DPD")) {
188                         vpninfo->dtls_dpd = atol(dtls_opt->value);
189                 }
190                         
191                 dtls_opt = dtls_opt->next;
192         }
193         if (!sessid_found || !dtls_port)
194                 return -EINVAL;
195
196         if (connect_dtls_socket(vpninfo, dtls_port))
197                 return -EINVAL;
198
199         BIO_set_nbio(SSL_get_rbio(vpninfo->dtls_ssl),1);
200         BIO_set_nbio(SSL_get_wbio(vpninfo->dtls_ssl),1);
201
202         fcntl(vpninfo->dtls_fd, F_SETFL, fcntl(vpninfo->dtls_fd, F_GETFL) | O_NONBLOCK);
203
204         vpn_add_pollfd(vpninfo, vpninfo->ssl_fd, POLLIN|POLLHUP|POLLERR);
205         vpninfo->last_dtls_rx = vpninfo->last_dtls_tx = time(NULL);
206
207         if (verbose)
208                 printf("DTLS connected. DPD %d, Keepalive %d\n",
209                        vpninfo->dtls_dpd, vpninfo->dtls_keepalive);
210
211         return 0;
212 }
213
214 int dtls_mainloop(struct anyconnect_info *vpninfo, int *timeout)
215 {
216         char buf[2000];
217         int len;
218         int work_done = 0;
219
220         while ( (len = SSL_read(vpninfo->dtls_ssl, buf, sizeof(buf))) > 0 ) {
221                 if (verbose) {
222                         printf("Received DTLS packet of %d bytes\n", len);
223                         printf("Packet starts %02x %02x %02x %02x %02x %02x %02x %02x\n",
224                                buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
225                 }
226                 vpninfo->last_dtls_rx = time(NULL);
227                 switch(buf[0]) {
228                 case 0:
229                         queue_new_packet(&vpninfo->incoming_queue, AF_INET, buf+1, len-1);
230                         work_done = 1;
231                         break;
232
233                 case 4: /* DPD response */
234                         if (verbose)
235                                 printf("Got DTLS DPD response\n");
236                         break;
237
238                 default:
239                         fprintf(stderr, "Unknown DTLS packet type %02x\n", buf[0]);
240                         vpninfo->quit_reason = "Unknown packet received";
241                         return 1;
242                 }
243         }
244         while (vpninfo->outgoing_queue) {
245                 struct pkt *this = vpninfo->outgoing_queue;
246                 int ret;
247
248                 vpninfo->outgoing_queue = this->next;
249
250                 buf[0] = 0;
251                 memcpy(buf + 1, this->data, this->len);
252                 
253                 ret = SSL_write(vpninfo->dtls_ssl, buf, this->len + 1);
254                 vpninfo->last_dtls_tx = time(NULL);
255                 if (verbose) {
256                         printf("Sent DTLS packet of %d bytes; SSL_write() returned %d\n",
257                                this->len, ret);
258                 }
259         }
260
261         /* DPD is bidirectional -- PKT 3 out, PKT 4 back */
262         if (vpninfo->dtls_dpd) {
263                 time_t now = time(NULL);
264                 time_t due = vpninfo->last_dtls_rx + vpninfo->dtls_dpd;
265                 time_t overdue = vpninfo->last_dtls_rx + (5 * vpninfo->dtls_dpd);
266
267                 /* If we already have DPD outstanding, don't flood */
268                 if (vpninfo->last_dtls_dpd > vpninfo->last_dtls_rx)
269                         due = vpninfo->last_dtls_dpd + vpninfo->dtls_dpd;
270                         
271                 if (now > overdue) {
272                         fprintf(stderr, "DTLS Dead Peer Detection detected dead peer!\n");
273                         /* FIXME: Can we call fack to SSL instead? */
274                         SSL_free(vpninfo->dtls_ssl);
275                         close(vpninfo->dtls_fd);
276                         vpninfo->dtls_ssl = NULL;
277                         vpninfo->dtls_fd = -1;
278                         return 1;
279                 }
280                 if (now >= due) {
281                         static unsigned char dtls_dpd_pkt[1] = { 3 };
282                         /* Haven't heard anything from the other end for a while.
283                            Check if it's still there */
284                         /* FIXME: If isn't, we should act on that */
285                         SSL_write(vpninfo->dtls_ssl, dtls_dpd_pkt, 1);
286                         vpninfo->last_dtls_tx = now;
287
288                         due = now + vpninfo->dtls_dpd;
289                         if (verbose)
290                                 printf("Sent DTLS DPD\n");
291                 }
292
293                 if (verbose)
294                         printf("Next DTLS DPD due in %ld seconds\n", (due - now));
295                 if (*timeout > (due - now) * 1000)
296                         *timeout = (due - now) * 1000;
297         }
298
299         /* Keepalive is just client -> server */
300         if (vpninfo->dtls_keepalive) {
301                 time_t now = time(NULL);
302                 time_t due = vpninfo->last_dtls_tx + vpninfo->dtls_keepalive;
303
304                 if (now >= due) {
305                         static unsigned char dtls_keepalive_pkt[1] = { 7 };
306
307                         /* Send something (which is discarded), to keep
308                            the connection alive. */
309                         SSL_write(vpninfo->dtls_ssl, dtls_keepalive_pkt, 1);
310                         vpninfo->last_dtls_tx = now;
311
312                         due = now + vpninfo->dtls_keepalive;
313                         if (verbose)
314                                 printf("Sent DTLS Keepalive\n");
315                 }
316
317                 if (verbose)
318                         printf("Next DTLS Keepalive due in %ld seconds\n", (due - now));
319                 if (*timeout > (due - now) * 1000)
320                         *timeout = (due - now) * 1000;
321         }
322
323
324         /* FIXME: Keepalive */
325         return work_done;
326 }
327
328