1 /*
2  * OpenConnect (SSL + DTLS) VPN client
3  *
4  * Copyright © 2008-2015 Intel Corporation.
5  *
6  * Author: David Woodhouse <dwmw2@infradead.org>
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * version 2.1, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  */
17 
18 #include <config.h>
19 
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <errno.h>
26 
27 #include "openconnect-internal.h"
28 #include "lzo.h"
29 
print_esp_keys(struct openconnect_info * vpninfo,const char * name,struct esp * esp)30 int print_esp_keys(struct openconnect_info *vpninfo, const char *name, struct esp *esp)
31 {
32 	int i;
33 	const char *enctype, *mactype;
34 	char enckey[256], mackey[256];
35 
36 	switch(vpninfo->esp_enc) {
37 	case ENC_AES_128_CBC:
38 		enctype = "AES-128-CBC (RFC3602)";
39 		break;
40 	case ENC_AES_256_CBC:
41 		enctype = "AES-256-CBC (RFC3602)";
42 		break;
43 	default:
44 		return -EINVAL;
45 	}
46 	switch(vpninfo->esp_hmac) {
47 	case HMAC_MD5:
48 		mactype = "HMAC-MD5-96 (RFC2403)";
49 		break;
50 	case HMAC_SHA1:
51 		mactype = "HMAC-SHA-1-96 (RFC2404)";
52 		break;
53 	case HMAC_SHA256:
54 		mactype = "HMAC-SHA-256-128 (RFC4868)";
55 		break;
56 	default:
57 		return -EINVAL;
58 	}
59 
60 	for (i = 0; i < vpninfo->enc_key_len; i++)
61 		sprintf(enckey + (2 * i), "%02x", esp->enc_key[i]);
62 	for (i = 0; i < vpninfo->hmac_key_len; i++)
63 		sprintf(mackey + (2 * i), "%02x", esp->hmac_key[i]);
64 
65 	vpn_progress(vpninfo, PRG_TRACE,
66 		     _("Parameters for %s ESP: SPI 0x%08x\n"),
67 		     name, (unsigned)ntohl(esp->spi));
68 	vpn_progress(vpninfo, PRG_TRACE,
69 		     _("ESP encryption type %s key 0x%s\n"),
70 		     enctype, enckey);
71 	vpn_progress(vpninfo, PRG_TRACE,
72 		     _("ESP authentication type %s key 0x%s\n"),
73 		     mactype, mackey);
74 	return 0;
75 }
76 
esp_setup(struct openconnect_info * vpninfo,int dtls_attempt_period)77 int esp_setup(struct openconnect_info *vpninfo, int dtls_attempt_period)
78 {
79 	if (vpninfo->dtls_state == DTLS_DISABLED ||
80 	    vpninfo->dtls_state == DTLS_NOSECRET)
81 		return -EINVAL;
82 
83 	if (vpninfo->esp_ssl_fallback)
84 		vpninfo->dtls_times.dpd = vpninfo->esp_ssl_fallback;
85 	else
86 		vpninfo->dtls_times.dpd = dtls_attempt_period;
87 
88 	vpninfo->dtls_attempt_period = dtls_attempt_period;
89 
90 	print_esp_keys(vpninfo, _("incoming"), &vpninfo->esp_in[vpninfo->current_esp_in]);
91 	print_esp_keys(vpninfo, _("outgoing"), &vpninfo->esp_out);
92 
93 	vpn_progress(vpninfo, PRG_DEBUG, _("Send ESP probes\n"));
94 	if (vpninfo->proto->udp_send_probes)
95 		vpninfo->proto->udp_send_probes(vpninfo);
96 
97 	return 0;
98 }
99 
construct_esp_packet(struct openconnect_info * vpninfo,struct pkt * pkt,uint8_t next_hdr)100 int construct_esp_packet(struct openconnect_info *vpninfo, struct pkt *pkt, uint8_t next_hdr)
101 {
102 	const int blksize = 16;
103 	int i, padlen, ret;
104 
105 	if (!next_hdr) {
106 		if ((pkt->data[0] & 0xf0) == 0x60) /* iph->ip_v */
107 			next_hdr = IPPROTO_IPV6;
108 		else
109 			next_hdr = IPPROTO_IPIP;
110 	}
111 
112 	/* This gets much more fun if the IV is variable-length */
113 	pkt->esp.spi = vpninfo->esp_out.spi;
114 	pkt->esp.seq = htonl(vpninfo->esp_out.seq++);
115 
116 	padlen = blksize - 1 - ((pkt->len + 1) % blksize);
117 	for (i=0; i<padlen; i++)
118 		pkt->data[pkt->len + i] = i + 1;
119 	pkt->data[pkt->len + padlen] = padlen;
120 	pkt->data[pkt->len + padlen + 1] = next_hdr;
121 
122 	memcpy(pkt->esp.iv, vpninfo->esp_out.iv, sizeof(pkt->esp.iv));
123 
124 	ret = encrypt_esp_packet(vpninfo, pkt, pkt->len + padlen + 2);
125 	if (ret)
126 		return ret;
127 
128 	return sizeof(pkt->esp) + pkt->len + padlen + 2 + vpninfo->hmac_out_len;
129 }
130 
esp_mainloop(struct openconnect_info * vpninfo,int * timeout,int readable)131 int esp_mainloop(struct openconnect_info *vpninfo, int *timeout, int readable)
132 {
133 	struct esp *esp = &vpninfo->esp_in[vpninfo->current_esp_in];
134 	struct esp *old_esp = &vpninfo->esp_in[vpninfo->current_esp_in ^ 1];
135 	struct pkt *this;
136 	int work_done = 0;
137 	int ret;
138 
139 	/* Some servers send us packets that are larger than negotiated
140 	   MTU, or lack the ability to negotiate MTU (see gpst.c). We
141 	   reserve some extra space to handle that */
142 	int receive_mtu = MAX(2048, vpninfo->ip_info.mtu + 256);
143 
144 	if (vpninfo->dtls_state == DTLS_SLEEPING) {
145 		if (ka_check_deadline(timeout, time(NULL), vpninfo->new_dtls_started + vpninfo->dtls_attempt_period)
146 		    || vpninfo->dtls_need_reconnect) {
147 			vpn_progress(vpninfo, PRG_DEBUG, _("Send ESP probes\n"));
148 			if (vpninfo->proto->udp_send_probes)
149 				vpninfo->proto->udp_send_probes(vpninfo);
150 		}
151 	}
152 	if (vpninfo->dtls_fd == -1)
153 		return 0;
154 
155 	while (readable) {
156 		int len = receive_mtu + vpninfo->pkt_trailer;
157 		int i;
158 		struct pkt *pkt;
159 
160 		if (!vpninfo->dtls_pkt) {
161 			vpninfo->dtls_pkt = malloc(sizeof(struct pkt) + len);
162 			if (!vpninfo->dtls_pkt) {
163 				vpn_progress(vpninfo, PRG_ERR, _("Allocation failed\n"));
164 				break;
165 			}
166 		}
167 		pkt = vpninfo->dtls_pkt;
168 		len = recv(vpninfo->dtls_fd, (void *)&pkt->esp, len + sizeof(pkt->esp), 0);
169 		if (len <= 0)
170 			break;
171 
172 		vpn_progress(vpninfo, PRG_TRACE, _("Received ESP packet of %d bytes\n"),
173 			     len);
174 		work_done = 1;
175 
176 		/* both supported algos (SHA1 and MD5) have 12-byte MAC lengths (RFC2403 and RFC2404) */
177 		if (len <= sizeof(pkt->esp) + vpninfo->hmac_out_len)
178 			continue;
179 
180 		len -= sizeof(pkt->esp) + vpninfo->hmac_out_len;
181 		pkt->len = len;
182 
183 		if (pkt->esp.spi == esp->spi) {
184 			if (decrypt_esp_packet(vpninfo, esp, pkt))
185 				continue;
186 		} else if (pkt->esp.spi == old_esp->spi &&
187 			   ntohl(pkt->esp.seq) + esp->seq < vpninfo->old_esp_maxseq) {
188 			vpn_progress(vpninfo, PRG_TRACE,
189 				     _("Received ESP packet from old SPI 0x%x, seq %u\n"),
190 				     (unsigned)ntohl(old_esp->spi), (unsigned)ntohl(pkt->esp.seq));
191 			if (decrypt_esp_packet(vpninfo, old_esp, pkt))
192 				continue;
193 		} else {
194 			vpn_progress(vpninfo, PRG_DEBUG,
195 				     _("Received ESP packet with invalid SPI 0x%08x\n"),
196 				     (unsigned)ntohl(pkt->esp.spi));
197 			continue;
198 		}
199 
200 		/* Possible values of the Next Header field are:
201 		   0x04: IP[v4]-in-IP
202 		   0x05: supposed to mean Internet Stream Protocol
203 		         (XXX: but used for LZO compressed packets by Juniper)
204 		   0x29: IPv6 encapsulation */
205 		if (pkt->data[len - 1] != 0x04 && pkt->data[len - 1] != 0x29 &&
206 		    pkt->data[len - 1] != 0x05) {
207 			vpn_progress(vpninfo, PRG_ERR,
208 				     _("Received ESP packet with unrecognised payload type %02x\n"),
209 				     pkt->data[len-1]);
210 			continue;
211 		}
212 
213 		if (len <= 2 + pkt->data[len - 2]) {
214 			vpn_progress(vpninfo, PRG_ERR,
215 				     _("Invalid padding length %02x in ESP\n"),
216 				     pkt->data[len - 2]);
217 			continue;
218 		}
219 		pkt->len = len - 2 - pkt->data[len - 2];
220 		for (i = 0 ; i < pkt->data[len - 2]; i++) {
221 			if (pkt->data[pkt->len + i] != i + 1)
222 				break; /* We can't just 'continue' here because it
223 					* would only break out of this 'for' loop */
224 		}
225 		if (i != pkt->data[len - 2]) {
226 			vpn_progress(vpninfo, PRG_ERR,
227 				     _("Invalid padding bytes in ESP\n"));
228 			continue; /* We can here, though */
229 		}
230 		vpninfo->dtls_times.last_rx = time(NULL);
231 
232 		if (vpninfo->proto->udp_catch_probe) {
233 			if (vpninfo->proto->udp_catch_probe(vpninfo, pkt)) {
234 				if (vpninfo->dtls_state == DTLS_SLEEPING) {
235 					vpn_progress(vpninfo, PRG_INFO,
236 						     _("ESP session established with server\n"));
237 					vpninfo->dtls_state = DTLS_CONNECTING;
238 				}
239 				continue;
240 			}
241 		}
242 		if (pkt->data[len - 1] == 0x05) {
243 			struct pkt *newpkt = malloc(sizeof(*pkt) + receive_mtu + vpninfo->pkt_trailer);
244 			int newlen = receive_mtu;
245 			if (!newpkt) {
246 				vpn_progress(vpninfo, PRG_ERR,
247 					     _("Failed to allocate memory to decrypt ESP packet\n"));
248 				continue;
249 			}
250 			if (av_lzo1x_decode(newpkt->data, &newlen,
251 					    pkt->data, &pkt->len) || pkt->len) {
252 				vpn_progress(vpninfo, PRG_ERR,
253 					     _("LZO decompression of ESP packet failed\n"));
254 				free(newpkt);
255 				continue;
256 			}
257 			newpkt->len = receive_mtu - newlen;
258 			vpn_progress(vpninfo, PRG_TRACE,
259 				     _("LZO decompressed %d bytes into %d\n"),
260 				     len - 2 - pkt->data[len-2], newpkt->len);
261 			queue_packet(&vpninfo->incoming_queue, newpkt);
262 		} else {
263 			queue_packet(&vpninfo->incoming_queue, pkt);
264 			vpninfo->dtls_pkt = NULL;
265 		}
266 	}
267 
268 	if (vpninfo->dtls_state != DTLS_CONNECTED)
269 		return 0;
270 
271 	switch (keepalive_action(&vpninfo->dtls_times, timeout)) {
272 	case KA_REKEY:
273 		vpn_progress(vpninfo, PRG_ERR, _("Rekey not implemented for ESP\n"));
274 		break;
275 
276 	case KA_DPD_DEAD:
277 		vpn_progress(vpninfo, PRG_ERR, _("ESP detected dead peer\n"));
278 		if (vpninfo->proto->udp_close)
279 			vpninfo->proto->udp_close(vpninfo);
280 		if (vpninfo->proto->udp_send_probes)
281 			vpninfo->proto->udp_send_probes(vpninfo);
282 		return 1;
283 
284 	case KA_DPD:
285 		vpn_progress(vpninfo, PRG_DEBUG, _("Send ESP probes for DPD\n"));
286 		if (vpninfo->proto->udp_send_probes)
287 			vpninfo->proto->udp_send_probes(vpninfo);
288 		work_done = 1;
289 		break;
290 
291 	case KA_KEEPALIVE:
292 		vpn_progress(vpninfo, PRG_ERR, _("Keepalive not implemented for ESP\n"));
293 		break;
294 
295 	case KA_NONE:
296 		break;
297 	}
298 	while (1) {
299 		int len;
300 
301 		if (vpninfo->deflate_pkt) {
302 			this = vpninfo->deflate_pkt;
303 			len = this->len;
304 		} else {
305 			this = dequeue_packet(&vpninfo->outgoing_queue);
306 			if (!this)
307 				break;
308 
309 			if (vpninfo->proto->udp_send_probes == oncp_esp_send_probes) {
310 				uint8_t dontsend;
311 
312 				/* Pulse/NC can only accept ESP of the same protocol as the one
313 				 * you connected to it with. The other has to go over IF-T/TLS. */
314 				if (vpninfo->dtls_addr->sa_family == AF_INET6)
315 					dontsend = 0x40;
316 				else
317 					dontsend = 0x60;
318 
319 				if ( (this->data[0] & 0xf0) == dontsend) {
320 					store_be32(&this->pulse.vendor, 0xa4c);
321 					store_be32(&this->pulse.type, 4);
322 					store_be32(&this->pulse.len, this->len + 16);
323 					queue_packet(&vpninfo->oncp_control_queue, this);
324 					work_done = 1;
325 					continue;
326 				}
327 			}
328 
329 			/* XX: Must precede in-place encryption of the packet, because
330 			   IP header fields (version and TOS) are garbled afterward.
331 			   If TOS optname is set, we want to copy the TOS/TCLASS header
332 			   to the outer UDP packet */
333 			if (vpninfo->dtls_tos_optname)
334 				udp_tos_update(vpninfo, this);
335 
336 			len = construct_esp_packet(vpninfo, this, 0);
337 			if (len < 0) {
338 				/* Should we disable ESP? */
339 				free(this);
340 				work_done = 1;
341 				continue;
342 			}
343 		}
344 
345 		ret = send(vpninfo->dtls_fd, (void *)&this->esp, len, 0);
346 		if (ret < 0) {
347 			/* Not that this is likely to happen with UDP, but... */
348 			if (errno == ENOBUFS || errno == EAGAIN || errno == EWOULDBLOCK) {
349 				int err = errno;
350 				vpninfo->deflate_pkt = this;
351 				this->len = len;
352 				vpn_progress(vpninfo, PRG_DEBUG,
353 					     _("Requeueing failed ESP send: %s\n"),
354 					     strerror(err));
355 				monitor_write_fd(vpninfo, dtls);
356 				return work_done;
357 			} else {
358 				/* A real error in sending. Fall back to TCP? */
359 				vpn_progress(vpninfo, PRG_ERR,
360 					_("Failed to send ESP packet: %s\n"),
361 					strerror(errno));
362 			}
363 		} else {
364 			vpninfo->dtls_times.last_tx = time(NULL);
365 
366 			vpn_progress(vpninfo, PRG_TRACE, _("Sent ESP packet of %d bytes\n"),
367 				     len);
368 		}
369 		if (this == vpninfo->deflate_pkt) {
370 			unmonitor_write_fd(vpninfo, dtls);
371 			vpninfo->deflate_pkt = NULL;
372 		}
373 		free(this);
374 		work_done = 1;
375 	}
376 
377 	return work_done;
378 }
379 
esp_close(struct openconnect_info * vpninfo)380 void esp_close(struct openconnect_info *vpninfo)
381 {
382 	/* We close and reopen the socket in case we roamed and our
383 	   local IP address has changed. */
384 	if (vpninfo->dtls_fd != -1) {
385 		closesocket(vpninfo->dtls_fd);
386 		unmonitor_read_fd(vpninfo, dtls);
387 		unmonitor_write_fd(vpninfo, dtls);
388 		unmonitor_except_fd(vpninfo, dtls);
389 		vpninfo->dtls_fd = -1;
390 	}
391 	if (vpninfo->dtls_state > DTLS_DISABLED)
392 		vpninfo->dtls_state = DTLS_SLEEPING;
393 	if (vpninfo->deflate_pkt) {
394 		free(vpninfo->deflate_pkt);
395 		vpninfo->deflate_pkt = NULL;
396 	}
397 }
398 
esp_shutdown(struct openconnect_info * vpninfo)399 void esp_shutdown(struct openconnect_info *vpninfo)
400 {
401 	destroy_esp_ciphers(&vpninfo->esp_in[0]);
402 	destroy_esp_ciphers(&vpninfo->esp_in[1]);
403 	destroy_esp_ciphers(&vpninfo->esp_out);
404 	if (vpninfo->proto->udp_close)
405 		vpninfo->proto->udp_close(vpninfo);
406 	if (vpninfo->dtls_state != DTLS_DISABLED)
407 		vpninfo->dtls_state = DTLS_NOSECRET;
408 }
409 
openconnect_setup_esp_keys(struct openconnect_info * vpninfo,int new_keys)410 int openconnect_setup_esp_keys(struct openconnect_info *vpninfo, int new_keys)
411 {
412 	struct esp *esp_in;
413 	int ret;
414 
415 	if (vpninfo->dtls_state == DTLS_DISABLED)
416 		return -EOPNOTSUPP;
417 	if (!vpninfo->dtls_addr)
418 		return -EINVAL;
419 
420 	if (vpninfo->esp_hmac == HMAC_SHA256)
421 		vpninfo->hmac_out_len = 16;
422 	else /* MD5 and SHA1 */
423 		vpninfo->hmac_out_len = 12;
424 
425 	if (new_keys) {
426 		vpninfo->old_esp_maxseq = vpninfo->esp_in[vpninfo->current_esp_in].seq + 32;
427 		vpninfo->current_esp_in ^= 1;
428 	}
429 
430 	esp_in = &vpninfo->esp_in[vpninfo->current_esp_in];
431 
432 	if (new_keys) {
433 		if (openconnect_random(&esp_in->spi, sizeof(esp_in->spi)) ||
434 		    openconnect_random((void *)&esp_in->enc_key, vpninfo->enc_key_len) ||
435 		    openconnect_random((void *)&esp_in->hmac_key, vpninfo->hmac_key_len)) {
436 			vpn_progress(vpninfo, PRG_ERR,
437 				     _("Failed to generate random keys for ESP\n"));
438 			return -EIO;
439 		}
440 	}
441 
442 	if (openconnect_random(vpninfo->esp_out.iv, sizeof(vpninfo->esp_out.iv))) {
443 		vpn_progress(vpninfo, PRG_ERR,
444 			     _("Failed to generate initial IV for ESP\n"));
445 		return -EIO;
446 	}
447 
448 	/* This is the minimum; some implementations may increase it */
449 	vpninfo->pkt_trailer = MAX_ESP_PAD + MAX_IV_SIZE + MAX_HMAC_SIZE;
450 
451 	vpninfo->esp_out.seq = vpninfo->esp_out.seq_backlog = 0;
452 	esp_in->seq = esp_in->seq_backlog = 0;
453 
454 	ret = init_esp_ciphers(vpninfo, &vpninfo->esp_out, esp_in);
455 	if (ret)
456 		return ret;
457 
458 	if (vpninfo->dtls_state == DTLS_NOSECRET)
459 		vpninfo->dtls_state = DTLS_SECRET;
460 
461 	return 0;
462 }
463