Use explicit numbers for DTLS1_BAD_VER and DTLS1_VERSION
[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
110         if (verbose)
111                 printf("SSL_SESSION is %zd bytes\n", sizeof(*dtls_session));
112         /* We're going to "resume" a session which never existed. Fake it... */
113         dtls_session = SSL_SESSION_new();
114
115         dtls_session->ssl_version = 0x0100; //DTLS1_BAD_VER;
116
117         dtls_session->master_key_length = sizeof(vpninfo->dtls_secret);
118         memcpy(dtls_session->master_key, vpninfo->dtls_secret,
119                sizeof(vpninfo->dtls_secret));
120
121         dtls_session->session_id_length = sizeof(vpninfo->dtls_session_id);
122         memcpy(dtls_session->session_id, vpninfo->dtls_session_id,
123                sizeof(vpninfo->dtls_session_id));
124
125         dtls_session->cipher = https_cipher;
126         dtls_session->cipher_id = https_cipher->id;
127
128         /* Having faked a session, add it to the CTX and the SSL */
129         if (!SSL_set_session(dtls_ssl, dtls_session)) {
130                 printf("SSL_set_session() failed with old protocol version 0x%x\n", dtls_session->ssl_version);
131                 printf("Trying the official version %x\n", 0xfeff);
132                 dtls_session->ssl_version = 0xfeff;
133                 if (!SSL_set_session(dtls_ssl, dtls_session)) {
134                         printf("SSL_set_session() failed still. Is your build ABI-compatible with your libssl?\n");
135                         return -EINVAL;
136                 }
137         }
138         if (!SSL_CTX_add_session(dtls_ctx, dtls_session))
139                 printf("SSL_CTX_add_session() failed\n");
140
141
142         /* Go Go Go! */
143         dtls_bio = BIO_new_socket(dtls_fd, BIO_NOCLOSE);
144         SSL_set_bio(dtls_ssl, dtls_bio, dtls_bio);
145
146         ret = SSL_do_handshake(dtls_ssl);
147         
148         if (ret != 1) {
149                 fprintf(stderr, "DTLS connection returned %d\n", ret);
150                 if (ret < 0)
151                         fprintf(stderr, "DTLS handshake error: %d\n", SSL_get_error(dtls_ssl, ret));
152                 ERR_print_errors_fp(stderr);
153                 SSL_free(dtls_ssl);
154                 SSL_CTX_free(dtls_ctx);
155                 close(dtls_fd);
156                 return -EINVAL;
157         }
158
159         vpninfo->dtls_fd = dtls_fd;
160         vpninfo->dtls_ssl = dtls_ssl;
161
162         return 0;
163 }
164
165 int setup_dtls(struct anyconnect_info *vpninfo)
166 {
167         struct vpn_option *dtls_opt = vpninfo->dtls_options;
168         int sessid_found = 0;
169         int dtls_port = 0;
170         int i;
171
172         while (dtls_opt) {
173                 if (verbose)
174                         printf("DTLS option %s : %s\n", dtls_opt->option, dtls_opt->value);
175
176                 if (!strcmp(dtls_opt->option, "X-DTLS-Session-ID")) {
177                         if (strlen(dtls_opt->value) != 64) {
178                                 fprintf(stderr, "X-DTLS-Session-ID not 64 characters\n");
179                                 fprintf(stderr, "Is: %s\n", dtls_opt->value);
180                                 return -EINVAL;
181                         }
182                         for (i = 0; i < 64; i += 2)
183                                 vpninfo->dtls_session_id[i/2] = hex(dtls_opt->value + i);
184                         sessid_found = 1;
185                 } else if (!strcmp(dtls_opt->option + 7, "Port")) {
186                         dtls_port = atol(dtls_opt->value);
187                 } else if (!strcmp(dtls_opt->option + 7, "Keepalive")) {
188                         vpninfo->dtls_keepalive = atol(dtls_opt->value);
189                 } else if (!strcmp(dtls_opt->option + 7, "DPD")) {
190                         vpninfo->dtls_dpd = atol(dtls_opt->value);
191                 }
192                         
193                 dtls_opt = dtls_opt->next;
194         }
195         if (!sessid_found || !dtls_port)
196                 return -EINVAL;
197
198         if (connect_dtls_socket(vpninfo, dtls_port))
199                 return -EINVAL;
200
201         BIO_set_nbio(SSL_get_rbio(vpninfo->dtls_ssl),1);
202         BIO_set_nbio(SSL_get_wbio(vpninfo->dtls_ssl),1);
203
204         fcntl(vpninfo->dtls_fd, F_SETFL, fcntl(vpninfo->dtls_fd, F_GETFL) | O_NONBLOCK);
205
206         vpn_add_pollfd(vpninfo, vpninfo->ssl_fd, POLLIN|POLLHUP|POLLERR);
207         vpninfo->last_dtls_rx = vpninfo->last_dtls_tx = time(NULL);
208
209         if (verbose)
210                 printf("DTLS connected. DPD %d, Keepalive %d\n",
211                        vpninfo->dtls_dpd, vpninfo->dtls_keepalive);
212
213         return 0;
214 }
215
216 int dtls_mainloop(struct anyconnect_info *vpninfo, int *timeout)
217 {
218         char buf[2000];
219         int len;
220         int work_done = 0;
221
222         while ( (len = SSL_read(vpninfo->dtls_ssl, buf, sizeof(buf))) > 0 ) {
223                 if (verbose) {
224                         printf("Received DTLS packet of %d bytes\n", len);
225                         printf("Packet starts %02x %02x %02x %02x %02x %02x %02x %02x\n",
226                                buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
227                 }
228                 vpninfo->last_dtls_rx = time(NULL);
229                 switch(buf[0]) {
230                 case 0:
231                         queue_new_packet(&vpninfo->incoming_queue, AF_INET, buf+1, len-1);
232                         work_done = 1;
233                         break;
234
235                 case 4: /* DPD response */
236                         if (verbose)
237                                 printf("Got DTLS DPD response\n");
238                         break;
239
240                 default:
241                         fprintf(stderr, "Unknown DTLS packet type %02x\n", buf[0]);
242                         vpninfo->quit_reason = "Unknown packet received";
243                         return 1;
244                 }
245         }
246         while (vpninfo->outgoing_queue) {
247                 struct pkt *this = vpninfo->outgoing_queue;
248                 int ret;
249
250                 vpninfo->outgoing_queue = this->next;
251
252                 buf[0] = 0;
253                 memcpy(buf + 1, this->data, this->len);
254                 
255                 ret = SSL_write(vpninfo->dtls_ssl, buf, this->len + 1);
256                 vpninfo->last_dtls_tx = time(NULL);
257                 if (verbose) {
258                         printf("Sent DTLS packet of %d bytes; SSL_write() returned %d\n",
259                                this->len, ret);
260                 }
261         }
262
263         /* DPD is bidirectional -- PKT 3 out, PKT 4 back */
264         if (vpninfo->dtls_dpd) {
265                 time_t now = time(NULL);
266                 time_t due = vpninfo->last_dtls_rx + vpninfo->dtls_dpd;
267                 time_t overdue = vpninfo->last_dtls_rx + (5 * vpninfo->dtls_dpd);
268
269                 /* If we already have DPD outstanding, don't flood */
270                 if (vpninfo->last_dtls_dpd > vpninfo->last_dtls_rx)
271                         due = vpninfo->last_dtls_dpd + vpninfo->dtls_dpd;
272                         
273                 if (now > overdue) {
274                         fprintf(stderr, "DTLS Dead Peer Detection detected dead peer!\n");
275                         /* FIXME: Can we call fack to SSL instead? */
276                         SSL_free(vpninfo->dtls_ssl);
277                         close(vpninfo->dtls_fd);
278                         vpninfo->dtls_ssl = NULL;
279                         vpninfo->dtls_fd = -1;
280                         return 1;
281                 }
282                 if (now >= due) {
283                         static unsigned char dtls_dpd_pkt[1] = { 3 };
284                         /* Haven't heard anything from the other end for a while.
285                            Check if it's still there */
286                         /* FIXME: If isn't, we should act on that */
287                         SSL_write(vpninfo->dtls_ssl, dtls_dpd_pkt, 1);
288                         vpninfo->last_dtls_tx = now;
289
290                         due = now + vpninfo->dtls_dpd;
291                         if (verbose)
292                                 printf("Sent DTLS DPD\n");
293                 }
294
295                 if (verbose)
296                         printf("Next DTLS DPD due in %ld seconds\n", (due - now));
297                 if (*timeout > (due - now) * 1000)
298                         *timeout = (due - now) * 1000;
299         }
300
301         /* Keepalive is just client -> server */
302         if (vpninfo->dtls_keepalive) {
303                 time_t now = time(NULL);
304                 time_t due = vpninfo->last_dtls_tx + vpninfo->dtls_keepalive;
305
306                 if (now >= due) {
307                         static unsigned char dtls_keepalive_pkt[1] = { 7 };
308
309                         /* Send something (which is discarded), to keep
310                            the connection alive. */
311                         SSL_write(vpninfo->dtls_ssl, dtls_keepalive_pkt, 1);
312                         vpninfo->last_dtls_tx = now;
313
314                         due = now + vpninfo->dtls_keepalive;
315                         if (verbose)
316                                 printf("Sent DTLS Keepalive\n");
317                 }
318
319                 if (verbose)
320                         printf("Next DTLS Keepalive due in %ld seconds\n", (due - now));
321                 if (*timeout > (due - now) * 1000)
322                         *timeout = (due - now) * 1000;
323         }
324
325
326         /* FIXME: Keepalive */
327         return work_done;
328 }
329
330