1 /* IPSec VPN client compatible with Cisco equipment.
2    Copyright (C) 2002      Geoffrey Keating
3    Copyright (C) 2003-2005 Maurice Massar
4    Copyright (C) 2004      Tomas Mraz
5    Copyright (C) 2004      Martin von Gagern
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 
21    $Id: vpnc.c 371 2008-11-19 20:55:28Z Joerg Mayer $
22 */
23 
24 #define _GNU_SOURCE
25 #include <assert.h>
26 #include <unistd.h>
27 #include <sys/fcntl.h>
28 #include <stdio.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <time.h>
32 #include <stdlib.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <netdb.h>
36 #include <arpa/inet.h>
37 #include <poll.h>
38 #include <sys/ioctl.h>
39 #include <sys/utsname.h>
40 
41 #include <gcrypt.h>
42 
43 #ifdef OPENSSL_GPL_VIOLATION
44 /* OpenSSL */
45 #include <openssl/x509.h>
46 #include <openssl/err.h>
47 #endif /* OPENSSL_GPL_VIOLATION */
48 
49 #include "sysdep.h"
50 #include "config.h"
51 #include "isakmp-pkt.h"
52 #include "math_group.h"
53 #include "dh.h"
54 #include "vpnc.h"
55 #include "tunip.h"
56 #include "supp.h"
57 
58 #if defined(__CYGWIN__)
59 	GCRY_THREAD_OPTION_PTHREAD_IMPL;
60 #endif
61 
62 #define ISAKMP_PORT (500)
63 #define ISAKMP_PORT_NATT (4500)
64 
65 const unsigned char VID_XAUTH[] = { /* "draft-ietf-ipsra-isakmp-xauth-06.txt"/8 */
66 	0x09, 0x00, 0x26, 0x89, 0xDF, 0xD6, 0xB7, 0x12
67 };
68 const unsigned char VID_DPD[] = { /* Dead Peer Detection, RFC 3706 */
69 	0xAF, 0xCA, 0xD7, 0x13, 0x68, 0xA1, 0xF1, 0xC9,
70 	0x6B, 0x86, 0x96, 0xFC, 0x77, 0x57, 0x01, 0x00
71 };
72 const unsigned char VID_UNITY[] = { /* "CISCO-UNITY"/14 + major + minor */
73 	0x12, 0xF5, 0xF2, 0x8C, 0x45, 0x71, 0x68, 0xA9,
74 	0x70, 0x2D, 0x9F, 0xE2, 0x74, 0xCC, 0x01, 0x00
75 };
76 const unsigned char VID_UNKNOWN[] = {
77 	0x12, 0x6E, 0x1F, 0x57, 0x72, 0x91, 0x15, 0x3B,
78 	0x20, 0x48, 0x5F, 0x7F, 0x15, 0x5B, 0x4B, 0xC8
79 };
80 const unsigned char VID_NATT_00[] = { /* "draft-ietf-ipsec-nat-t-ike-00" */
81 	0x44, 0x85, 0x15, 0x2d, 0x18, 0xb6, 0xbb, 0xcd,
82 	0x0b, 0xe8, 0xa8, 0x46, 0x95, 0x79, 0xdd, 0xcc
83 };
84 const unsigned char VID_NATT_01[] = { /* "draft-ietf-ipsec-nat-t-ike-01" */
85 	0x16, 0xf6, 0xca, 0x16, 0xe4, 0xa4, 0x06, 0x6d,
86 	0x83, 0x82, 0x1a, 0x0f, 0x0a, 0xea, 0xa8, 0x62
87 };
88 const unsigned char VID_NATT_02[] = { /* "draft-ietf-ipsec-nat-t-ike-02" */
89 	0xcd, 0x60, 0x46, 0x43, 0x35, 0xdf, 0x21, 0xf8,
90 	0x7c, 0xfd, 0xb2, 0xfc, 0x68, 0xb6, 0xa4, 0x48
91 };
92 const unsigned char VID_NATT_02N[] = { /* "draft-ietf-ipsec-nat-t-ike-02\n" */
93 	0x90, 0xCB, 0x80, 0x91, 0x3E, 0xBB, 0x69, 0x6E,
94 	0x08, 0x63, 0x81, 0xB5, 0xEC, 0x42, 0x7B, 0x1F
95 };
96 const unsigned char VID_NATT_RFC[] = { /* "RFC 3947" */
97 	0x4A, 0x13, 0x1C, 0x81, 0x07, 0x03, 0x58, 0x45,
98 	0x5C, 0x57, 0x28, 0xF2, 0x0E, 0x95, 0x45, 0x2F
99 };
100 const unsigned char VID_DWR[] = { /* DWR: Delete with reason */
101 	0x2D, 0x79, 0x22, 0xC6, 0xB3, 0x01, 0xD9, 0xB0,
102 	0xE1, 0x34, 0x27, 0x39, 0xE9, 0xCF, 0xBB, 0xD5
103 };
104 /* Cisco Unknown1:
105  *const unsigned char VID_CISCO_UNKNOWN_1[] = {
106  *	1f07f70eaa6514d3b0fa96542a500407
107  *};
108  */
109 
110 const unsigned char VID_CISCO_FRAG[] = { /* "FRAGMENTATION" */
111 	0x40, 0x48, 0xB7, 0xD5, 0x6E, 0xBC, 0xE8, 0x85,
112 	0x25, 0xE7, 0xDE, 0x7F, 0x00, 0xD6, 0xC2, 0xD3,
113 	0x80, 0x00, 0x00, 0x00
114 };
115 const unsigned char VID_NETSCREEN_15[] = { /* netscreen 15 */
116 	0x16, 0x6f, 0x93, 0x2d, 0x55, 0xeb, 0x64, 0xd8,
117 	0xe4, 0xdf, 0x4f, 0xd3, 0x7e, 0x23, 0x13, 0xf0,
118 	0xd0, 0xfd, 0x84, 0x51, 0x00, 0x00, 0x00, 0x00,
119 	0x00, 0x00, 0x00, 0x00
120 };
121 const unsigned char VID_HEARTBEAT_NOTIFY[] = { /* Heartbeat Notify */
122 	0x48, 0x65, 0x61, 0x72, 0x74, 0x42, 0x65, 0x61,
123 	0x74, 0x5f, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79,
124 	0x38, 0x6b, 0x01, 0x00
125 };
126 const unsigned char VID_NORTEL_CONT[] = { /* BNES: Bay Networks Enterprise Switch + version/id of some kind */
127 	0x42, 0x4e, 0x45, 0x53, 0x00, 0x00, 0x00, 0x0a
128 };
129 
130 const unsigned char FW_UNKNOWN_TYPEINFO[] = {
131 	0x80, 0x01, 0x00, 0x01, 0x80, 0x02, 0x00, 0x01,
132 	0x80, 0x03, 0x00, 0x02
133 };
134 
135 struct vid_element {
136 	const unsigned char* valueptr;
137 	const uint16_t length;
138 	const char* descr;
139 };
140 
141 const struct vid_element vid_list[] = {
142 	{ VID_XAUTH,		sizeof(VID_XAUTH),	"Xauth" },
143 	{ VID_DPD,		sizeof(VID_DPD),	"DPD" },
144 	{ VID_UNITY,		sizeof(VID_UNITY),	"Cisco Unity" },
145 	{ VID_NATT_00,		sizeof(VID_NATT_00),	"Nat-T 00" },
146 	{ VID_NATT_01,		sizeof(VID_NATT_01),	"Nat-T 01" },
147 	{ VID_NATT_02,		sizeof(VID_NATT_02),	"Nat-T 02" },
148 	{ VID_NATT_02N,		sizeof(VID_NATT_02N),	"Nat-T 02N" },
149 	{ VID_NATT_RFC,		sizeof(VID_NATT_RFC),	"Nat-T RFC" },
150 	{ VID_DWR,		sizeof(VID_DWR),	"Delete With Reason" },
151 	{ VID_CISCO_FRAG,	sizeof(VID_CISCO_FRAG),	"Cisco Fragmentation" },
152 	{ VID_NETSCREEN_15,	sizeof(VID_NETSCREEN_15),	"Netscreen 15" },
153 	{ VID_NORTEL_CONT,	sizeof(VID_NORTEL_CONT),	"Nortel Contivity" },
154 	{ VID_HEARTBEAT_NOTIFY,	sizeof(VID_HEARTBEAT_NOTIFY),	"Heartbeat Notify" },
155 
156 	{ NULL, 0, NULL }
157 };
158 
159 /* What are DWR-Code and DWR-Text ? */
160 
161 static uint8_t r_packet[8192];
162 static ssize_t r_length;
163 
print_vid(const unsigned char * vid,uint16_t len)164 void print_vid(const unsigned char *vid, uint16_t len) {
165 
166 	int vid_index = 0;
167 
168 	if (opt_debug < 2)
169 		return;
170 
171 	while (vid_list[vid_index].length) {
172 		if (len == vid_list[vid_index].length &&
173 			memcmp(vid_list[vid_index].valueptr, vid, len) == 0) {
174 			printf("   (%s)\n", vid_list[vid_index].descr);
175 			return;
176 		}
177 		vid_index++;
178 	}
179 	printf("   (unknown)\n");
180 }
181 
min(int a,int b)182 static __inline__ int min(int a, int b)
183 {
184 	return (a < b) ? a : b;
185 }
186 
addenv(const void * name,const char * value)187 static void addenv(const void *name, const char *value)
188 {
189 	char *strbuf = NULL, *oldval;
190 
191 	oldval = getenv(name);
192 	if (oldval != NULL) {
193 		strbuf = xallocc(strlen(oldval) + 1 + strlen(value) + 1);
194 		strcat(strbuf, oldval);
195 		strcat(strbuf, " ");
196 		strcat(strbuf, value);
197 	}
198 
199 	setenv(name, strbuf ? strbuf : value, 1);
200 
201 	free(strbuf);
202 }
203 
addenv_ipv4(const void * name,uint8_t * data)204 static void addenv_ipv4(const void *name, uint8_t * data)
205 {
206 	addenv(name, inet_ntoa(*((struct in_addr *)data)));
207 }
208 
make_socket(struct sa_block * s,uint16_t src_port,uint16_t dst_port)209 static int make_socket(struct sa_block *s, uint16_t src_port, uint16_t dst_port)
210 {
211 	int sock;
212 	struct sockaddr_in name;
213 	socklen_t len = sizeof(name);
214 
215 	/* create the socket */
216 	sock = socket(PF_INET, SOCK_DGRAM, 0);
217 	if (sock < 0)
218 		error(1, errno, "making socket");
219 
220 #ifdef FD_CLOEXEC
221 	/* do not pass socket to vpnc-script, etc. */
222 	fcntl(sock, F_SETFD, FD_CLOEXEC);
223 #endif
224 
225 	/* give the socket a name */
226 	name.sin_family = AF_INET;
227 	name.sin_addr = s->opt_src_ip;
228 	name.sin_port = htons(src_port);
229 	if (bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0)
230 		error(1, errno, "Error binding to source port. Try '--local-port 0'\nFailed to bind to %s:%d", inet_ntoa(s->opt_src_ip), src_port);
231 
232 	/* connect the socket */
233 	name.sin_family = AF_INET;
234 	name.sin_addr = s->dst;
235 	name.sin_port = htons(dst_port);
236 	if (connect(sock, (struct sockaddr *)&name, sizeof(name)) < 0)
237 		error(1, errno, "connecting to port %d", ntohs(dst_port));
238 
239 	/* who am I */
240 	if (getsockname(sock, (struct sockaddr *)&name, &len) < 0)
241 		error(1, errno, "reading local address from socket %d", sock);
242 	s->src = name.sin_addr;
243 
244 	return sock;
245 }
246 
cleanup(struct sa_block * s)247 static void cleanup(struct sa_block *s) {
248 	if (s->ike_fd != 0) {
249 		close(s->ike_fd);
250 		s->ike_fd = 0;
251 	}
252 	if (s->esp_fd != 0) {
253 		close(s->esp_fd);
254 		s->esp_fd = 0;
255 	}
256 	if (s->ike.resend_hash) {
257 		free(s->ike.resend_hash);
258 		s->ike.resend_hash = NULL;
259 	}
260 	if (s->ike.skeyid_d) {
261 		free(s->ike.skeyid_d);
262 		s->ike.skeyid_d = NULL;
263 	}
264 	if (s->ike.skeyid_a) {
265 		free(s->ike.skeyid_a);
266 		s->ike.skeyid_a = NULL;
267 	}
268 	if (s->ike.initial_iv) {
269 		free(s->ike.initial_iv);
270 		s->ike.initial_iv = NULL;
271 	}
272 	if (s->ike.current_iv) {
273 		free(s->ike.current_iv);
274 		s->ike.current_iv = NULL;
275 	}
276 	if (s->ike.key) {
277 		free(s->ike.key);
278 		s->ike.key = NULL;
279 	}
280 	if (s->ipsec.rx.key) {
281 		free(s->ipsec.rx.key);
282 		s->ipsec.rx.key = NULL;
283 	}
284 	if (s->ipsec.tx.key) {
285 		free(s->ipsec.tx.key);
286 		s->ipsec.tx.key = NULL;
287 	}
288 	if (s->ipsec.rx.cry_ctx) {
289 		gcry_cipher_close(s->ipsec.rx.cry_ctx);
290 		s->ipsec.rx.cry_ctx = NULL;
291 	}
292 	if (s->ipsec.tx.cry_ctx) {
293 		gcry_cipher_close(s->ipsec.tx.cry_ctx);
294 		s->ipsec.tx.cry_ctx = NULL;
295 	}
296 }
297 
init_sockaddr(struct in_addr * dst,const char * hostname)298 static void init_sockaddr(struct in_addr *dst, const char *hostname)
299 {
300 	struct hostent *hostinfo;
301 
302 	if (inet_aton(hostname, dst) == 0) {
303 		hostinfo = gethostbyname(hostname);
304 		if (hostinfo == NULL)
305 			error(1, 0, "unknown host `%s'\n", hostname);
306 		*dst = *(struct in_addr *)hostinfo->h_addr;
307 	}
308 }
309 
init_netaddr(struct in_addr * net,const char * string)310 static void init_netaddr(struct in_addr *net, const char *string)
311 {
312 	char *p;
313 
314 	if ((p = strchr(string, '/')) != NULL) {
315 		char *host = xallocc(p - string + 1);
316 		memcpy(host, string, p - string + 1);
317 		host[p - string] = '\0';
318 		init_sockaddr((struct in_addr *)net, host);
319 		free(host);
320 		if (strchr(p + 1, '.') != NULL)
321 			init_sockaddr(net + 1, p + 1);
322 		else {
323 			int bits = atoi(p + 1);
324 			unsigned long mask = (1 << bits) - 1;
325 			memcpy((char *)(net + 1), (char *)&mask, 4);
326 		}
327 	} else {
328 		memset((char *)net, 0, 8);
329 	}
330 }
331 
setup_tunnel(struct sa_block * s)332 static void setup_tunnel(struct sa_block *s)
333 {
334 	setenv("reason", "pre-init", 1);
335 	system(config[CONFIG_SCRIPT]);
336 
337 	if (config[CONFIG_IF_NAME])
338 		memcpy(s->tun_name, config[CONFIG_IF_NAME], strlen(config[CONFIG_IF_NAME]));
339 
340 	s->tun_fd = tun_open(s->tun_name, opt_if_mode);
341 	DEBUG(2, printf("using interface %s\n", s->tun_name));
342 	setenv("TUNDEV", s->tun_name, 1);
343 
344 	if (s->tun_fd == -1)
345 		error(1, errno, "can't initialise tunnel interface");
346 #ifdef FD_CLOEXEC
347 	/* do not pass socket to vpnc-script, etc. */
348 	fcntl(s->tun_fd, F_SETFD, FD_CLOEXEC);
349 #endif
350 
351 	if (opt_if_mode == IF_MODE_TAP) {
352 		if (tun_get_hwaddr(s->tun_fd, s->tun_name, s->tun_hwaddr) < 0) {
353 			error(1, errno, "can't get tunnel HW address");
354 		}
355 		hex_dump("interface HW addr", s->tun_hwaddr, ETH_ALEN, NULL);
356 	}
357 }
358 
config_tunnel(struct sa_block * s)359 static void config_tunnel(struct sa_block *s)
360 {
361 	setenv("VPNGATEWAY", inet_ntoa(s->dst), 1);
362 	setenv("reason", "connect", 1);
363 	system(config[CONFIG_SCRIPT]);
364 }
365 
close_tunnel(struct sa_block * s)366 static void close_tunnel(struct sa_block *s)
367 {
368 	setenv("reason", "disconnect", 1);
369 	system(config[CONFIG_SCRIPT]);
370 	tun_close(s->tun_fd, s->tun_name);
371 }
372 
recv_ignore_dup(struct sa_block * s,void * recvbuf,size_t recvbufsize)373 static int recv_ignore_dup(struct sa_block *s, void *recvbuf, size_t recvbufsize)
374 {
375 	uint8_t *resend_check_hash;
376 	int recvsize, hash_len;
377 
378 	recvsize = recv(s->ike_fd, recvbuf, recvbufsize, 0);
379 	if (recvsize < 0)
380 		error(1, errno, "receiving packet");
381 	if ((unsigned int)recvsize > recvbufsize)
382 		error(1, errno, "received packet too large for buffer");
383 
384 	/* skip (not only) NAT-T draft-0 keepalives */
385 	if ( /* (s->ipsec.natt_active_mode == NATT_ACTIVE_DRAFT_OLD) && */
386 	    (recvsize == 1) && (*((u_char *)(recvbuf)) == 0xff))
387 	{
388 		if ((s->ipsec.natt_active_mode != NATT_ACTIVE_DRAFT_OLD))
389 		{
390 			DEBUG(2, printf("Received UDP NAT-Keepalive bug nat active mode incorrect: %d\n", s->ipsec.natt_active_mode));
391 		}
392 		return -1;
393 	}
394 
395 	hash_len = gcry_md_get_algo_dlen(GCRY_MD_SHA1);
396 	resend_check_hash = malloc(hash_len);
397 	gcry_md_hash_buffer(GCRY_MD_SHA1, resend_check_hash, recvbuf, recvsize);
398 	if (s->ike.resend_hash && memcmp(s->ike.resend_hash, resend_check_hash, hash_len) == 0) {
399 		free(resend_check_hash);
400 		return -1;
401 	}
402 	if (!s->ike.resend_hash) {
403 		s->ike.resend_hash = resend_check_hash;
404 	} else {
405 		memcpy(s->ike.resend_hash, resend_check_hash, hash_len);
406 		free(resend_check_hash);
407 	}
408 
409 	return recvsize;
410 }
411 
412 /* Send TOSEND of size SENDSIZE to the socket.  Then wait for a new packet,
413    resending TOSEND on timeout, and ignoring duplicate packets; the
414    new packet is put in RECVBUF of size RECVBUFSIZE and the actual size
415    of the new packet is returned.  */
416 
sendrecv(struct sa_block * s,void * recvbuf,size_t recvbufsize,void * tosend,size_t sendsize,int sendonly)417 static ssize_t sendrecv(struct sa_block *s, void *recvbuf, size_t recvbufsize, void *tosend, size_t sendsize, int sendonly)
418 {
419 	struct pollfd pfd;
420 	int tries = 0;
421 	int recvsize = -1;
422 	time_t start = time(NULL);
423 	time_t end = 0;
424 	void *realtosend;
425 
426 	pfd.fd = s->ike_fd;
427 	pfd.events = POLLIN;
428 	tries = 0;
429 
430 	if ((s->ipsec.natt_active_mode == NATT_ACTIVE_RFC) && (tosend != NULL)) {
431 		DEBUG(2, printf("NAT-T mode, adding non-esp marker\n"));
432 		realtosend = xallocc(sendsize+4);
433 		memmove((char*)realtosend+4, tosend, sendsize);
434 		sendsize += 4;
435 	} else {
436 		realtosend = tosend;
437 	}
438 
439 	for (;;) {
440 		int pollresult;
441 
442 		if (realtosend != NULL)
443 			if (write(s->ike_fd, realtosend, sendsize) != (int)sendsize)
444 				error(1, errno, "can't send packet");
445 		if (sendonly)
446 			break;
447 
448 		do {
449 			pollresult = poll(&pfd, 1, s->ike.timeout << tries);
450 		} while (pollresult == -1 && errno == EINTR);
451 
452 		if (pollresult == -1)
453 			error(1, errno, "can't poll socket");
454 		if (pollresult != 0) {
455 			recvsize = recv_ignore_dup(s, recvbuf, recvbufsize);
456 			end = time(NULL);
457 			if (recvsize != -1)
458 				break;
459 			continue;
460 		}
461 
462 		if (tries > 2)
463 			error(1, 0, "no response from target");
464 		tries++;
465 	}
466 
467 	if (realtosend != tosend)
468 		free(realtosend);
469 
470 	if (sendonly)
471 		return 0;
472 
473 	if ((s->ipsec.natt_active_mode == NATT_ACTIVE_RFC)&&(recvsize > 4)) {
474 		recvsize -= 4; /* 4 bytes non-esp marker */
475 		memmove(recvbuf, (char *)recvbuf+4, recvsize);
476 	}
477 
478 	DEBUGTOP(3, printf("\n receiving: <========================\n"));
479 
480 	/* Wait at least 2s for a response or 4 times the time it took
481 	 * last time.  */
482 	if (start >= end)
483 		s->ike.timeout = 2000;
484 	else
485 		s->ike.timeout = 4000 * (end - start);
486 
487 	return recvsize;
488 }
489 
isakmp_crypt(struct sa_block * s,uint8_t * block,size_t blocklen,int enc)490 static int isakmp_crypt(struct sa_block *s, uint8_t * block, size_t blocklen, int enc)
491 {
492 	unsigned char *new_iv, *iv = NULL;
493 	int info_ex;
494 	gcry_cipher_hd_t cry_ctx;
495 
496 	if (blocklen < ISAKMP_PAYLOAD_O || ((blocklen - ISAKMP_PAYLOAD_O) % s->ike.ivlen != 0))
497 		abort();
498 
499 	if (!enc && (memcmp(block + ISAKMP_I_COOKIE_O, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH) != 0
500 		|| memcmp(block + ISAKMP_R_COOKIE_O, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH) != 0)) {
501 		DEBUG(2, printf("got paket with wrong cookies\n"));
502 		return ISAKMP_N_INVALID_COOKIE;
503 	}
504 
505 	info_ex = block[ISAKMP_EXCHANGE_TYPE_O] == ISAKMP_EXCHANGE_INFORMATIONAL;
506 
507 	if (memcmp(block + ISAKMP_MESSAGE_ID_O, s->ike.current_iv_msgid, 4) != 0) {
508 		gcry_md_hd_t md_ctx;
509 
510 		gcry_md_open(&md_ctx, s->ike.md_algo, 0);
511 		gcry_md_write(md_ctx, s->ike.initial_iv, s->ike.ivlen);
512 		gcry_md_write(md_ctx, block + ISAKMP_MESSAGE_ID_O, 4);
513 		gcry_md_final(md_ctx);
514 		if (info_ex) {
515 			iv = xallocc(s->ike.ivlen);
516 			memcpy(iv, gcry_md_read(md_ctx, 0), s->ike.ivlen);
517 		} else {
518 			memcpy(s->ike.current_iv, gcry_md_read(md_ctx, 0), s->ike.ivlen);
519 			memcpy(s->ike.current_iv_msgid, block + ISAKMP_MESSAGE_ID_O, 4);
520 		}
521 		gcry_md_close(md_ctx);
522 	} else if (info_ex) {
523 		abort();
524 	}
525 
526 	if (!info_ex) {
527 		iv = s->ike.current_iv;
528 	}
529 
530 	new_iv = xallocc(s->ike.ivlen);
531 	gcry_cipher_open(&cry_ctx, s->ike.cry_algo, GCRY_CIPHER_MODE_CBC, 0);
532 	gcry_cipher_setkey(cry_ctx, s->ike.key, s->ike.keylen);
533 	gcry_cipher_setiv(cry_ctx, iv, s->ike.ivlen);
534 	if (!enc) {
535 		memcpy(new_iv, block + blocklen - s->ike.ivlen, s->ike.ivlen);
536 		gcry_cipher_decrypt(cry_ctx, block + ISAKMP_PAYLOAD_O, blocklen - ISAKMP_PAYLOAD_O,
537 			NULL, 0);
538 		if (!info_ex)
539 			memcpy(s->ike.current_iv, new_iv, s->ike.ivlen);
540 	} else {
541 		gcry_cipher_encrypt(cry_ctx, block + ISAKMP_PAYLOAD_O, blocklen - ISAKMP_PAYLOAD_O,
542 			NULL, 0);
543 		if (!info_ex)
544 			memcpy(s->ike.current_iv, block + blocklen - s->ike.ivlen, s->ike.ivlen);
545 	}
546 	gcry_cipher_close(cry_ctx);
547 
548 	free(new_iv);
549 	if (info_ex)
550 		free(iv);
551 
552 	return 0;
553 }
554 
unpack_verify_phase2(struct sa_block * s,uint8_t * r_packet,size_t r_length,struct isakmp_packet ** r_p,const uint8_t * nonce,size_t nonce_size)555 static uint16_t unpack_verify_phase2(struct sa_block *s, uint8_t * r_packet,
556 	size_t r_length, struct isakmp_packet **r_p, const uint8_t * nonce, size_t nonce_size)
557 {
558 	struct isakmp_packet *r;
559 	int reject = 0;
560 
561 	*r_p = NULL;
562 
563 	/* Some users report "payload ... not padded..." errors. It seems that they
564 	 * are harmless, so ignore and fix the symptom
565 	 */
566 	if (r_length < ISAKMP_PAYLOAD_O ||
567 	    ((r_length - ISAKMP_PAYLOAD_O) % s->ike.ivlen != 0)) {
568 		DEBUG(2, printf("payload too short or not padded: len=%lld, min=%d (ivlen=%lld)\n",
569 			(long long)r_length, ISAKMP_PAYLOAD_O, (long long)s->ike.ivlen));
570 		hex_dump("Payload", r_packet, r_length, NULL);
571 		if (r_length < ISAKMP_PAYLOAD_O ) {
572 			return ISAKMP_N_UNEQUAL_PAYLOAD_LENGTHS;
573 		}
574 		r_length -= (r_length - ISAKMP_PAYLOAD_O) % s->ike.ivlen;
575 	}
576 
577 	reject = isakmp_crypt(s, r_packet, r_length, 0);
578 	if (reject != 0)
579 		return reject;
580 
581 	s->ike.life.rx += r_length;
582 
583 	{
584 		r = parse_isakmp_packet(r_packet, r_length, &reject);
585 		if (reject != 0) {
586 			if (r) free_isakmp_packet(r);
587 			return reject;
588 		}
589 	}
590 
591 	/* Verify the basic stuff.  */
592 	if (r->flags != ISAKMP_FLAG_E) {
593 		free_isakmp_packet(r);
594 		return ISAKMP_N_INVALID_FLAGS;
595 	}
596 
597 	{
598 		size_t sz, spos;
599 		gcry_md_hd_t hm;
600 		unsigned char *expected_hash;
601 		struct isakmp_payload *h = r->payload;
602 
603 		if (h == NULL || h->type != ISAKMP_PAYLOAD_HASH || h->u.hash.length != s->ike.md_len) {
604 			free_isakmp_packet(r);
605 			return ISAKMP_N_INVALID_HASH_INFORMATION;
606 		}
607 
608 		spos = (ISAKMP_PAYLOAD_O + (r_packet[ISAKMP_PAYLOAD_O + 2] << 8)
609 			+ r_packet[ISAKMP_PAYLOAD_O + 3]);
610 
611 		/* Compute the real length based on the payload lengths.  */
612 		for (sz = spos; r_packet[sz] != 0; sz += r_packet[sz + 2] << 8 | r_packet[sz + 3]) ;
613 		sz += r_packet[sz + 2] << 8 | r_packet[sz + 3];
614 
615 		gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
616 		gcry_md_setkey(hm, s->ike.skeyid_a, s->ike.md_len);
617 		gcry_md_write(hm, r_packet + ISAKMP_MESSAGE_ID_O, 4);
618 		if (nonce)
619 			gcry_md_write(hm, nonce, nonce_size);
620 		gcry_md_write(hm, r_packet + spos, sz - spos);
621 		gcry_md_final(hm);
622 		expected_hash = gcry_md_read(hm, 0);
623 
624 		DEBUG(3,printf("hashlen: %lu\n", (unsigned long)s->ike.md_len));
625 		DEBUG(3,printf("u.hash.length: %d\n", h->u.hash.length));
626 		hex_dump("expected_hash", expected_hash, s->ike.md_len, NULL);
627 		hex_dump("h->u.hash.data", h->u.hash.data, s->ike.md_len, NULL);
628 
629 		reject = 0;
630 		if (memcmp(h->u.hash.data, expected_hash, s->ike.md_len) != 0)
631 			reject = ISAKMP_N_AUTHENTICATION_FAILED;
632 		gcry_md_close(hm);
633 #if 0
634 		if (reject != 0) {
635 			free_isakmp_packet(r);
636 			return reject;
637 		}
638 #endif
639 	}
640 	*r_p = r;
641 	return 0;
642 }
643 
644 static void
phase2_authpacket(struct sa_block * s,struct isakmp_payload * pl,uint8_t exchange_type,uint32_t msgid,uint8_t ** p_flat,size_t * p_size,uint8_t * nonce_i,int ni_len,uint8_t * nonce_r,int nr_len)645 phase2_authpacket(struct sa_block *s, struct isakmp_payload *pl,
646 	uint8_t exchange_type, uint32_t msgid,
647 	uint8_t ** p_flat, size_t * p_size,
648 	uint8_t * nonce_i, int ni_len, uint8_t * nonce_r, int nr_len)
649 {
650 	struct isakmp_packet *p;
651 	uint8_t *pl_flat;
652 	size_t pl_size;
653 	gcry_md_hd_t hm;
654 	uint8_t msgid_sent[4];
655 
656 	/* Build up the packet.  */
657 	p = new_isakmp_packet();
658 	memcpy(p->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
659 	memcpy(p->r_cookie, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
660 	p->flags = ISAKMP_FLAG_E;
661 	p->isakmp_version = ISAKMP_VERSION;
662 	p->exchange_type = exchange_type;
663 	p->message_id = msgid;
664 	p->payload = new_isakmp_payload(ISAKMP_PAYLOAD_HASH);
665 	p->payload->next = pl;
666 	p->payload->u.hash.length = s->ike.md_len;
667 	p->payload->u.hash.data = xallocc(s->ike.md_len);
668 
669 	/* Set the MAC.  */
670 	gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
671 	gcry_md_setkey(hm, s->ike.skeyid_a, s->ike.md_len);
672 
673 	if (pl == NULL) {
674 		DEBUG(3, printf("authing NULL package!\n"));
675 		gcry_md_write(hm, "" /* \0 */ , 1);
676 	}
677 
678 	msgid_sent[0] = msgid >> 24;
679 	msgid_sent[1] = msgid >> 16;
680 	msgid_sent[2] = msgid >> 8;
681 	msgid_sent[3] = msgid;
682 	gcry_md_write(hm, msgid_sent, sizeof(msgid_sent));
683 
684 	if (nonce_i != NULL)
685 		gcry_md_write(hm, nonce_i, ni_len);
686 
687 	if (nonce_r != NULL)
688 		gcry_md_write(hm, nonce_r, nr_len);
689 
690 	if (pl != NULL) {
691 		flatten_isakmp_payloads(pl, &pl_flat, &pl_size);
692 		gcry_md_write(hm, pl_flat, pl_size);
693 		memset(pl_flat, 0, pl_size);
694 		free(pl_flat);
695 	}
696 
697 	gcry_md_final(hm);
698 	memcpy(p->payload->u.hash.data, gcry_md_read(hm, 0), s->ike.md_len);
699 	gcry_md_close(hm);
700 
701 	flatten_isakmp_packet(p, p_flat, p_size, s->ike.ivlen);
702 	free_isakmp_packet(p);
703 }
704 
sendrecv_phase2(struct sa_block * s,struct isakmp_payload * pl,uint8_t exchange_type,uint32_t msgid,int sendonly,uint8_t ** save_p_flat,size_t * save_p_size,uint8_t * nonce_i,int ni_len,uint8_t * nonce_r,int nr_len)705 static void sendrecv_phase2(struct sa_block *s, struct isakmp_payload *pl,
706 	uint8_t exchange_type, uint32_t msgid, int sendonly,
707 	uint8_t ** save_p_flat, size_t * save_p_size,
708 	uint8_t * nonce_i, int ni_len, uint8_t * nonce_r, int nr_len)
709 {
710 	uint8_t *p_flat;
711 	size_t p_size;
712 	ssize_t recvlen;
713 
714 	if ((save_p_flat == NULL) || (*save_p_flat == NULL)) {
715 		phase2_authpacket(s, pl, exchange_type, msgid, &p_flat, &p_size,
716 			nonce_i, ni_len, nonce_r, nr_len);
717 		isakmp_crypt(s, p_flat, p_size, 1);
718 	} else {
719 		p_flat = *save_p_flat;
720 		p_size = *save_p_size;
721 	}
722 
723 	s->ike.life.tx += p_size;
724 
725 	recvlen = sendrecv(s, r_packet, sizeof(r_packet), p_flat, p_size, sendonly);
726 	if (sendonly == 0)
727 		r_length = recvlen;
728 
729 	if (save_p_flat == NULL) {
730 		free(p_flat);
731 	} else {
732 		*save_p_flat = p_flat;
733 		*save_p_size = p_size;
734 	}
735 }
736 
send_phase2_late(struct sa_block * s,struct isakmp_payload * pl,uint8_t exchange_type,uint32_t msgid)737 static void send_phase2_late(struct sa_block *s, struct isakmp_payload *pl,
738 	uint8_t exchange_type, uint32_t msgid)
739 {
740 	struct isakmp_packet *p;
741 	uint8_t *p_flat;
742 	size_t p_size;
743 	ssize_t recvlen;
744 
745 	/* Build up the packet.  */
746 	p = new_isakmp_packet();
747 	memcpy(p->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
748 	memcpy(p->r_cookie, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
749 	p->flags = ISAKMP_FLAG_E;
750 	p->isakmp_version = ISAKMP_VERSION;
751 	p->exchange_type = exchange_type;
752 	p->message_id = msgid;
753 	p->payload = pl;
754 
755 	flatten_isakmp_packet(p, &p_flat, &p_size, s->ike.ivlen);
756 	free_isakmp_packet(p);
757 	isakmp_crypt(s, p_flat, p_size, 1);
758 
759 	s->ike.life.tx += p_size;
760 
761 	recvlen = sendrecv(s, NULL, 0, p_flat, p_size, 1);
762 	free(p_flat);
763 }
764 
keepalive_ike(struct sa_block * s)765 void keepalive_ike(struct sa_block *s)
766 {
767 	uint32_t msgid;
768 
769 	gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
770 	send_phase2_late(s, NULL, ISAKMP_EXCHANGE_INFORMATIONAL, msgid);
771 }
772 
send_dpd(struct sa_block * s,int isack,uint32_t seqno)773 static void send_dpd(struct sa_block *s, int isack, uint32_t seqno)
774 {
775 	struct isakmp_payload *pl;
776 	uint32_t msgid;
777 
778 	pl = new_isakmp_payload(ISAKMP_PAYLOAD_N);
779 	pl->u.n.doi = ISAKMP_DOI_IPSEC;
780 	pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
781 	pl->u.n.type = isack ? ISAKMP_N_R_U_THERE_ACK : ISAKMP_N_R_U_THERE;
782 	pl->u.n.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
783 	pl->u.n.spi = xallocc(2 * ISAKMP_COOKIE_LENGTH);
784 	memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
785 	memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
786 	pl->u.n.data_length = 4;
787 	pl->u.n.data = xallocc(4);
788 	memcpy(pl->u.n.data, &seqno, 4);
789 	gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
790 	/* 2007-09-06 JKU/ZID: Sonicwall drops non hashed r_u_there-requests */
791 	sendrecv_phase2(s, pl, ISAKMP_EXCHANGE_INFORMATIONAL, msgid,
792 		1 , NULL, NULL, NULL, 0, NULL, 0);
793 }
794 
dpd_ike(struct sa_block * s)795 void dpd_ike(struct sa_block *s)
796 {
797 	if (!s->ike.do_dpd)
798 		return;
799 
800 	if (s->ike.dpd_seqno == s->ike.dpd_seqno_ack) {
801 		/* Increase the sequence number, reset the attempts to 6, record
802 		** the current time and send a dpd request
803 		*/
804 		s->ike.dpd_attempts = 6;
805 		s->ike.dpd_sent = time(NULL);
806 		++s->ike.dpd_seqno;
807 		send_dpd(s, 0, s->ike.dpd_seqno);
808 	} else {
809 		/* Our last dpd request has not yet been acked.  If it's been
810 		** less than 5 seconds since we sent it do nothing.  Otherwise
811 		** decrement dpd_attempts.  If dpd_attempts is 0 dpd fails and we
812 		** terminate otherwise we send it again with the same sequence
813 		** number and record current time.
814 		*/
815 		time_t now = time(NULL);
816 		if (now < s->ike.dpd_sent + 5)
817 			return;
818 		if (--s->ike.dpd_attempts == 0) {
819 			DEBUG(2, printf("dead peer detected, terminating\n"));
820 			do_kill = -2;
821 			return;
822 		}
823 		s->ike.dpd_sent = now;
824 		send_dpd(s, 0, s->ike.dpd_seqno);
825 	}
826 }
827 
phase2_fatal(struct sa_block * s,const char * msg,int id)828 static void phase2_fatal(struct sa_block *s, const char *msg, int id)
829 {
830 	struct isakmp_payload *pl;
831 	uint32_t msgid;
832 
833 	DEBUG(1, printf("\n\n---!!!!!!!!! entering phase2_fatal !!!!!!!!!---\n\n\n"));
834 	gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
835 	pl = new_isakmp_payload(ISAKMP_PAYLOAD_N);
836 	pl->u.n.doi = ISAKMP_DOI_IPSEC;
837 	pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
838 	pl->u.n.type = id;
839 	sendrecv_phase2(s, pl, ISAKMP_EXCHANGE_INFORMATIONAL, msgid, 1, 0, 0, 0, 0, 0, 0);
840 
841 	gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
842 	pl = new_isakmp_payload(ISAKMP_PAYLOAD_D);
843 	pl->u.d.doi = ISAKMP_DOI_IPSEC;
844 	pl->u.d.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
845 	pl->u.d.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
846 	pl->u.d.num_spi = 1;
847 	pl->u.d.spi = xallocc(1 * sizeof(uint8_t *));
848 	pl->u.d.spi[0] = xallocc(2 * ISAKMP_COOKIE_LENGTH);
849 	memcpy(pl->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
850 	memcpy(pl->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
851 	sendrecv_phase2(s, pl, ISAKMP_EXCHANGE_INFORMATIONAL, msgid, 1, 0, 0, 0, 0, 0, 0);
852 
853 	error(1, 0, msg, val_to_string(id, isakmp_notify_enum_array), id);
854 }
855 
gen_keymat(struct sa_block * s,uint8_t protocol,uint32_t spi,const uint8_t * dh_shared,size_t dh_size,const uint8_t * ni_data,size_t ni_size,const uint8_t * nr_data,size_t nr_size)856 static uint8_t *gen_keymat(struct sa_block *s,
857 	uint8_t protocol, uint32_t spi,
858 	const uint8_t * dh_shared, size_t dh_size,
859 	const uint8_t * ni_data, size_t ni_size, const uint8_t * nr_data, size_t nr_size)
860 {
861 	gcry_md_hd_t hm;
862 	uint8_t *block;
863 	int i;
864 	int blksz;
865 	int cnt;
866 
867 	blksz = s->ipsec.md_len + s->ipsec.key_len;
868 	cnt = (blksz + s->ike.md_len - 1) / s->ike.md_len;
869 	block = xallocc(cnt * s->ike.md_len);
870 	DEBUG(3, printf("generating %d bytes keymat (cnt=%d)\n", blksz, cnt));
871 	if (cnt < 1)
872 		abort();
873 
874 	for (i = 0; i < cnt; i++) {
875 		gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
876 		gcry_md_setkey(hm, s->ike.skeyid_d, s->ike.md_len);
877 		if (i != 0)
878 			gcry_md_write(hm, block + (i - 1) * s->ike.md_len, s->ike.md_len);
879 		if (dh_shared != NULL)
880 			gcry_md_write(hm, dh_shared, dh_size);
881 		gcry_md_write(hm, &protocol, 1);
882 		gcry_md_write(hm, (uint8_t *) & spi, sizeof(spi));
883 		gcry_md_write(hm, ni_data, ni_size);
884 		gcry_md_write(hm, nr_data, nr_size);
885 		gcry_md_final(hm);
886 		memcpy(block + i * s->ike.md_len, gcry_md_read(hm, 0), s->ike.md_len);
887 		gcry_md_close(hm);
888 	}
889 	return block;
890 }
891 
mask_to_masklen(struct in_addr mask)892 static int mask_to_masklen(struct in_addr mask)
893 {
894 	int len;
895 	uint32_t addr;
896 
897 	addr = ntohl(mask.s_addr);
898 	for (len = 0; addr; addr <<= 1, len++)
899 		;
900 	return len;
901 }
902 
do_config_to_env(struct sa_block * s,struct isakmp_attribute * a)903 static int do_config_to_env(struct sa_block *s, struct isakmp_attribute *a)
904 {
905 	int i;
906 	int reject = 0;
907 	int seen_address = 0;
908 	char *strbuf, *strbuf2;
909 
910 	unsetenv("CISCO_BANNER");
911 	unsetenv("CISCO_DEF_DOMAIN");
912 	unsetenv("CISCO_SPLIT_INC");
913 	unsetenv("INTERNAL_IP4_NBNS");
914 	unsetenv("INTERNAL_IP4_DNS");
915 	unsetenv("INTERNAL_IP4_NETMASK");
916 	unsetenv("INTERNAL_IP4_ADDRESS");
917 
918 	for (; a && reject == 0; a = a->next)
919 		switch (a->type) {
920 		case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_ADDRESS:
921 			if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
922 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
923 			else {
924 				addenv_ipv4("INTERNAL_IP4_ADDRESS", a->u.lots.data);
925 				memcpy(s->our_address, a->u.lots.data, 4);
926 			}
927 			seen_address = 1;
928 			break;
929 
930 		case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NETMASK:
931 			if (a->af == isakmp_attr_lots && a->u.lots.length == 0) {
932 				DEBUG(2, printf("ignoring zero length netmask\n"));
933 				continue;
934 			}
935 			if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
936 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
937 			else {
938 				uint32_t netaddr = ((struct in_addr *)(s->our_address))->s_addr & ((struct in_addr *)(a->u.lots.data))->s_addr;
939 				addenv_ipv4("INTERNAL_IP4_NETMASK", a->u.lots.data);
940 				asprintf(&strbuf, "%d", mask_to_masklen(*((struct in_addr *)a->u.lots.data)));
941 				setenv("INTERNAL_IP4_NETMASKLEN", strbuf, 1);
942 				free(strbuf);
943 				addenv_ipv4("INTERNAL_IP4_NETADDR",  (uint8_t *)&netaddr);
944 			}
945 			break;
946 
947 		case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_DNS:
948 			if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
949 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
950 			else
951 				addenv_ipv4("INTERNAL_IP4_DNS", a->u.lots.data);
952 			break;
953 
954 		case ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NBNS:
955 			if (a->af != isakmp_attr_lots || a->u.lots.length != 4)
956 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
957 			else
958 				addenv_ipv4("INTERNAL_IP4_NBNS", a->u.lots.data);
959 			break;
960 
961 		case ISAKMP_MODECFG_ATTRIB_CISCO_DEF_DOMAIN:
962 			if (a->af != isakmp_attr_lots) {
963 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
964 				break;
965 			}
966 			strbuf = xallocc(a->u.lots.length + 1);
967 			memcpy(strbuf, a->u.lots.data, a->u.lots.length);
968 			addenv("CISCO_DEF_DOMAIN", strbuf);
969 			free(strbuf);
970 			break;
971 
972 		case ISAKMP_MODECFG_ATTRIB_CISCO_BANNER:
973 			if (a->af != isakmp_attr_lots) {
974 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
975 				break;
976 			}
977 			strbuf = xallocc(a->u.lots.length + 1);
978 			memcpy(strbuf, a->u.lots.data, a->u.lots.length);
979 			addenv("CISCO_BANNER", strbuf);
980 			free(strbuf);
981 			DEBUG(1, printf("Banner: "));
982 			DEBUG(1, fwrite(a->u.lots.data, a->u.lots.length, 1, stdout));
983 			DEBUG(1, printf("\n"));
984 			break;
985 
986 		case ISAKMP_MODECFG_ATTRIB_APPLICATION_VERSION:
987 			DEBUG(2, printf("Remote Application Version: "));
988 			DEBUG(2, fwrite(a->u.lots.data, a->u.lots.length, 1, stdout));
989 			DEBUG(2, printf("\n"));
990 			break;
991 
992 		case ISAKMP_MODECFG_ATTRIB_CISCO_DO_PFS:
993 			if (a->af != isakmp_attr_16)
994 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
995 			else {
996 				s->ipsec.do_pfs = a->u.attr_16;
997 				DEBUG(2, printf("got pfs setting: %d\n", s->ipsec.do_pfs));
998 			}
999 			break;
1000 
1001 		case ISAKMP_MODECFG_ATTRIB_CISCO_UDP_ENCAP_PORT:
1002 			if (a->af != isakmp_attr_16)
1003 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
1004 			else {
1005 				s->ipsec.peer_udpencap_port = a->u.attr_16;
1006 				DEBUG(2, printf("got peer udp encapsulation port: %hu\n", s->ipsec.peer_udpencap_port));
1007 			}
1008 			break;
1009 
1010 		case ISAKMP_MODECFG_ATTRIB_CISCO_SPLIT_INC:
1011 			if (a->af != isakmp_attr_acl) {
1012 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
1013 				break;
1014 			}
1015 
1016 			DEBUG(2, printf("got %d acls for split include\n", a->u.acl.count));
1017 			asprintf(&strbuf, "%d", a->u.acl.count);
1018 			setenv("CISCO_SPLIT_INC", strbuf, 1);
1019 			free(strbuf);
1020 
1021 			for (i = 0; i < a->u.acl.count; i++) {
1022 				DEBUG(2, printf("acl %d: ", i));
1023 				/* NOTE: inet_ntoa returns one static buffer */
1024 
1025 				asprintf(&strbuf, "CISCO_SPLIT_INC_%d_ADDR", i);
1026 				asprintf(&strbuf2, "%s", inet_ntoa(a->u.acl.acl_ent[i].addr));
1027 				DEBUG(2, printf("addr: %s/", strbuf2));
1028 				setenv(strbuf, strbuf2, 1);
1029 				free(strbuf); free(strbuf2);
1030 
1031 				asprintf(&strbuf, "CISCO_SPLIT_INC_%d_MASK", i);
1032 				asprintf(&strbuf2, "%s", inet_ntoa(a->u.acl.acl_ent[i].mask));
1033 				DEBUG(2, printf("%s ", strbuf2));
1034 				setenv(strbuf, strbuf2, 1);
1035 				free(strbuf); free(strbuf2);
1036 
1037 				/* this is just here because ip route does not accept netmasks */
1038 				asprintf(&strbuf, "CISCO_SPLIT_INC_%d_MASKLEN", i);
1039 				asprintf(&strbuf2, "%d", mask_to_masklen(a->u.acl.acl_ent[i].mask));
1040 				DEBUG(2, printf("(%s), ", strbuf2));
1041 				setenv(strbuf, strbuf2, 1);
1042 				free(strbuf); free(strbuf2);
1043 
1044 				asprintf(&strbuf, "CISCO_SPLIT_INC_%d_PROTOCOL", i);
1045 				asprintf(&strbuf2, "%hu", a->u.acl.acl_ent[i].protocol);
1046 				DEBUG(2, printf("protocol: %s, ", strbuf2));
1047 				setenv(strbuf, strbuf2, 1);
1048 				free(strbuf); free(strbuf2);
1049 
1050 				asprintf(&strbuf, "CISCO_SPLIT_INC_%d_SPORT", i);
1051 				asprintf(&strbuf2, "%hu", a->u.acl.acl_ent[i].sport);
1052 				DEBUG(2, printf("sport: %s, ", strbuf2));
1053 				setenv(strbuf, strbuf2, 1);
1054 				free(strbuf); free(strbuf2);
1055 
1056 				asprintf(&strbuf, "CISCO_SPLIT_INC_%d_DPORT", i);
1057 				asprintf(&strbuf2, "%hu", a->u.acl.acl_ent[i].dport);
1058 				DEBUG(2, printf("dport: %s\n", strbuf2));
1059 				setenv(strbuf, strbuf2, 1);
1060 				free(strbuf); free(strbuf2);
1061 			}
1062 			break;
1063 
1064 		case ISAKMP_MODECFG_ATTRIB_CISCO_SAVE_PW:
1065 			DEBUG(2, printf("got save password setting: %d\n", a->u.attr_16));
1066 			break;
1067 
1068 		default:
1069 			DEBUG(2, printf("unknown attribute %d / 0x%X\n", a->type, a->type));
1070 			break;
1071 		}
1072 
1073 	if (reject == 0 && !seen_address)
1074 		reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
1075 
1076 	return reject;
1077 }
1078 
1079 /* * */
1080 
make_transform_ike(int dh_group,int crypt,int hash,int keylen,int auth)1081 static struct isakmp_attribute *make_transform_ike(int dh_group, int crypt, int hash, int keylen, int auth)
1082 {
1083 	struct isakmp_attribute *a = NULL;
1084 
1085 	a = new_isakmp_attribute(IKE_ATTRIB_LIFE_DURATION, a);
1086 	a->af = isakmp_attr_lots;
1087 	a->u.lots.length = 4;
1088 	a->u.lots.data = xallocc(a->u.lots.length);
1089 	*((uint32_t *) a->u.lots.data) = htonl(2147483);
1090 	a = new_isakmp_attribute_16(IKE_ATTRIB_LIFE_TYPE, IKE_LIFE_TYPE_SECONDS, a);
1091 	a = new_isakmp_attribute_16(IKE_ATTRIB_AUTH_METHOD, auth, a);
1092 	a = new_isakmp_attribute_16(IKE_ATTRIB_GROUP_DESC, dh_group, a);
1093 	a = new_isakmp_attribute_16(IKE_ATTRIB_HASH, hash, a);
1094 	a = new_isakmp_attribute_16(IKE_ATTRIB_ENC, crypt, a);
1095 	if (keylen != 0)
1096 		a = new_isakmp_attribute_16(IKE_ATTRIB_KEY_LENGTH, keylen, a);
1097 	return a;
1098 }
1099 
make_our_sa_ike(void)1100 static struct isakmp_payload *make_our_sa_ike(void)
1101 {
1102 	struct isakmp_payload *r = new_isakmp_payload(ISAKMP_PAYLOAD_SA);
1103 	struct isakmp_payload *t = NULL, *tn;
1104 	struct isakmp_attribute *a;
1105 	int dh_grp = get_dh_group_ike()->ike_sa_id;
1106 	unsigned int auth, crypt, hash, keylen;
1107 	int i;
1108 
1109 	r->u.sa.doi = ISAKMP_DOI_IPSEC;
1110 	r->u.sa.situation = ISAKMP_IPSEC_SIT_IDENTITY_ONLY;
1111 	r->u.sa.proposals = new_isakmp_payload(ISAKMP_PAYLOAD_P);
1112 	r->u.sa.proposals->u.p.prot_id = ISAKMP_IPSEC_PROTO_ISAKMP;
1113 	for (auth = 0; supp_auth[auth].name != NULL; auth++) {
1114 		if (opt_auth_mode == AUTH_MODE_CERT) {
1115 			if ((supp_auth[auth].ike_sa_id != IKE_AUTH_RSA_SIG) &&
1116 				(supp_auth[auth].ike_sa_id != IKE_AUTH_DSS))
1117 				continue;
1118 		} else if (opt_auth_mode == AUTH_MODE_HYBRID) {
1119 			if ((supp_auth[auth].ike_sa_id != IKE_AUTH_HybridInitRSA) &&
1120 				(supp_auth[auth].ike_sa_id != IKE_AUTH_HybridInitDSS))
1121 				continue;
1122 		} else {
1123 			if (supp_auth[auth].ike_sa_id == IKE_AUTH_HybridInitRSA ||
1124 				supp_auth[auth].ike_sa_id == IKE_AUTH_HybridInitDSS ||
1125 				supp_auth[auth].ike_sa_id == IKE_AUTH_RSA_SIG ||
1126 				supp_auth[auth].ike_sa_id == IKE_AUTH_DSS)
1127 				continue;
1128 		}
1129 		for (crypt = 0; supp_crypt[crypt].name != NULL; crypt++) {
1130 			keylen = supp_crypt[crypt].keylen;
1131 			for (hash = 0; supp_hash[hash].name != NULL; hash++) {
1132 				tn = t;
1133 				t = new_isakmp_payload(ISAKMP_PAYLOAD_T);
1134 				t->u.t.id = ISAKMP_IPSEC_KEY_IKE;
1135 				a = make_transform_ike(dh_grp, supp_crypt[crypt].ike_sa_id,
1136 					supp_hash[hash].ike_sa_id, keylen, supp_auth[auth].ike_sa_id);
1137 				t->u.t.attributes = a;
1138 				t->next = tn;
1139 			}
1140 		}
1141 	}
1142 	for (i = 0, tn = t; tn; tn = tn->next)
1143 		tn->u.t.number = i++;
1144 	r->u.sa.proposals->u.p.transforms = t;
1145 	return r;
1146 }
1147 
lifetime_ike_process(struct sa_block * s,struct isakmp_attribute * a)1148 static void lifetime_ike_process(struct sa_block *s, struct isakmp_attribute *a)
1149 {
1150 	uint32_t value;
1151 
1152 	assert(a != NULL);
1153 	assert(a->type == IKE_ATTRIB_LIFE_TYPE);
1154 	assert(a->af == isakmp_attr_16);
1155 	assert(a->u.attr_16 == IKE_LIFE_TYPE_SECONDS || a->u.attr_16 == IKE_LIFE_TYPE_K);
1156 	assert(a->next != NULL);
1157 	assert(a->next->type == IKE_ATTRIB_LIFE_DURATION);
1158 
1159 	if (a->next->af == isakmp_attr_16)
1160 		value = a->next->u.attr_16;
1161 	else if (a->next->af == isakmp_attr_lots && a->next->u.lots.length == 4)
1162 		value = ntohl(*((uint32_t *) a->next->u.lots.data));
1163 	else {
1164 		DEBUG(2, printf("got unknown ike lifetime attributes af %d len %d\n",
1165 					a->next->af, a->next->u.lots.length));
1166 		return;
1167 	}
1168 
1169 	DEBUG(2, printf("got ike lifetime attributes: %d %s\n", value,
1170 		(a->u.attr_16 == IKE_LIFE_TYPE_SECONDS) ? "seconds" : "kilobyte"));
1171 
1172 	if (a->u.attr_16 == IKE_LIFE_TYPE_SECONDS)
1173 		s->ike.life.seconds = value;
1174 	else
1175 		s->ike.life.kbytes = value;
1176 }
1177 
lifetime_ipsec_process(struct sa_block * s,struct isakmp_attribute * a)1178 static void lifetime_ipsec_process(struct sa_block *s, struct isakmp_attribute *a)
1179 {
1180 	uint32_t value;
1181 
1182 	assert(a != NULL);
1183 	assert(a->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE);
1184 	assert(a->af == isakmp_attr_16);
1185 	assert(a->u.attr_16 == IPSEC_LIFE_SECONDS || a->u.attr_16 == IPSEC_LIFE_K);
1186 	assert(a->next != NULL);
1187 	assert(a->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION);
1188 
1189 	if (a->next->af == isakmp_attr_16)
1190 		value = a->next->u.attr_16;
1191 	else if (a->next->af == isakmp_attr_lots && a->next->u.lots.length == 4)
1192 		value = ntohl(*((uint32_t *) a->next->u.lots.data));
1193 	else
1194 		assert(0);
1195 
1196 	DEBUG(2, printf("got ipsec lifetime attributes: %d %s\n", value,
1197 		(a->u.attr_16 == IPSEC_LIFE_SECONDS) ? "seconds" : "kilobyte"));
1198 
1199 	if (a->u.attr_16 == IPSEC_LIFE_SECONDS)
1200 		s->ipsec.life.seconds = value;
1201 	else
1202 		s->ipsec.life.kbytes = value;
1203 
1204 	/* FIXME: for notice-payloads: write a seperate function to handle them */
1205 	/* bug: this may process lifetime-attributes of SAs twice but to no consequence */
1206 	if (a->next->next != NULL && a->next->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE)
1207 		lifetime_ipsec_process(s, a->next->next);
1208 }
1209 
do_phase1_am(const char * key_id,const char * shared_key,struct sa_block * s)1210 static void do_phase1_am(const char *key_id, const char *shared_key, struct sa_block *s)
1211 {
1212 	unsigned char i_nonce[20];
1213 	struct group *dh_grp;
1214 	unsigned char *dh_public;
1215 	unsigned char *returned_hash;
1216 	unsigned char *psk_hash;
1217 
1218 	struct isakmp_packet *p1;
1219 	struct isakmp_packet *r;
1220 	int seen_natt_vid = 0, seen_natd = 0, seen_natd_them = 0, seen_natd_us = 0, natd_type = 0;
1221 	unsigned char *natd_us = NULL, *natd_them = NULL;
1222 	int natt_draft = -1;
1223 	unsigned char *dh_shared_secret;
1224 
1225 	DEBUGTOP(2, printf("S4.1 create_nonce\n"));
1226 	gcry_create_nonce(s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1227 	s->ike.life.start = time(NULL);
1228 	s->ipsec.do_pfs = -1;
1229 	if (s->ike.i_cookie[0] == 0)
1230 		s->ike.i_cookie[0] = 1;
1231 	hex_dump("i_cookie", s->ike.i_cookie, ISAKMP_COOKIE_LENGTH, NULL);
1232 	gcry_create_nonce(i_nonce, sizeof(i_nonce));
1233 	hex_dump("i_nonce", i_nonce, sizeof(i_nonce), NULL);
1234 	DEBUGTOP(2, printf("S4.2 dh setup\n"));
1235 	/* Set up the Diffie-Hellman stuff.  */
1236 	{
1237 		dh_grp = group_get(get_dh_group_ike()->my_id);
1238 		dh_public = xallocc(dh_getlen(dh_grp));
1239 		dh_create_exchange(dh_grp, dh_public);
1240 		hex_dump("dh_public", dh_public, dh_getlen(dh_grp), NULL);
1241 	}
1242 
1243 	DEBUGTOP(2, printf("S4.3 AM packet_1\n"));
1244 	/* Create the first packet.  */
1245 	{
1246 		struct isakmp_payload *l;
1247 		uint8_t *pkt;
1248 		size_t pkt_len;
1249 
1250 		p1 = new_isakmp_packet();
1251 		memcpy(p1->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1252 		p1->isakmp_version = ISAKMP_VERSION;
1253 		p1->exchange_type = ISAKMP_EXCHANGE_AGGRESSIVE;
1254 		p1->payload = l = make_our_sa_ike();
1255 		l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_KE, dh_public, dh_getlen(dh_grp));
1256 		l->next->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_NONCE,
1257 			i_nonce, sizeof(i_nonce));
1258 		l = l->next->next;
1259 		l->next = new_isakmp_payload(ISAKMP_PAYLOAD_ID);
1260 		l = l->next;
1261 		if (opt_vendor == VENDOR_CISCO)
1262 			l->u.id.type = ISAKMP_IPSEC_ID_KEY_ID;
1263 		else
1264 			l->u.id.type = ISAKMP_IPSEC_ID_USER_FQDN;
1265 		l->u.id.protocol = IPPROTO_UDP;
1266 		l->u.id.port = ISAKMP_PORT; /* this must be 500, see rfc2407, 4.6.2 */
1267 		l->u.id.length = strlen(key_id);
1268 		l->u.id.data = xallocc(l->u.id.length);
1269 		memcpy(l->u.id.data, key_id, strlen(key_id));
1270 		l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1271 			VID_XAUTH, sizeof(VID_XAUTH));
1272 		l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1273 			VID_UNITY, sizeof(VID_UNITY));
1274 		if ((opt_natt_mode == NATT_NORMAL) || (opt_natt_mode == NATT_FORCE)) {
1275 			l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1276 				VID_NATT_RFC, sizeof(VID_NATT_RFC));
1277 			l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1278 				VID_NATT_02N, sizeof(VID_NATT_02N));
1279 			l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1280 				VID_NATT_02, sizeof(VID_NATT_02));
1281 			l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1282 				VID_NATT_01, sizeof(VID_NATT_01));
1283 			l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1284 				VID_NATT_00, sizeof(VID_NATT_00));
1285 		}
1286 		s->ike.dpd_idle = atoi(config[CONFIG_DPD_IDLE]);
1287 		if (s->ike.dpd_idle != 0) {
1288 			if (s->ike.dpd_idle < 10)
1289 				s->ike.dpd_idle = 10;
1290 			if (s->ike.dpd_idle > 86400)
1291 				s->ike.dpd_idle = 86400;
1292 			l = l->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
1293 				VID_DPD, sizeof(VID_DPD));
1294 		}
1295 		flatten_isakmp_packet(p1, &pkt, &pkt_len, 0);
1296 
1297 		/* Now, send that packet and receive a new one.  */
1298 		r_length = sendrecv(s, r_packet, sizeof(r_packet), pkt, pkt_len, 0);
1299 		free(pkt);
1300 	}
1301 	DEBUGTOP(2, printf("S4.4 AM_packet2\n"));
1302 	/* Decode the recieved packet.  */
1303 	{
1304 		int reject;
1305 		struct isakmp_payload *rp;
1306 		struct isakmp_payload *nonce = NULL;
1307 		struct isakmp_payload *ke = NULL;
1308 		struct isakmp_payload *hash = NULL;
1309 		struct isakmp_payload *last_cert = NULL;
1310 		struct isakmp_payload *sig = NULL;
1311 		struct isakmp_payload *idp = NULL;
1312 		int seen_sa = 0, seen_xauth_vid = 0;
1313 		unsigned char *psk_skeyid;
1314 		unsigned char *skeyid;
1315 		gcry_md_hd_t skeyid_ctx;
1316 
1317 #ifdef OPENSSL_GPL_VIOLATION
1318 		X509 *current_cert;
1319 		/* structure to store the certificate chain */
1320 		STACK_OF(X509) *cert_stack = sk_X509_new_null();
1321 #endif /* OPENSSL_GPL_VIOLATION */
1322 
1323 		reject = 0;
1324 		r = parse_isakmp_packet(r_packet, r_length, &reject);
1325 
1326 		/* Verify the correctness of the recieved packet.  */
1327 		if (reject == 0 && memcmp(r->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH) != 0)
1328 			reject = ISAKMP_N_INVALID_COOKIE;
1329 		if (reject == 0)
1330 			memcpy(s->ike.r_cookie, r->r_cookie, ISAKMP_COOKIE_LENGTH);
1331 		if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_AGGRESSIVE)
1332 			reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
1333 		if (reject == 0 && r->flags != 0)
1334 			reject = ISAKMP_N_INVALID_FLAGS;
1335 		if (reject == 0 && r->message_id != 0)
1336 			reject = ISAKMP_N_INVALID_MESSAGE_ID;
1337 		if (reject != 0)
1338 			error(1, 0, "response was invalid [1]: %s(%d)", val_to_string(reject, isakmp_notify_enum_array), reject);
1339 		for (rp = r->payload; rp && reject == 0; rp = rp->next)
1340 			switch (rp->type) {
1341 			case ISAKMP_PAYLOAD_SA:
1342 				if (reject == 0 && rp->u.sa.doi != ISAKMP_DOI_IPSEC)
1343 					reject = ISAKMP_N_DOI_NOT_SUPPORTED;
1344 				if (reject == 0 &&
1345 					rp->u.sa.situation != ISAKMP_IPSEC_SIT_IDENTITY_ONLY)
1346 					reject = ISAKMP_N_SITUATION_NOT_SUPPORTED;
1347 				if (reject == 0 &&
1348 					(rp->u.sa.proposals == NULL
1349 						|| rp->u.sa.proposals->next != NULL))
1350 					reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1351 				if (reject == 0 &&
1352 					rp->u.sa.proposals->u.p.prot_id !=
1353 					ISAKMP_IPSEC_PROTO_ISAKMP)
1354 					reject = ISAKMP_N_INVALID_PROTOCOL_ID;
1355 				if (reject == 0 && rp->u.sa.proposals->u.p.spi_size != 0)
1356 					reject = ISAKMP_N_INVALID_SPI;
1357 				if (reject == 0 &&
1358 					(rp->u.sa.proposals->u.p.transforms == NULL
1359 						|| rp->u.sa.proposals->u.p.transforms->next !=
1360 						NULL))
1361 					reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1362 				if (reject == 0 &&
1363 					(rp->u.sa.proposals->u.p.transforms->u.t.id
1364 						!= ISAKMP_IPSEC_KEY_IKE))
1365 					reject = ISAKMP_N_INVALID_TRANSFORM_ID;
1366 				if (reject == 0) {
1367 					struct isakmp_attribute *a
1368 						=
1369 						rp->u.sa.proposals->u.p.transforms->u.t.attributes;
1370 					int seen_enc = 0, seen_hash = 0, seen_auth = 0;
1371 					int seen_group = 0, seen_keylen = 0;
1372 					for (; a && reject == 0; a = a->next)
1373 						switch (a->type) {
1374 						case IKE_ATTRIB_GROUP_DESC:
1375 							if (a->af == isakmp_attr_16 &&
1376 								a->u.attr_16 ==
1377 								get_dh_group_ike()->ike_sa_id)
1378 								seen_group = 1;
1379 							else
1380 								reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1381 							break;
1382 						case IKE_ATTRIB_AUTH_METHOD:
1383 							if (a->af == isakmp_attr_16)
1384 								seen_auth = a->u.attr_16;
1385 							else
1386 								reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1387 							break;
1388 						case IKE_ATTRIB_HASH:
1389 							if (a->af == isakmp_attr_16)
1390 								seen_hash = a->u.attr_16;
1391 							else
1392 								reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1393 							break;
1394 						case IKE_ATTRIB_ENC:
1395 							if (a->af == isakmp_attr_16)
1396 								seen_enc = a->u.attr_16;
1397 							else
1398 								reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1399 							break;
1400 						case IKE_ATTRIB_KEY_LENGTH:
1401 							if (a->af == isakmp_attr_16)
1402 								seen_keylen = a->u.attr_16;
1403 							else
1404 								reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1405 							break;
1406 						case IKE_ATTRIB_LIFE_TYPE:
1407 							/* lifetime duration MUST follow lifetype attribute */
1408 							if (a->next->type == IKE_ATTRIB_LIFE_DURATION) {
1409 								lifetime_ike_process(s, a);
1410 							} else
1411 								reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1412 							break;
1413 						case IKE_ATTRIB_LIFE_DURATION:
1414 							/* already processed above in IKE_ATTRIB_LIFE_TYPE: */
1415 							break;
1416 						default:
1417 							DEBUG(1, printf
1418 								("unknown attribute %d, arborting..\n",
1419 									a->type));
1420 							reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
1421 							break;
1422 						}
1423 					if (!seen_group || !seen_auth || !seen_hash || !seen_enc)
1424 						reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
1425 
1426 					if (get_algo(SUPP_ALGO_AUTH, SUPP_ALGO_IKE_SA, seen_auth,
1427 							NULL, 0) == NULL)
1428 						reject = ISAKMP_N_NO_PROPOSAL_CHOSEN;
1429 					if (get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IKE_SA, seen_hash,
1430 							NULL, 0) == NULL)
1431 						reject = ISAKMP_N_NO_PROPOSAL_CHOSEN;
1432 					if (get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IKE_SA, seen_enc,
1433 							NULL, seen_keylen) == NULL)
1434 						reject = ISAKMP_N_NO_PROPOSAL_CHOSEN;
1435 
1436 					if (reject == 0) {
1437 						seen_sa = 1;
1438 						s->ike.auth_algo = seen_auth;
1439 						s->ike.cry_algo =
1440 							get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IKE_SA,
1441 							seen_enc, NULL, seen_keylen)->my_id;
1442 						s->ike.md_algo =
1443 							get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IKE_SA,
1444 							seen_hash, NULL, 0)->my_id;
1445 						s->ike.md_len = gcry_md_get_algo_dlen(s->ike.md_algo);
1446 						DEBUG(1, printf("IKE SA selected %s-%s-%s\n",
1447 								get_algo(SUPP_ALGO_AUTH,
1448 									SUPP_ALGO_IKE_SA, seen_auth,
1449 									NULL, 0)->name,
1450 								get_algo(SUPP_ALGO_CRYPT,
1451 									SUPP_ALGO_IKE_SA, seen_enc,
1452 									NULL, seen_keylen)->name,
1453 								get_algo(SUPP_ALGO_HASH,
1454 									SUPP_ALGO_IKE_SA, seen_hash,
1455 									NULL, 0)->name));
1456 						if (s->ike.cry_algo == GCRY_CIPHER_DES && !opt_1des) {
1457 							error(1, 0, "peer selected (single) DES as \"encryption\" method.\n"
1458 								"This algorithm is considered too weak today\n"
1459 								"If your vpn concentrator admin still insists on using DES\n"
1460 								"use the \"--enable-1des\" option.\n");
1461 						}
1462 					}
1463 				}
1464 				break;
1465 
1466 			case ISAKMP_PAYLOAD_ID:
1467 				idp = rp;
1468 				break;
1469 			case ISAKMP_PAYLOAD_KE:
1470 				ke = rp;
1471 				break;
1472 			case ISAKMP_PAYLOAD_NONCE:
1473 				nonce = rp;
1474 				break;
1475 			case ISAKMP_PAYLOAD_HASH:
1476 				hash = rp;
1477 				break;
1478 			case ISAKMP_PAYLOAD_CERT:
1479 				last_cert = rp;
1480 				if (last_cert->u.cert.encoding == ISAKMP_CERT_X509_SIG) {
1481 #ifdef OPENSSL_GPL_VIOLATION
1482 					/* convert the certificate to an openssl-X509 structure and push it onto the chain stack */
1483 					current_cert = d2i_X509(NULL, (const unsigned char **)&last_cert->u.cert.data, last_cert->u.cert.length);
1484 					sk_X509_push(cert_stack, current_cert);
1485 					last_cert->u.cert.data -= last_cert->u.cert.length; /* 'rewind' the pointer */
1486 #endif /* OPENSSL_GPL_VIOLATION */
1487 				}
1488 				break;
1489 			case ISAKMP_PAYLOAD_SIG:
1490 				sig = rp;
1491 				break;
1492 			case ISAKMP_PAYLOAD_VID:
1493 				if (rp->u.vid.length == sizeof(VID_XAUTH)
1494 					&& memcmp(rp->u.vid.data, VID_XAUTH,
1495 						sizeof(VID_XAUTH)) == 0) {
1496 					seen_xauth_vid = 1;
1497 				} else if (rp->u.vid.length == sizeof(VID_NATT_RFC)
1498 					&& memcmp(rp->u.vid.data, VID_NATT_RFC,
1499 						sizeof(VID_NATT_RFC)) == 0) {
1500 					seen_natt_vid = 1;
1501 					if (natt_draft < 1) natt_draft = 2;
1502 					DEBUG(2, printf("peer is NAT-T capable (RFC 3947)\n"));
1503 				} else if (rp->u.vid.length == sizeof(VID_NATT_02N)
1504 					&& memcmp(rp->u.vid.data, VID_NATT_02N,
1505 						sizeof(VID_NATT_02N)) == 0) {
1506 					seen_natt_vid = 1;
1507 					if (natt_draft < 1) natt_draft = 2;
1508 					DEBUG(2, printf("peer is NAT-T capable (draft-02)\\n\n")); /* sic! */
1509 				} else if (rp->u.vid.length == sizeof(VID_NATT_02)
1510 					&& memcmp(rp->u.vid.data, VID_NATT_02,
1511 						sizeof(VID_NATT_02)) == 0) {
1512 					seen_natt_vid = 1;
1513 					if (natt_draft < 1) natt_draft = 2;
1514 					DEBUG(2, printf("peer is NAT-T capable (draft-02)\n"));
1515 				} else if (rp->u.vid.length == sizeof(VID_NATT_01)
1516 					&& memcmp(rp->u.vid.data, VID_NATT_01,
1517 						sizeof(VID_NATT_01)) == 0) {
1518 					seen_natt_vid = 1;
1519 					if (natt_draft < 1) natt_draft = 1;
1520 					DEBUG(2, printf("peer is NAT-T capable (draft-01)\n"));
1521 				} else if (rp->u.vid.length == sizeof(VID_NATT_00)
1522 					&& memcmp(rp->u.vid.data, VID_NATT_00,
1523 						sizeof(VID_NATT_00)) == 0) {
1524 					seen_natt_vid = 1;
1525 					if (natt_draft < 0) natt_draft = 0;
1526 					DEBUG(2, printf("peer is NAT-T capable (draft-00)\n"));
1527 				} else if (rp->u.vid.length == sizeof(VID_DPD)
1528 					&& memcmp(rp->u.vid.data, VID_DPD,
1529 						sizeof(VID_DPD)) == 0) {
1530 					if (s->ike.dpd_idle != 0) {
1531 						gcry_create_nonce(&s->ike.dpd_seqno, sizeof(s->ike.dpd_seqno));
1532 						s->ike.dpd_seqno &= 0x7FFFFFFF;
1533 						s->ike.dpd_seqno_ack = s->ike.dpd_seqno;
1534 						s->ike.do_dpd = 1;
1535 						DEBUG(2, printf("peer is DPD capable (RFC3706)\n"));
1536 					} else {
1537 						DEBUG(2, printf("ignoring that peer is DPD capable (RFC3706)\n"));
1538 					}
1539 				} else if (rp->u.vid.length == sizeof(VID_NETSCREEN_15)
1540 					&& memcmp(rp->u.vid.data, VID_NETSCREEN_15,
1541 						sizeof(VID_NETSCREEN_15)) == 0) {
1542 					DEBUG(2, printf("peer is using ScreenOS 5.3, 5.4 or 6.0\n"));
1543 				} else if (rp->u.vid.length == sizeof(VID_HEARTBEAT_NOTIFY)
1544 					&& memcmp(rp->u.vid.data, VID_HEARTBEAT_NOTIFY,
1545 						sizeof(VID_HEARTBEAT_NOTIFY)) == 0) {
1546 					DEBUG(2, printf("peer sent Heartbeat Notify payload\n"));
1547 				} else {
1548 					hex_dump("unknown ISAKMP_PAYLOAD_VID",
1549 						rp->u.vid.data, rp->u.vid.length, NULL);
1550 				}
1551 				break;
1552 			case ISAKMP_PAYLOAD_NAT_D_OLD:
1553 			case ISAKMP_PAYLOAD_NAT_D:
1554 				natd_type = rp->type;
1555 				DEBUG(2, printf("peer is using type %d%s for NAT-Discovery payloads\n",
1556 					natd_type, val_to_string(natd_type, isakmp_payload_enum_array)));
1557 				if (!seen_sa /*|| !seen_natt_vid*/) {
1558 					reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
1559 				} else if (opt_natt_mode == NATT_NONE) {
1560 					;
1561 				} else if (rp->u.natd.length != s->ike.md_len) {
1562 					reject = ISAKMP_N_PAYLOAD_MALFORMED;
1563 				} else if (seen_natd == 0) {
1564 					gcry_md_hd_t hm;
1565 					uint16_t n_dst_port = htons(s->ike.dst_port);
1566 
1567 					natd_us = xallocc(s->ike.md_len);
1568 					natd_them = xallocc(s->ike.md_len);
1569 					memcpy(natd_us, rp->u.natd.data, s->ike.md_len);
1570 					gcry_md_open(&hm, s->ike.md_algo, 0);
1571 					gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1572 					gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1573 					gcry_md_write(hm, &s->dst, sizeof(struct in_addr));
1574 					gcry_md_write(hm, &n_dst_port, sizeof(uint16_t));
1575 					gcry_md_final(hm);
1576 					memcpy(natd_them, gcry_md_read(hm, 0), s->ike.md_len);
1577 					gcry_md_close(hm);
1578 					seen_natd = 1;
1579 				} else {
1580 					if (memcmp(natd_them, rp->u.natd.data, s->ike.md_len) == 0)
1581 						seen_natd_them = 1;
1582 				}
1583 				break;
1584 			case ISAKMP_PAYLOAD_N:
1585 				if (rp->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
1586 					if (rp->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
1587 						lifetime_ike_process(s, rp->u.n.attributes);
1588 					else if (rp->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
1589 						lifetime_ipsec_process(s, rp->u.n.attributes);
1590 					else
1591 						DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
1592 				} else {
1593 					DEBUG(1, printf("rejecting ISAKMP_PAYLOAD_N, type is not lifetime\n"));
1594 					reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
1595 				}
1596 				break;
1597 			default:
1598 				DEBUG(1, printf("rejecting invalid payload type %d\n", rp->type));
1599 				reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
1600 				break;
1601 			}
1602 
1603 		if (reject == 0) {
1604 			gcry_cipher_algo_info(s->ike.cry_algo, GCRYCTL_GET_BLKLEN, NULL, &(s->ike.ivlen));
1605 			gcry_cipher_algo_info(s->ike.cry_algo, GCRYCTL_GET_KEYLEN, NULL, &(s->ike.keylen));
1606 		}
1607 
1608 		if (reject == 0 && (ke == NULL || ke->u.ke.length != dh_getlen(dh_grp)))
1609 			reject = ISAKMP_N_INVALID_KEY_INFORMATION;
1610 		if (reject == 0 && nonce == NULL)
1611 			reject = ISAKMP_N_INVALID_HASH_INFORMATION;
1612 		if (reject != 0)
1613 			error(1, 0, "response was invalid [2]: %s(%d)", val_to_string(reject, isakmp_notify_enum_array), reject);
1614 		if (reject == 0 && idp == NULL)
1615 			reject = ISAKMP_N_INVALID_ID_INFORMATION;
1616 
1617 		/* Decide if signature or hash is expected (sig only if vpnc is initiator of hybrid-auth */
1618 		if (reject == 0 && opt_auth_mode == AUTH_MODE_PSK && (hash == NULL || hash->u.hash.length != s->ike.md_len))
1619 			reject = ISAKMP_N_INVALID_HASH_INFORMATION;
1620 		if (reject == 0 && sig == NULL &&
1621 			(opt_auth_mode == AUTH_MODE_CERT ||
1622 			 opt_auth_mode == AUTH_MODE_HYBRID))
1623 			reject = ISAKMP_N_INVALID_SIGNATURE;
1624 		if (reject != 0)
1625 			error(1, 0, "response was invalid [3]: %s(%d)", val_to_string(reject, isakmp_notify_enum_array), reject);
1626 
1627 		/* Determine the shared secret.  */
1628 		dh_shared_secret = xallocc(dh_getlen(dh_grp));
1629 		dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
1630 		hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
1631 		/* Generate SKEYID.  */
1632 		{
1633 			gcry_md_open(&skeyid_ctx, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1634 			gcry_md_setkey(skeyid_ctx, shared_key, strlen(shared_key));
1635 			gcry_md_write(skeyid_ctx, i_nonce, sizeof(i_nonce));
1636 			gcry_md_write(skeyid_ctx, nonce->u.nonce.data, nonce->u.nonce.length);
1637 			gcry_md_final(skeyid_ctx);
1638 			psk_skeyid = xallocc(s->ike.md_len);
1639 			memcpy(psk_skeyid, gcry_md_read(skeyid_ctx, 0), s->ike.md_len);
1640 			if (opt_debug < 99)
1641 				DEBUG(3, printf("(not dumping psk hash)\n"));
1642 			else
1643 				hex_dump("psk_skeyid", psk_skeyid, s->ike.md_len, NULL);
1644 			free(psk_skeyid);
1645 			gcry_md_close(skeyid_ctx);
1646 			DEBUG(99, printf("shared-key: %s\n",shared_key));
1647 
1648 			/* SKEYID - psk only */
1649 			if (s->ike.auth_algo == IKE_AUTH_PRESHARED ||
1650 				s->ike.auth_algo == IKE_AUTH_XAUTHInitPreShared ||
1651 				s->ike.auth_algo == IKE_AUTH_XAUTHRespPreShared) {
1652 				gcry_md_open(&skeyid_ctx, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1653 				gcry_md_setkey(skeyid_ctx, shared_key, strlen(shared_key));
1654 				gcry_md_write(skeyid_ctx, i_nonce, sizeof(i_nonce));
1655 				gcry_md_write(skeyid_ctx, nonce->u.nonce.data, nonce->u.nonce.length);
1656 				gcry_md_final(skeyid_ctx);
1657 			} else if (s->ike.auth_algo == IKE_AUTH_DSS ||
1658 				s->ike.auth_algo == IKE_AUTH_RSA_SIG ||
1659 				s->ike.auth_algo == IKE_AUTH_ECDSA_SIG ||
1660 				s->ike.auth_algo == IKE_AUTH_HybridInitRSA ||
1661 				s->ike.auth_algo == IKE_AUTH_HybridRespRSA ||
1662 				s->ike.auth_algo == IKE_AUTH_HybridInitDSS ||
1663 				s->ike.auth_algo == IKE_AUTH_HybridRespDSS ||
1664 				s->ike.auth_algo == IKE_AUTH_XAUTHInitDSS ||
1665 				s->ike.auth_algo == IKE_AUTH_XAUTHRespDSS ||
1666 				s->ike.auth_algo == IKE_AUTH_XAUTHInitRSA ||
1667 				s->ike.auth_algo == IKE_AUTH_XAUTHRespRSA) {
1668 				unsigned char *key;
1669 				int key_len;
1670 				key_len = sizeof(i_nonce) + nonce->u.nonce.length;
1671 				key = xallocc(key_len);
1672 				memcpy(key, i_nonce, sizeof(i_nonce));
1673 				memcpy(key + sizeof(i_nonce), nonce->u.nonce.data, nonce->u.nonce.length);
1674 				gcry_md_open(&skeyid_ctx, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1675 				gcry_md_setkey(skeyid_ctx, key, key_len);
1676 				gcry_md_write(skeyid_ctx, dh_shared_secret, dh_getlen(dh_grp));
1677 				gcry_md_final(skeyid_ctx);
1678 			} else
1679 				error(1, 0, "SKEYID could not be computed: %s", "the selected authentication method is not supported");
1680 			skeyid = gcry_md_read(skeyid_ctx, 0);
1681 			hex_dump("skeyid", skeyid, s->ike.md_len, NULL);
1682 		}
1683 
1684 		/* Verify the hash.  */
1685 		{
1686 			gcry_md_hd_t hm;
1687 			unsigned char *expected_hash;
1688 			uint8_t *sa_f, *idi_f, *idp_f;
1689 			size_t sa_size, idi_size, idp_size;
1690 			struct isakmp_payload *sa, *idi;
1691 
1692 			sa = p1->payload;
1693 			for (idi = sa; idi->type != ISAKMP_PAYLOAD_ID; idi = idi->next) ;
1694 			flatten_isakmp_payload(sa, &sa_f, &sa_size);
1695 			flatten_isakmp_payload(idi, &idi_f, &idi_size);
1696 			flatten_isakmp_payload(idp, &idp_f, &idp_size);
1697 
1698 			gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1699 			gcry_md_setkey(hm, skeyid, s->ike.md_len);
1700 			gcry_md_write(hm, ke->u.ke.data, ke->u.ke.length);
1701 			gcry_md_write(hm, dh_public, dh_getlen(dh_grp));
1702 			gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1703 			gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1704 			gcry_md_write(hm, sa_f + 4, sa_size - 4);
1705 			gcry_md_write(hm, idp_f + 4, idp_size - 4);
1706 			gcry_md_final(hm);
1707 			expected_hash = gcry_md_read(hm, 0);
1708 			hex_dump("expected hash", expected_hash, s->ike.md_len, NULL);
1709 
1710 			if (opt_auth_mode == AUTH_MODE_PSK) {
1711 				if (memcmp(expected_hash, hash->u.hash.data, s->ike.md_len) != 0)
1712 					error(2, 0, "hash comparison failed: %s(%d)\ncheck group password!",
1713 						val_to_string(ISAKMP_N_AUTHENTICATION_FAILED, isakmp_notify_enum_array),
1714 						ISAKMP_N_AUTHENTICATION_FAILED);
1715 				hex_dump("received hash", hash->u.hash.data, hash->u.hash.length, NULL);
1716 			} else if (opt_auth_mode == AUTH_MODE_CERT ||
1717 				opt_auth_mode == AUTH_MODE_HYBRID) {
1718 #ifdef OPENSSL_GPL_VIOLATION
1719 
1720 				/* BEGIN - check the signature using OpenSSL */
1721 
1722 				X509 		*x509;
1723 				EVP_PKEY 	*pkey;
1724 				RSA 		*rsa;
1725 				X509_STORE 	*store;
1726 				/* X509_LOOKUP	*lookup; */
1727 				X509_STORE_CTX	*verify_ctx;
1728 				unsigned char	*rec_hash;
1729 				int		decr_size;
1730 
1731 			  	hex_dump("received signature", sig->u.sig.data, sig->u.sig.length, NULL);
1732 				OpenSSL_add_all_ciphers();
1733 				OpenSSL_add_all_digests();
1734 				OpenSSL_add_all_algorithms();
1735 
1736 				ERR_load_crypto_strings();
1737 
1738 				hex_dump("last cert", last_cert->u.cert.data, last_cert->u.cert.length, NULL);
1739 				x509 = d2i_X509(NULL, (const unsigned char **)&last_cert->u.cert.data, last_cert->u.cert.length);
1740 				if (x509 == NULL) {
1741 					ERR_print_errors_fp (stderr);
1742 					error(1, 0, "x509 error\n");
1743 				}
1744 				DEBUG(3, printf("Subject name hash: %08lx\n",X509_subject_name_hash(x509)));
1745 
1746 				/* BEGIN - verify certificate chain */
1747 				/* create the cert store */
1748 				if (!(store = X509_STORE_new())) {
1749 					error(1, 0, "Error creating X509_STORE object\n");
1750 				}
1751 				/* load the CA certificates */
1752 				if (X509_STORE_load_locations (store, config[CONFIG_CA_FILE], config[CONFIG_CA_DIR]) != 1) {
1753 					error(1, 0, "Error loading the CA file or directory\n");
1754 				}
1755 				if (X509_STORE_set_default_paths (store) != 1) {
1756 					error(1, 0, "Error loading the system-wide CA certificates\n");
1757 				}
1758 
1759 #if 0
1760 				/* check CRLs */
1761 				/* add the corresponding CRL for each CA in the chain to the lookup */
1762 #define CRL_FILE "root-ca-crl.crl.pem"
1763 
1764 				if (!(lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()))) {
1765 					error(1, 0, "Error creating X509 lookup object.\n");
1766 				}
1767 				if (X509_load_crl_file(lookup, CRL_FILE, X509_FILETYPE_PEM) != 1) {
1768 					ERR_print_errors_fp(stderr);
1769 					error(1, 0, "Error reading CRL file\n");
1770 				}
1771 				X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1772 #endif /* 0 */
1773 				/* create a verification context and initialize it */
1774 				if (!(verify_ctx = X509_STORE_CTX_new ())) {
1775 					error(1, 0, "Error creating X509_STORE_CTX object\n");
1776 				}
1777 				/* X509_STORE_CTX_init did not return an error condition
1778 				in prior versions */
1779 				if (X509_STORE_CTX_init (verify_ctx, store, x509, cert_stack) != 1)
1780 					printf("Error intializing verification context\n");
1781 
1782 				/* verify the certificate */
1783 				if (X509_verify_cert(verify_ctx) != 1) {
1784 					ERR_print_errors_fp(stderr);
1785 					error(2, 0, "Error verifying the certificate-chain\n");
1786 				} else
1787 					DEBUG(3, printf("Certificate-chain verified correctly!\n"));
1788 
1789 				/* END   - verify certificate chain */
1790 
1791 
1792 				/* BEGIN - Signature Verification */
1793 				pkey = X509_get_pubkey(x509);
1794 				if (pkey == NULL) {
1795 					ERR_print_errors_fp (stderr);
1796 					exit (1);
1797 				}
1798 
1799 				rsa = EVP_PKEY_get1_RSA(pkey);
1800 				if (rsa == NULL) {
1801 					ERR_print_errors_fp (stderr);
1802 					exit (1);
1803 				}
1804 				rec_hash = xallocc(s->ike.md_len);
1805 				decr_size = RSA_public_decrypt(sig->u.sig.length, sig->u.sig.data, rec_hash, rsa, RSA_PKCS1_PADDING);
1806 
1807 				if (decr_size != (int) s->ike.md_len) {
1808 					printf("Decrypted-Size: %d\n",decr_size);
1809 					hex_dump("    decr_hash", rec_hash, decr_size, NULL);
1810 					hex_dump("expected hash", expected_hash, s->ike.md_len, NULL);
1811 
1812 					error(2, 0, "The hash-value, which was decrypted from the received signature, and the expected hash-value differ in size.\n");
1813 				} else {
1814 					if (memcmp(rec_hash, expected_hash, decr_size) != 0) {
1815 						printf("Decrypted-Size: %d\n",decr_size);
1816 						hex_dump("    decr_hash", rec_hash, decr_size, NULL);
1817 						hex_dump("expected hash", expected_hash, s->ike.md_len, NULL);
1818 
1819 						error(2, 0, "The hash-value, which was decrypted from the received signature, and the expected hash-value differ.\n");
1820 					} else {
1821 						DEBUG(3, printf("Signature MATCH!!\n"));
1822 					}
1823 				}
1824 				/* END - Signature Verification */
1825 
1826 				EVP_PKEY_free(pkey);
1827 				free(rec_hash);
1828 
1829 				/* END   - check the signature using OpenSSL */
1830 #endif /* OPENSSL_GPL_VIOLATION */
1831 			}
1832 
1833 			gcry_md_close(hm);
1834 
1835 			gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1836 			gcry_md_setkey(hm, skeyid, s->ike.md_len);
1837 			gcry_md_write(hm, dh_public, dh_getlen(dh_grp));
1838 			gcry_md_write(hm, ke->u.ke.data, ke->u.ke.length);
1839 			gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1840 			gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1841 			gcry_md_write(hm, sa_f + 4, sa_size - 4);
1842 			gcry_md_write(hm, idi_f + 4, idi_size - 4);
1843 			gcry_md_final(hm);
1844 			returned_hash = xallocc(s->ike.md_len);
1845 			memcpy(returned_hash, gcry_md_read(hm, 0), s->ike.md_len);
1846 			gcry_md_close(hm);
1847 			hex_dump("returned_hash", returned_hash, s->ike.md_len, NULL);
1848 
1849 			/* PRESHARED_KEY_HASH */
1850 			gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1851 			gcry_md_setkey(hm, skeyid, s->ike.md_len);
1852 			gcry_md_write(hm, shared_key, strlen(shared_key));
1853 			gcry_md_final(hm);
1854 			psk_hash = xallocc(s->ike.md_len);
1855 			memcpy(psk_hash, gcry_md_read(hm, 0), s->ike.md_len);
1856 			gcry_md_close(hm);
1857 			hex_dump("psk_hash", psk_hash, s->ike.md_len, NULL);
1858 			/* End PRESHARED_KEY_HASH */
1859 
1860 			free(sa_f);
1861 			free(idi_f);
1862 			free(idp_f);
1863 		}
1864 
1865 		/* Determine all the SKEYID_x keys.  */
1866 		{
1867 			gcry_md_hd_t hm;
1868 			int i;
1869 			static const unsigned char c012[3] = { 0, 1, 2 };
1870 			unsigned char *skeyid_e;
1871 			unsigned char *dh_shared_secret;
1872 
1873 			/* Determine the shared secret.  */
1874 			dh_shared_secret = xallocc(dh_getlen(dh_grp));
1875 			dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
1876 			hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
1877 
1878 			gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1879 			gcry_md_setkey(hm, skeyid, s->ike.md_len);
1880 			gcry_md_write(hm, dh_shared_secret, dh_getlen(dh_grp));
1881 			gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1882 			gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1883 			gcry_md_write(hm, c012 + 0, 1);
1884 			gcry_md_final(hm);
1885 			if (s->ike.skeyid_d) free(s->ike.skeyid_d);
1886 			s->ike.skeyid_d = xallocc(s->ike.md_len);
1887 			memcpy(s->ike.skeyid_d, gcry_md_read(hm, 0), s->ike.md_len);
1888 			gcry_md_close(hm);
1889 			hex_dump("skeyid_d", s->ike.skeyid_d, s->ike.md_len, NULL);
1890 
1891 			gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1892 			gcry_md_setkey(hm, skeyid, s->ike.md_len);
1893 			gcry_md_write(hm, s->ike.skeyid_d, s->ike.md_len);
1894 			gcry_md_write(hm, dh_shared_secret, dh_getlen(dh_grp));
1895 			gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1896 			gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1897 			gcry_md_write(hm, c012 + 1, 1);
1898 			gcry_md_final(hm);
1899 			if (s->ike.skeyid_a) free(s->ike.skeyid_a);
1900 			s->ike.skeyid_a = xallocc(s->ike.md_len);
1901 			memcpy(s->ike.skeyid_a, gcry_md_read(hm, 0), s->ike.md_len);
1902 			gcry_md_close(hm);
1903 			hex_dump("skeyid_a", s->ike.skeyid_a, s->ike.md_len, NULL);
1904 
1905 			gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1906 			gcry_md_setkey(hm, skeyid, s->ike.md_len);
1907 			gcry_md_write(hm, s->ike.skeyid_a, s->ike.md_len);
1908 			gcry_md_write(hm, dh_shared_secret, dh_getlen(dh_grp));
1909 			gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1910 			gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1911 			gcry_md_write(hm, c012 + 2, 1);
1912 			gcry_md_final(hm);
1913 			skeyid_e = xallocc(s->ike.md_len);
1914 			memcpy(skeyid_e, gcry_md_read(hm, 0), s->ike.md_len);
1915 			gcry_md_close(hm);
1916 			hex_dump("skeyid_e", skeyid_e, s->ike.md_len, NULL);
1917 
1918 			memset(dh_shared_secret, 0, sizeof(dh_shared_secret));
1919 			free(dh_shared_secret);
1920 
1921 			/* Determine the IKE encryption key.  */
1922 			if (s->ike.key) free(s->ike.key);
1923 			s->ike.key = xallocc(s->ike.keylen);
1924 
1925 			if (s->ike.keylen > s->ike.md_len) {
1926 				for (i = 0; i * s->ike.md_len < s->ike.keylen; i++) {
1927 					gcry_md_open(&hm, s->ike.md_algo, GCRY_MD_FLAG_HMAC);
1928 					gcry_md_setkey(hm, skeyid_e, s->ike.md_len);
1929 					if (i == 0)
1930 						gcry_md_write(hm, "" /* &'\0' */ , 1);
1931 					else
1932 						gcry_md_write(hm, s->ike.key + (i - 1) * s->ike.md_len,
1933 							s->ike.md_len);
1934 					gcry_md_final(hm);
1935 					memcpy(s->ike.key + i * s->ike.md_len, gcry_md_read(hm, 0),
1936 						min(s->ike.md_len, s->ike.keylen - i * s->ike.md_len));
1937 					gcry_md_close(hm);
1938 				}
1939 			} else { /* keylen <= md_len */
1940 				memcpy(s->ike.key, skeyid_e, s->ike.keylen);
1941 			}
1942 			hex_dump("enc-key", s->ike.key, s->ike.keylen, NULL);
1943 
1944 			memset(skeyid_e, 0, s->ike.md_len);
1945 			free(skeyid_e);
1946 		}
1947 
1948 		/* Determine the initial IV.  */
1949 		{
1950 			gcry_md_hd_t hm;
1951 
1952 			assert(s->ike.ivlen <= s->ike.md_len);
1953 			gcry_md_open(&hm, s->ike.md_algo, 0);
1954 			gcry_md_write(hm, dh_public, dh_getlen(dh_grp));
1955 			gcry_md_write(hm, ke->u.ke.data, ke->u.ke.length);
1956 			gcry_md_final(hm);
1957 			if (s->ike.current_iv) free(s->ike.current_iv);
1958 			s->ike.current_iv = xallocc(s->ike.ivlen);
1959 			memcpy(s->ike.current_iv, gcry_md_read(hm, 0), s->ike.ivlen);
1960 			gcry_md_close(hm);
1961 			hex_dump("current_iv", s->ike.current_iv, s->ike.ivlen, NULL);
1962 			memset(s->ike.current_iv_msgid, 0, 4);
1963 		}
1964 
1965 		gcry_md_close(skeyid_ctx);
1966 	}
1967 
1968 	DEBUGTOP(2, printf("S4.5 AM_packet3\n"));
1969 	/* Send final phase 1 packet.  */
1970 	{
1971 		struct isakmp_packet *p2;
1972 		uint8_t *p2kt;
1973 		size_t p2kt_len;
1974 		struct isakmp_payload *pl;
1975 #if 0 /* cert support */
1976 #ifdef OPENSSL_GPL_VIOLATION
1977 		struct isakmp_payload *last_cert = NULL;
1978 		struct isakmp_payload *sig = NULL;
1979 
1980 
1981 		X509 *current_cert;
1982 		/* structure to store the certificate chain */
1983 		STACK_OF(X509) *cert_stack = sk_X509_new_null();
1984 #endif /* OPENSSL_GPL_VIOLATION */
1985 #endif /* 0 */
1986 
1987 		p2 = new_isakmp_packet();
1988 		memcpy(p2->i_cookie, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
1989 		memcpy(p2->r_cookie, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
1990 		p2->flags = ISAKMP_FLAG_E;
1991 		p2->isakmp_version = ISAKMP_VERSION;
1992 		p2->exchange_type = ISAKMP_EXCHANGE_AGGRESSIVE;
1993 	/* XXX CERT Add id(?), cert and sig here in case of cert auth */
1994 		p2->payload = new_isakmp_data_payload(ISAKMP_PAYLOAD_HASH,
1995 			returned_hash, s->ike.md_len);
1996 		p2->payload->next = pl = new_isakmp_payload(ISAKMP_PAYLOAD_N);
1997 		pl->u.n.doi = ISAKMP_DOI_IPSEC;
1998 		pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
1999 		pl->u.n.type = ISAKMP_N_IPSEC_INITIAL_CONTACT;
2000 		pl->u.n.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
2001 		pl->u.n.spi = xallocc(2 * ISAKMP_COOKIE_LENGTH);
2002 		memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
2003 		memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
2004 
2005 		/* send PSK-hash if hybrid authentication is negotiated */
2006 		if (s->ike.auth_algo == IKE_AUTH_HybridInitRSA ||
2007 			s->ike.auth_algo == IKE_AUTH_HybridInitDSS) {
2008 			/* Notify - PRESHARED_KEY_HASH */
2009 			pl = pl->next = new_isakmp_payload(ISAKMP_PAYLOAD_N);
2010 			pl->u.n.doi = ISAKMP_DOI_IPSEC;
2011 			pl->u.n.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
2012 			/* Notify Message - Type: PRESHARED_KEY_HASH */
2013 			pl->u.n.type =  ISAKMP_N_CISCO_PRESHARED_KEY_HASH;
2014 			pl->u.n.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
2015 			pl->u.n.spi = xallocc(2 * ISAKMP_COOKIE_LENGTH);
2016 			memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 0,
2017 				s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
2018 			memcpy(pl->u.n.spi + ISAKMP_COOKIE_LENGTH * 1,
2019 				s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
2020 			pl->u.n.data_length = s->ike.md_len;
2021 			pl->u.n.data = xallocc(pl->u.n.data_length);
2022 			memcpy(pl->u.n.data, psk_hash, pl->u.n.data_length);
2023 			/* End Notify - PRESHARED_KEY_HASH */
2024 		}
2025 		pl = pl->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
2026 			VID_UNKNOWN, sizeof(VID_UNKNOWN));
2027 		pl = pl->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_VID,
2028 			VID_UNITY, sizeof(VID_UNITY));
2029 
2030 		/* include NAT traversal discovery payloads */
2031 		if (seen_natt_vid) {
2032 			assert(natd_type != 0);
2033 			pl = pl->next = new_isakmp_data_payload(natd_type,
2034 				natd_them, s->ike.md_len);
2035 			/* this could be repeated fo any known outbound interfaces */
2036 			{
2037 				gcry_md_hd_t hm;
2038 				uint16_t n_src_port = htons(s->ike.src_port);
2039 
2040 				gcry_md_open(&hm, s->ike.md_algo, 0);
2041 				gcry_md_write(hm, s->ike.i_cookie, ISAKMP_COOKIE_LENGTH);
2042 				gcry_md_write(hm, s->ike.r_cookie, ISAKMP_COOKIE_LENGTH);
2043 				gcry_md_write(hm, &s->src, sizeof(struct in_addr));
2044 				gcry_md_write(hm, &n_src_port, sizeof(uint16_t));
2045 				gcry_md_final(hm);
2046 				pl = pl->next = new_isakmp_data_payload(natd_type,
2047 					gcry_md_read(hm, 0), s->ike.md_len);
2048 				if (opt_natt_mode == NATT_FORCE) /* force detection of "this end behind NAT" */
2049 					pl->u.ke.data[0] ^= 1; /* by flipping a bit in the nat-detection-hash */
2050 				if (seen_natd && memcmp(natd_us, pl->u.ke.data, s->ike.md_len) == 0)
2051 					seen_natd_us = 1;
2052 				gcry_md_close(hm);
2053 			}
2054 			if (seen_natd) {
2055 				free(natd_us);
2056 				free(natd_them);
2057 			}
2058 			/* if there is a NAT, change to port 4500 and select UDP encap */
2059 			if (!seen_natd_us || !seen_natd_them) {
2060 				DEBUG(1, printf("NAT status: this end behind NAT? %s -- remote end behind NAT? %s\n",
2061 					seen_natd_us ? "no" : "YES", seen_natd_them ? "no" : "YES"));
2062 				switch (natd_type) {
2063 					case ISAKMP_PAYLOAD_NAT_D:
2064 						s->ipsec.encap_mode = IPSEC_ENCAP_UDP_TUNNEL;
2065 						break;
2066 					case ISAKMP_PAYLOAD_NAT_D_OLD:
2067 						s->ipsec.encap_mode = IPSEC_ENCAP_UDP_TUNNEL_OLD;
2068 						break;
2069 					default:
2070 						abort();
2071 				}
2072 				if (natt_draft >= 2) {
2073 					s->ipsec.natt_active_mode = NATT_ACTIVE_RFC;
2074 					close(s->ike_fd);
2075 					if (s->ike.src_port == ISAKMP_PORT)
2076 						s->ike.src_port = ISAKMP_PORT_NATT;
2077 					s->ike_fd = make_socket(s, s->ike.src_port, s->ike.dst_port = ISAKMP_PORT_NATT);
2078 				} else {
2079 					s->ipsec.natt_active_mode = NATT_ACTIVE_DRAFT_OLD;
2080 				}
2081 			} else {
2082 				DEBUG(1, printf("NAT status: NAT-T VID seen, no NAT device detected\n"));
2083 			}
2084 		} else {
2085 			DEBUG(1, printf("NAT status: no NAT-T VID seen\n"));
2086 		}
2087 
2088 
2089 		flatten_isakmp_packet(p2, &p2kt, &p2kt_len, s->ike.ivlen);
2090 		free_isakmp_packet(p2);
2091 		isakmp_crypt(s, p2kt, p2kt_len, 1);
2092 
2093 		if (s->ike.initial_iv) free(s->ike.initial_iv);
2094 		s->ike.initial_iv = xallocc(s->ike.ivlen);
2095 		memcpy(s->ike.initial_iv, s->ike.current_iv, s->ike.ivlen);
2096 		hex_dump("initial_iv", s->ike.initial_iv, s->ike.ivlen, NULL);
2097 
2098 		/* Now, send that packet and receive a new one.  */
2099 		r_length = sendrecv(s, r_packet, sizeof(r_packet), p2kt, p2kt_len, 0);
2100 		free(p2kt);
2101 	}
2102 	DEBUGTOP(2, printf("S4.6 cleanup\n"));
2103 
2104 	free_isakmp_packet(p1);
2105 	/* This seems to cause a duplicate free of some data:
2106 	 * *** glibc detected *** vpnc-connect: free(): invalid pointer: 0x09d63ba5
2107 	 * See also: http://bugs.gentoo.org/show_bug.cgi?id=229003
2108 	 */
2109 #if 0
2110 	free_isakmp_packet(r);
2111 #endif
2112 	free(returned_hash);
2113 	free(dh_public);
2114 	free(dh_shared_secret);
2115 	free(psk_hash);
2116 	group_free(dh_grp);
2117 }
2118 
do_phase2_notice_check(struct sa_block * s,struct isakmp_packet ** r_p)2119 static int do_phase2_notice_check(struct sa_block *s, struct isakmp_packet **r_p)
2120 {
2121 	int reject = 0;
2122 	struct isakmp_packet *r;
2123 
2124 	while (1) {
2125 		reject = unpack_verify_phase2(s, r_packet, r_length, r_p, NULL, 0);
2126 		if (reject == ISAKMP_N_INVALID_COOKIE) {
2127 			r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
2128 			continue;
2129 		}
2130 		if (*r_p == NULL) {
2131 			assert(reject != 0);
2132 			return reject;
2133 		}
2134 		r = *r_p;
2135 
2136 		/* check for notices */
2137 		if (r->exchange_type == ISAKMP_EXCHANGE_INFORMATIONAL &&
2138 			r->payload->next != NULL) {
2139 			if (r->payload->next->type == ISAKMP_PAYLOAD_N) {
2140 				if (r->payload->next->u.n.type == ISAKMP_N_CISCO_LOAD_BALANCE) {
2141 					/* load balancing notice ==> restart with new gw */
2142 					if (r->payload->next->u.n.data_length != 4)
2143 						error(1, 0, "malformed loadbalance target");
2144 					s->dst = *(struct in_addr *)r->payload->next->u.n.data;
2145 					s->ike.dst_port = ISAKMP_PORT;
2146 					s->ipsec.encap_mode = IPSEC_ENCAP_TUNNEL;
2147 					s->ipsec.natt_active_mode = NATT_ACTIVE_NONE;
2148 					if (s->ike.src_port == ISAKMP_PORT_NATT)
2149 						s->ike.src_port = ISAKMP_PORT;
2150 					close(s->ike_fd);
2151 					s->ike_fd = make_socket(s, s->ike.src_port, s->ike.dst_port);
2152 					DEBUG(2, printf("got cisco loadbalancing notice, diverting to %s\n",
2153 							inet_ntoa(s->dst)));
2154 					return -1;
2155 				} else if (r->payload->next->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
2156 					if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
2157 						lifetime_ike_process(s, r->payload->next->u.n.attributes);
2158 					else if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
2159 						lifetime_ipsec_process(s, r->payload->next->u.n.attributes);
2160 					else
2161 						DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
2162 					r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
2163 					continue;
2164 				} else if (r->payload->next->u.n.type == ISAKMP_N_IPSEC_INITIAL_CONTACT) {
2165 					/* why in hell do we get this?? */
2166 					DEBUG(2, printf("got initial contact notice, ignoring..\n"));
2167 					r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
2168 					continue;
2169 				} else {
2170 					/* whatever */
2171 					printf("received notice of type %s(%d), giving up\n",
2172 						val_to_string(r->payload->next->u.n.type, isakmp_notify_enum_array),
2173 						r->payload->next->u.n.type);
2174 					return reject;
2175 				}
2176 			}
2177 			if (r->payload->next->type == ISAKMP_PAYLOAD_D) {
2178 				/* delete notice ==> ignore */
2179 				DEBUG(2, printf("got delete for old connection, ignoring..\n"));
2180 				r_length = sendrecv(s, r_packet, sizeof(r_packet), NULL, 0, 0);
2181 				continue;
2182 			}
2183 		}
2184 
2185 		break;
2186 	}
2187 	return reject;
2188 }
2189 
do_phase2_xauth(struct sa_block * s)2190 static int do_phase2_xauth(struct sa_block *s)
2191 {
2192 	struct isakmp_packet *r = NULL;
2193 	int loopcount;
2194 	int reject;
2195 	int passwd_used = 0;
2196 
2197 	DEBUGTOP(2, printf("S5.1 xauth_start\n"));
2198 	/* This can go around for a while.  */
2199 	for (loopcount = 0;; loopcount++) {
2200 		struct isakmp_payload *rp;
2201 		struct isakmp_attribute *a, *ap, *reply_attr;
2202 		char ntop_buf[32];
2203 		int seen_answer = 0;
2204 
2205 		DEBUGTOP(2, printf("S5.2 notice_check\n"));
2206 
2207 		/* recv and check for notices */
2208 		if (r) free_isakmp_packet(r);
2209 		r = NULL;
2210 		reject = do_phase2_notice_check(s, &r);
2211 		if (reject == -1) {
2212 			if (r) free_isakmp_packet(r);
2213 			return 1;
2214 		}
2215 
2216 		DEBUGTOP(2, printf("S5.3 type-is-xauth check\n"));
2217 		/* Check the transaction type is OK.  */
2218 		if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_MODECFG_TRANSACTION)
2219 			reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
2220 
2221 		/* After the hash, expect an attribute block.  */
2222 		if (reject == 0
2223 			&& (r->payload->next == NULL
2224 				|| r->payload->next->next != NULL
2225 				|| r->payload->next->type != ISAKMP_PAYLOAD_MODECFG_ATTR))
2226 			reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
2227 
2228 		if (reject == 0 && r->payload->next->u.modecfg.type == ISAKMP_MODECFG_CFG_SET)
2229 			break;
2230 		if (reject == 0 && r->payload->next->u.modecfg.type != ISAKMP_MODECFG_CFG_REQUEST)
2231 			reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
2232 
2233 		if (reject != 0)
2234 			phase2_fatal(s, "expected xauth packet; rejected: %s(%d)", reject);
2235 
2236 		DEBUGTOP(2, printf("S5.4 xauth type check\n"));
2237 		a = r->payload->next->u.modecfg.attributes;
2238 		/* First, print any messages, and verify that we understand the
2239 		 * conversation. This looks for any place were input is
2240 		 * required - in these cases, we need to print the prompt
2241 		 * regardless of whether the user requested interactive mode
2242 		 * or not. */
2243 		for (ap = a; ap && seen_answer == 0; ap = ap->next)
2244 			if (ap->type == ISAKMP_XAUTH_06_ATTRIB_ANSWER
2245 			    || ap->type == ISAKMP_XAUTH_06_ATTRIB_NEXT_PIN
2246 			    /* || ap->type == ISAKMP_XAUTH_06_ATTRIB_PASSCODE */)
2247 				seen_answer = 1;
2248 
2249 		for (ap = a; ap && reject == 0; ap = ap->next)
2250 			switch (ap->type) {
2251 			case ISAKMP_XAUTH_06_ATTRIB_TYPE:
2252 				if (ap->af != isakmp_attr_16 || ap->u.attr_16 != 0)
2253 					reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
2254 				break;
2255 			case ISAKMP_XAUTH_06_ATTRIB_USER_NAME:
2256 			case ISAKMP_XAUTH_06_ATTRIB_USER_PASSWORD:
2257 			case ISAKMP_XAUTH_06_ATTRIB_PASSCODE:
2258 			case ISAKMP_XAUTH_06_ATTRIB_DOMAIN:
2259 			case ISAKMP_XAUTH_06_ATTRIB_ANSWER:
2260 			case ISAKMP_XAUTH_06_ATTRIB_NEXT_PIN:
2261 			case ISAKMP_XAUTH_ATTRIB_CISCOEXT_VENDOR:
2262 				break;
2263 			case ISAKMP_XAUTH_06_ATTRIB_MESSAGE:
2264 				if (opt_debug || seen_answer || config[CONFIG_XAUTH_INTERACTIVE]) {
2265 					if (ap->af == isakmp_attr_16)
2266 						printf("%c%c\n", ap->u.attr_16 >> 8, ap->u.attr_16);
2267 					else
2268 						printf("%.*s%s", ap->u.lots.length, ap->u.lots.data,
2269 							((ap->u.lots.data
2270 									&& ap->u.lots.data[ap->u.
2271 										lots.length - 1] !=
2272 									'\n')
2273 								? "\n" : ""));
2274 				}
2275 				break;
2276 			default:
2277 				reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
2278 			}
2279 		if (reject != 0)
2280 			phase2_fatal(s, "xauth packet unsupported: %s(%d)", reject);
2281 
2282 		DEBUGTOP(2, printf("S5.5 do xauth authentication\n"));
2283 		inet_ntop(AF_INET, &s->dst, ntop_buf, sizeof(ntop_buf));
2284 
2285 		/* Collect data from the user.  */
2286 		reply_attr = NULL;
2287 		for (ap = a; ap && reject == 0; ap = ap->next)
2288 			switch (ap->type) {
2289 			case ISAKMP_XAUTH_06_ATTRIB_DOMAIN:
2290 				{
2291 					struct isakmp_attribute *na;
2292 					na = new_isakmp_attribute(ap->type, reply_attr);
2293 					reply_attr = na;
2294 					if (!config[CONFIG_DOMAIN])
2295 						error(1, 0,
2296 							"server requested domain, but none set (use \"Domain ...\" in config or --domain");
2297 					na->u.lots.length = strlen(config[CONFIG_DOMAIN]);
2298 					na->u.lots.data = xallocc(na->u.lots.length);
2299 					memcpy(na->u.lots.data, config[CONFIG_DOMAIN],
2300 						na->u.lots.length);
2301 					break;
2302 				}
2303 			case ISAKMP_XAUTH_06_ATTRIB_USER_NAME:
2304 				{
2305 					struct isakmp_attribute *na;
2306 					na = new_isakmp_attribute(ap->type, reply_attr);
2307 					reply_attr = na;
2308 					na->u.lots.length = strlen(config[CONFIG_XAUTH_USERNAME]);
2309 					na->u.lots.data = xallocc(na->u.lots.length);
2310 					memcpy(na->u.lots.data, config[CONFIG_XAUTH_USERNAME],
2311 						na->u.lots.length);
2312 					break;
2313 				}
2314 			case ISAKMP_XAUTH_06_ATTRIB_ANSWER:
2315 			case ISAKMP_XAUTH_06_ATTRIB_USER_PASSWORD:
2316 			case ISAKMP_XAUTH_06_ATTRIB_PASSCODE:
2317 			case ISAKMP_XAUTH_06_ATTRIB_NEXT_PIN:
2318 				if (passwd_used && config[CONFIG_NON_INTERACTIVE]) {
2319 					reject = ISAKMP_N_AUTHENTICATION_FAILED;
2320 					phase2_fatal(s, "noninteractive can't reuse password", reject);
2321 					error(2, 0, "authentication unsuccessful");
2322 				} else if (seen_answer || passwd_used || config[CONFIG_XAUTH_INTERACTIVE]) {
2323 					char *pass, *prompt = NULL;
2324 					struct isakmp_attribute *na;
2325 
2326 					asprintf(&prompt, "%s for VPN %s@%s: ",
2327 						(ap->type == ISAKMP_XAUTH_06_ATTRIB_ANSWER) ?
2328 						"Answer" :
2329 						(ap->type == ISAKMP_XAUTH_06_ATTRIB_USER_PASSWORD) ?
2330 						"Password" : "Passcode",
2331 						config[CONFIG_XAUTH_USERNAME], ntop_buf);
2332 					pass = getpass(prompt);
2333 					free(prompt);
2334 
2335 					na = new_isakmp_attribute(ap->type, reply_attr);
2336 					reply_attr = na;
2337 					na->u.lots.length = strlen(pass);
2338 					na->u.lots.data = xallocc(na->u.lots.length);
2339 					memcpy(na->u.lots.data, pass, na->u.lots.length);
2340 					memset(pass, 0, na->u.lots.length);
2341 				} else {
2342 					struct isakmp_attribute *na;
2343 					na = new_isakmp_attribute(ap->type, reply_attr);
2344 					reply_attr = na;
2345 					na->u.lots.length = strlen(config[CONFIG_XAUTH_PASSWORD]);
2346 					na->u.lots.data = xallocc(na->u.lots.length);
2347 					memcpy(na->u.lots.data, config[CONFIG_XAUTH_PASSWORD],
2348 						na->u.lots.length);
2349 					passwd_used = 1; /* Provide canned password at most once */
2350 				}
2351 				break;
2352 			default:
2353 				;
2354 			}
2355 
2356 		/* Send the response.  */
2357 		rp = new_isakmp_payload(ISAKMP_PAYLOAD_MODECFG_ATTR);
2358 		rp->u.modecfg.type = ISAKMP_MODECFG_CFG_REPLY;
2359 		rp->u.modecfg.id = r->payload->next->u.modecfg.id;
2360 		rp->u.modecfg.attributes = reply_attr;
2361 		sendrecv_phase2(s, rp, ISAKMP_EXCHANGE_MODECFG_TRANSACTION,
2362 			r->message_id, 0, 0, 0, 0, 0, 0, 0);
2363 
2364 	}
2365 
2366 	if ((opt_vendor == VENDOR_NETSCREEN) &&
2367 		(r->payload->next->u.modecfg.type == ISAKMP_MODECFG_CFG_SET)) {
2368 		struct isakmp_attribute *a = r->payload->next->u.modecfg.attributes;
2369 
2370 		DEBUGTOP(2, printf("S5.5.1 do netscreen modecfg extra\n"));
2371 
2372 		do_config_to_env(s, a);
2373 
2374 		for (; a; a = a->next)
2375 			if(a->af == isakmp_attr_lots)
2376 				a->u.lots.length = 0;
2377 
2378 		r->payload->next->u.modecfg.type = ISAKMP_MODECFG_CFG_ACK;
2379 		sendrecv_phase2(s, r->payload->next,
2380 			ISAKMP_EXCHANGE_MODECFG_TRANSACTION,
2381 			r->message_id, 0, 0, 0, 0, 0, 0, 0);
2382 
2383 		reject = do_phase2_notice_check(s, &r);
2384 		if (reject == -1) {
2385 			free_isakmp_packet(r);
2386 			return 1;
2387 		}
2388 	}
2389 
2390 	DEBUGTOP(2, printf("S5.6 process xauth response\n"));
2391 	{
2392 		/* The final SET should have just one attribute.  */
2393 		struct isakmp_attribute *a = r->payload->next->u.modecfg.attributes;
2394 		uint16_t set_result = 1;
2395 
2396 		if (a == NULL
2397 			|| a->type != ISAKMP_XAUTH_06_ATTRIB_STATUS
2398 			|| a->af != isakmp_attr_16 || a->next != NULL) {
2399 			reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
2400 			phase2_fatal(s, "xauth SET response rejected: %s(%d)", reject);
2401 		} else {
2402 			set_result = a->u.attr_16;
2403 		}
2404 
2405 		/* ACK the SET.  */
2406 		r->payload->next->u.modecfg.type = ISAKMP_MODECFG_CFG_ACK;
2407 		sendrecv_phase2(s, r->payload->next, ISAKMP_EXCHANGE_MODECFG_TRANSACTION,
2408 			r->message_id, 1, 0, 0, 0, 0, 0, 0);
2409 		r->payload->next = NULL;
2410 		free_isakmp_packet(r);
2411 
2412 		if (set_result == 0)
2413 			error(2, 0, "authentication unsuccessful");
2414 	}
2415 	DEBUGTOP(2, printf("S5.7 xauth done\n"));
2416 	return 0;
2417 }
2418 
do_phase2_config(struct sa_block * s)2419 static int do_phase2_config(struct sa_block *s)
2420 {
2421 	struct isakmp_payload *rp;
2422 	struct isakmp_attribute *a;
2423 	struct isakmp_packet *r;
2424 	struct utsname uts;
2425 	uint32_t msgid;
2426 	int reject;
2427 
2428 	uname(&uts);
2429 
2430 	gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
2431 	if (msgid == 0)
2432 		msgid = 1;
2433 
2434 	rp = new_isakmp_payload(ISAKMP_PAYLOAD_MODECFG_ATTR);
2435 	rp->u.modecfg.type = ISAKMP_MODECFG_CFG_REQUEST;
2436 	rp->u.modecfg.id = 20;
2437 	a = NULL;
2438 
2439 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_APPLICATION_VERSION, a);
2440 	a->u.lots.length = strlen(config[CONFIG_VERSION]);
2441 	a->u.lots.data = xallocc(a->u.lots.length);
2442 	memcpy(a->u.lots.data, config[CONFIG_VERSION], a->u.lots.length);
2443 
2444 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_DDNS_HOSTNAME, a);
2445 	a->u.lots.length = strlen(uts.nodename);
2446 	a->u.lots.data = xallocc(a->u.lots.length);
2447 	memcpy(a->u.lots.data, uts.nodename, a->u.lots.length);
2448 
2449 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_SPLIT_INC, a);
2450 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_SAVE_PW, a);
2451 
2452 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_BANNER, a);
2453 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_DO_PFS, a);
2454 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_FW_TYPE, a);
2455 	a->u.lots.length = sizeof(FW_UNKNOWN_TYPEINFO);
2456 	a->u.lots.data = xallocc(a->u.lots.length);
2457 	memcpy(a->u.lots.data, FW_UNKNOWN_TYPEINFO, a->u.lots.length);
2458 	if (opt_natt_mode == NATT_CISCO_UDP)
2459 		a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_UDP_ENCAP_PORT, a);
2460 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_CISCO_DEF_DOMAIN, a);
2461 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NBNS, a);
2462 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_DNS, a);
2463 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_NETMASK, a);
2464 	a = new_isakmp_attribute(ISAKMP_MODECFG_ATTRIB_INTERNAL_IP4_ADDRESS, a);
2465 
2466 	rp->u.modecfg.attributes = a;
2467 	DEBUGTOP(2, printf("S6.1 phase2_config send modecfg\n"));
2468 	sendrecv_phase2(s, rp, ISAKMP_EXCHANGE_MODECFG_TRANSACTION, msgid, 0, 0, 0, 0, 0, 0, 0);
2469 
2470 	DEBUGTOP(2, printf("S6.2 phase2_config receive modecfg\n"));
2471 	/* recv and check for notices */
2472 	reject = do_phase2_notice_check(s, &r);
2473 	if (reject == -1) {
2474 		if (r) free_isakmp_packet(r);
2475 		return 1;
2476 	}
2477 
2478 	/* Check the transaction type & message ID are OK.  */
2479 	if (reject == 0 && r->message_id != msgid)
2480 		reject = ISAKMP_N_INVALID_MESSAGE_ID;
2481 	if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_MODECFG_TRANSACTION)
2482 		reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
2483 
2484 	/* After the hash, expect an attribute block.  */
2485 	if (reject == 0
2486 		&& (r->payload->next == NULL
2487 			|| r->payload->next->next != NULL
2488 			|| r->payload->next->type != ISAKMP_PAYLOAD_MODECFG_ATTR
2489 #if 0
2490 			|| r->payload->next->u.modecfg.id != 20
2491 #endif
2492 			|| r->payload->next->u.modecfg.type != ISAKMP_MODECFG_CFG_REPLY))
2493 		reject = ISAKMP_N_PAYLOAD_MALFORMED;
2494 
2495 	if (reject != 0)
2496 		phase2_fatal(s, "configuration response rejected: %s(%d)", reject);
2497 
2498 	if (reject == 0)
2499 		reject = do_config_to_env(s, r->payload->next->u.modecfg.attributes);
2500 
2501 	if (reject != 0)
2502 		phase2_fatal(s, "configuration response rejected: %s(%d)", reject);
2503 
2504 	DEBUG(1, printf("got address %s\n", getenv("INTERNAL_IP4_ADDRESS")));
2505 	free_isakmp_packet(r);
2506 	return 0;
2507 }
2508 
make_transform_ipsec(struct sa_block * s,int dh_group,int hash,int keylen)2509 static struct isakmp_attribute *make_transform_ipsec(struct sa_block *s, int dh_group, int hash, int keylen)
2510 {
2511 	struct isakmp_attribute *a = NULL;
2512 
2513 	a = new_isakmp_attribute(ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION, a);
2514 	a->af = isakmp_attr_lots;
2515 	a->u.lots.length = 4;
2516 	a->u.lots.data = xallocc(a->u.lots.length);
2517 	*((uint32_t *) a->u.lots.data) = htonl(2147483);
2518 	a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE, IPSEC_LIFE_SECONDS, a);
2519 
2520 	if (dh_group)
2521 		a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_GROUP_DESC, dh_group, a);
2522 	a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_AUTH_ALG, hash, a);
2523 	a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_ENCAP_MODE, s->ipsec.encap_mode, a);
2524 	if (keylen != 0)
2525 		a = new_isakmp_attribute_16(ISAKMP_IPSEC_ATTRIB_KEY_LENGTH, keylen, a);
2526 
2527 	return a;
2528 }
2529 
make_our_sa_ipsec(struct sa_block * s)2530 static struct isakmp_payload *make_our_sa_ipsec(struct sa_block *s)
2531 {
2532 	struct isakmp_payload *r = new_isakmp_payload(ISAKMP_PAYLOAD_SA);
2533 	struct isakmp_payload *p = NULL, *pn;
2534 	struct isakmp_attribute *a;
2535 	int dh_grp = get_dh_group_ipsec(s->ipsec.do_pfs)->ipsec_sa_id;
2536 	unsigned int crypt, hash, keylen;
2537 	int i;
2538 
2539 	r = new_isakmp_payload(ISAKMP_PAYLOAD_SA);
2540 	r->u.sa.doi = ISAKMP_DOI_IPSEC;
2541 	r->u.sa.situation = ISAKMP_IPSEC_SIT_IDENTITY_ONLY;
2542 	r->u.sa.proposals = new_isakmp_payload(ISAKMP_PAYLOAD_P);
2543 	r->u.sa.proposals->u.p.spi_size = 4;
2544 	r->u.sa.proposals->u.p.spi = xallocc(4);
2545 	/* The sadb_sa_spi field is already in network order.  */
2546 	memcpy(r->u.sa.proposals->u.p.spi, &s->ipsec.rx.spi, 4);
2547 	r->u.sa.proposals->u.p.prot_id = ISAKMP_IPSEC_PROTO_IPSEC_ESP;
2548 	for (crypt = 0; supp_crypt[crypt].name != NULL; crypt++) {
2549 		keylen = supp_crypt[crypt].keylen;
2550 		for (hash = 0; supp_hash[hash].name != NULL; hash++) {
2551 			pn = p;
2552 			p = new_isakmp_payload(ISAKMP_PAYLOAD_P);
2553 			p->u.p.spi_size = 4;
2554 			p->u.p.spi = xallocc(4);
2555 			/* The sadb_sa_spi field is already in network order.  */
2556 			memcpy(p->u.p.spi, &s->ipsec.rx.spi, 4);
2557 			p->u.p.prot_id = ISAKMP_IPSEC_PROTO_IPSEC_ESP;
2558 			p->u.p.transforms = new_isakmp_payload(ISAKMP_PAYLOAD_T);
2559 			p->u.p.transforms->u.t.id = supp_crypt[crypt].ipsec_sa_id;
2560 			a = make_transform_ipsec(s, dh_grp, supp_hash[hash].ipsec_sa_id, keylen);
2561 			p->u.p.transforms->u.t.attributes = a;
2562 			p->next = pn;
2563 		}
2564 	}
2565 	for (i = 0, pn = p; pn; pn = pn->next)
2566 		pn->u.p.number = i++;
2567 	r->u.sa.proposals = p;
2568 	return r;
2569 }
2570 
do_phase2_qm(struct sa_block * s)2571 static void do_phase2_qm(struct sa_block *s)
2572 {
2573 	struct isakmp_payload *rp, *us, *ke = NULL, *them, *nonce_r = NULL;
2574 	struct isakmp_packet *r;
2575 	struct group *dh_grp = NULL;
2576 	uint32_t msgid;
2577 	int reject;
2578 	uint8_t *p_flat = NULL, *realiv = NULL, realiv_msgid[4];
2579 	size_t p_size = 0;
2580 	uint8_t nonce_i[20], *dh_public = NULL;
2581 	int i;
2582 
2583 	DEBUGTOP(2, printf("S7.1 QM_packet1\n"));
2584 	/* Set up the Diffie-Hellman stuff.  */
2585 	if (get_dh_group_ipsec(s->ipsec.do_pfs)->my_id) {
2586 		dh_grp = group_get(get_dh_group_ipsec(s->ipsec.do_pfs)->my_id);
2587 		DEBUG(3, printf("len = %d\n", dh_getlen(dh_grp)));
2588 		dh_public = xallocc(dh_getlen(dh_grp));
2589 		dh_create_exchange(dh_grp, dh_public);
2590 		hex_dump("dh_public", dh_public, dh_getlen(dh_grp), NULL);
2591 	}
2592 
2593 	gcry_create_nonce((uint8_t *) & s->ipsec.rx.spi, sizeof(s->ipsec.rx.spi));
2594 	rp = make_our_sa_ipsec(s); /* FIXME: LEAK: allocated memory never freed */
2595 	gcry_create_nonce((uint8_t *) nonce_i, sizeof(nonce_i));
2596 	rp->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_NONCE, nonce_i, sizeof(nonce_i));
2597 
2598 	us = new_isakmp_payload(ISAKMP_PAYLOAD_ID);
2599 	us->u.id.type = ISAKMP_IPSEC_ID_IPV4_ADDR;
2600 	us->u.id.length = 4;
2601 	us->u.id.data = xallocc(4);
2602 	memcpy(us->u.id.data, s->our_address, sizeof(struct in_addr));
2603 	them = new_isakmp_payload(ISAKMP_PAYLOAD_ID);
2604 	them->u.id.type = ISAKMP_IPSEC_ID_IPV4_ADDR_SUBNET;
2605 	them->u.id.length = 8;
2606 	them->u.id.data = xallocc(8);
2607 	init_netaddr((struct in_addr *)them->u.id.data,
2608 		     config[CONFIG_IPSEC_TARGET_NETWORK]);
2609 	us->next = them;
2610 	s->ipsec.life.start = time(NULL);
2611 
2612 	if (!dh_grp) {
2613 		rp->next->next = us;
2614 	} else {
2615 		rp->next->next = new_isakmp_data_payload(ISAKMP_PAYLOAD_KE,
2616 			dh_public, dh_getlen(dh_grp));
2617 		rp->next->next->next = us;
2618 	}
2619 
2620 	gcry_create_nonce((uint8_t *) & msgid, sizeof(msgid));
2621 	if (msgid == 0)
2622 		msgid = 1;
2623 
2624 	for (i = 0; i < 4; i++) {
2625 		DEBUGTOP(2, printf("S7.2 QM_packet2 send_receive\n"));
2626 		sendrecv_phase2(s, rp, ISAKMP_EXCHANGE_IKE_QUICK,
2627 			msgid, 0, &p_flat, &p_size, 0, 0, 0, 0);
2628 
2629 		if (realiv == NULL) {
2630 			realiv = xallocc(s->ike.ivlen);
2631 			memcpy(realiv, s->ike.current_iv, s->ike.ivlen);
2632 			memcpy(realiv_msgid, s->ike.current_iv_msgid, 4);
2633 		}
2634 
2635 		DEBUGTOP(2, printf("S7.3 QM_packet2 validate type\n"));
2636 		reject = unpack_verify_phase2(s, r_packet, r_length, &r, nonce_i, sizeof(nonce_i)); /* FIXME: LEAK */
2637 
2638 		if (((reject == 0) || (reject == ISAKMP_N_AUTHENTICATION_FAILED))
2639 			&& r->exchange_type == ISAKMP_EXCHANGE_INFORMATIONAL) {
2640 			DEBUGTOP(2, printf("S7.4 process and skip lifetime notice\n"));
2641 			/* handle notify responder-lifetime */
2642 			/* (broken hash => ignore AUTHENTICATION_FAILED) */
2643 			if (reject == 0 && r->payload->next->type != ISAKMP_PAYLOAD_N)
2644 				reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
2645 
2646 			if (reject == 0
2647 				&& r->payload->next->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
2648 				if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
2649 					lifetime_ike_process(s, r->payload->next->u.n.attributes);
2650 				else if (r->payload->next->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
2651 					lifetime_ipsec_process(s, r->payload->next->u.n.attributes);
2652 				else
2653 					DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
2654 				memcpy(s->ike.current_iv, realiv, s->ike.ivlen);
2655 				memcpy(s->ike.current_iv_msgid, realiv_msgid, 4);
2656 				continue;
2657 			}
2658 		}
2659 
2660 		/* Check the transaction type & message ID are OK.  */
2661 		if (reject == 0 && r->message_id != msgid)
2662 			reject = ISAKMP_N_INVALID_MESSAGE_ID;
2663 
2664 		if (reject == 0 && r->exchange_type != ISAKMP_EXCHANGE_IKE_QUICK)
2665 			reject = ISAKMP_N_INVALID_EXCHANGE_TYPE;
2666 
2667 		/* The SA payload must be second.  */
2668 		if (reject == 0 && r->payload->next->type != ISAKMP_PAYLOAD_SA)
2669 			reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
2670 
2671 		free(p_flat);
2672 		free(realiv);
2673 
2674 		break;
2675 	}
2676 
2677 	DEBUGTOP(2, printf("S7.5 QM_packet2 check reject offer\n"));
2678 	if (reject != 0)
2679 		phase2_fatal(s, "quick mode response rejected: %s(%d)\n"
2680 			"this means the concentrator did not like what we had to offer.\n"
2681 			"Possible reasons are:\n"
2682 			"  * concentrator configured to require a firewall\n"
2683 			"     this locks out even Cisco clients on any platform expect windows\n"
2684 			"     which is an obvious security improvment. There is no workaround (yet).\n"
2685 			"  * concentrator configured to require IP compression\n"
2686 			"     this is not yet supported by vpnc.\n"
2687 			"     Note: the Cisco Concentrator Documentation recommends against using\n"
2688 			"     compression, expect on low-bandwith (read: ISDN) links, because it\n"
2689 			"     uses much CPU-resources on the concentrator\n",
2690 			reject);
2691 
2692 	DEBUGTOP(2, printf("S7.6 QM_packet2 check and process proposal\n"));
2693 	for (rp = r->payload->next; rp && reject == 0; rp = rp->next)
2694 		switch (rp->type) {
2695 		case ISAKMP_PAYLOAD_SA:
2696 			if (reject == 0 && rp->u.sa.doi != ISAKMP_DOI_IPSEC)
2697 				reject = ISAKMP_N_DOI_NOT_SUPPORTED;
2698 			if (reject == 0 && rp->u.sa.situation != ISAKMP_IPSEC_SIT_IDENTITY_ONLY)
2699 				reject = ISAKMP_N_SITUATION_NOT_SUPPORTED;
2700 			if (reject == 0 &&
2701 				(rp->u.sa.proposals == NULL || rp->u.sa.proposals->next != NULL))
2702 				reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2703 			if (reject == 0 &&
2704 				rp->u.sa.proposals->u.p.prot_id != ISAKMP_IPSEC_PROTO_IPSEC_ESP)
2705 				reject = ISAKMP_N_INVALID_PROTOCOL_ID;
2706 			if (reject == 0 && rp->u.sa.proposals->u.p.spi_size != 4)
2707 				reject = ISAKMP_N_INVALID_SPI;
2708 			if (reject == 0 &&
2709 				(rp->u.sa.proposals->u.p.transforms == NULL
2710 					|| rp->u.sa.proposals->u.p.transforms->next != NULL))
2711 				reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2712 			if (reject == 0) {
2713 				struct isakmp_attribute *a
2714 					= rp->u.sa.proposals->u.p.transforms->u.t.attributes;
2715 				int seen_enc = rp->u.sa.proposals->u.p.transforms->u.t.id;
2716 				int seen_auth = 0, seen_encap = 0, seen_group = 0, seen_keylen = 0;
2717 
2718 				memcpy(&s->ipsec.tx.spi, rp->u.sa.proposals->u.p.spi, 4);
2719 
2720 				for (; a && reject == 0; a = a->next)
2721 					switch (a->type) {
2722 					case ISAKMP_IPSEC_ATTRIB_AUTH_ALG:
2723 						if (a->af == isakmp_attr_16)
2724 							seen_auth = a->u.attr_16;
2725 						else
2726 							reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2727 						break;
2728 					case ISAKMP_IPSEC_ATTRIB_ENCAP_MODE:
2729 						if (a->af == isakmp_attr_16 &&
2730 							a->u.attr_16 == s->ipsec.encap_mode)
2731 							seen_encap = 1;
2732 						else
2733 							reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2734 						break;
2735 					case ISAKMP_IPSEC_ATTRIB_GROUP_DESC:
2736 						if (dh_grp &&
2737 							a->af == isakmp_attr_16 &&
2738 							a->u.attr_16 ==
2739 							get_dh_group_ipsec(s->ipsec.do_pfs)->ipsec_sa_id)
2740 							seen_group = 1;
2741 						else
2742 							reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2743 						break;
2744 					case ISAKMP_IPSEC_ATTRIB_KEY_LENGTH:
2745 						if (a->af == isakmp_attr_16)
2746 							seen_keylen = a->u.attr_16;
2747 						else
2748 							reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2749 						break;
2750 					case ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE:
2751 						/* lifetime duration MUST follow lifetype attribute */
2752 						if (a->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION) {
2753 							lifetime_ipsec_process(s, a);
2754 						} else
2755 							reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2756 						break;
2757 					case ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION:
2758 						/* already processed above in ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE: */
2759 						break;
2760 					default:
2761 						reject = ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
2762 						break;
2763 					}
2764 				if (reject == 0 && (!seen_auth || !seen_encap ||
2765 						(dh_grp && !seen_group)))
2766 					reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2767 
2768 				if (reject == 0
2769 					&& get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA, seen_auth,
2770 						NULL, 0) == NULL)
2771 					reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2772 				if (reject == 0
2773 					&& get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA, seen_enc,
2774 						NULL, seen_keylen) == NULL)
2775 					reject = ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2776 
2777 				if (reject == 0) {
2778 					s->ipsec.cry_algo =
2779 						get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA,
2780 						seen_enc, NULL, seen_keylen)->my_id;
2781 					s->ipsec.md_algo =
2782 						get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA,
2783 						seen_auth, NULL, 0)->my_id;
2784 					if (s->ipsec.cry_algo) {
2785 						gcry_cipher_algo_info(s->ipsec.cry_algo, GCRYCTL_GET_KEYLEN, NULL, &(s->ipsec.key_len));
2786 						gcry_cipher_algo_info(s->ipsec.cry_algo, GCRYCTL_GET_BLKLEN, NULL, &(s->ipsec.blk_len));
2787 						s->ipsec.iv_len = s->ipsec.blk_len;
2788 					} else {
2789 						s->ipsec.key_len = 0;
2790 						s->ipsec.iv_len = 0;
2791 						s->ipsec.blk_len = 8; /* seems to be this without encryption... */
2792 					}
2793 					s->ipsec.md_len = gcry_md_get_algo_dlen(s->ipsec.md_algo);
2794 					DEBUG(1, printf("IPSEC SA selected %s-%s\n",
2795 							get_algo(SUPP_ALGO_CRYPT,
2796 								SUPP_ALGO_IPSEC_SA, seen_enc, NULL,
2797 								seen_keylen)->name,
2798 							get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA,
2799 								seen_auth, NULL, 0)->name));
2800 					if (s->ipsec.cry_algo == GCRY_CIPHER_DES && !opt_1des) {
2801 						error(1, 0, "peer selected (single) DES as \"encrytion\" method.\n"
2802 							"This algorithm is considered to weak today\n"
2803 							"If your vpn concentrator admin still insists on using DES\n"
2804 							"use the \"--enable-1des\" option.\n");
2805 					} else if (s->ipsec.cry_algo == GCRY_CIPHER_NONE && !opt_no_encryption) {
2806 						error(1, 0, "peer selected NULL as \"encrytion\" method.\n"
2807 							"This is _no_ encryption at all.\n"
2808 							"Your traffic is still protected against modification with %s\n"
2809 							"If your vpn concentrator admin still insists on not using encryption\n"
2810 							"use the \"--enable-no-encryption\" option.\n",
2811 							get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA, seen_auth, NULL, 0)->name);
2812 					}
2813 				}
2814 			}
2815 			break;
2816 
2817 		case ISAKMP_PAYLOAD_N:
2818 			if (reject == 0 && rp->u.n.type == ISAKMP_N_IPSEC_RESPONDER_LIFETIME) {
2819 				if (rp->u.n.protocol == ISAKMP_IPSEC_PROTO_ISAKMP)
2820 					lifetime_ike_process(s, rp->u.n.attributes);
2821 				else if (rp->u.n.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP)
2822 					lifetime_ipsec_process(s, rp->u.n.attributes);
2823 				else
2824 					DEBUG(2, printf("got unknown lifetime notice, ignoring..\n"));
2825 			}
2826 			break;
2827 		case ISAKMP_PAYLOAD_ID:
2828 			/* FIXME: Parse payload ID and add route-env in case of ipv4_prefix */
2829 			break;
2830 		case ISAKMP_PAYLOAD_KE:
2831 			ke = rp;
2832 			break;
2833 		case ISAKMP_PAYLOAD_NONCE:
2834 			nonce_r = rp;
2835 			break;
2836 
2837 		default:
2838 			reject = ISAKMP_N_INVALID_PAYLOAD_TYPE;
2839 			break;
2840 		}
2841 
2842 	if (reject == 0 && nonce_r == NULL)
2843 		reject = ISAKMP_N_INVALID_HASH_INFORMATION;
2844 	if (reject == 0 && dh_grp && (ke == NULL || ke->u.ke.length != dh_getlen(dh_grp)))
2845 		reject = ISAKMP_N_INVALID_KEY_INFORMATION;
2846 	if (reject != 0)
2847 		phase2_fatal(s, "quick mode response rejected [2]: %s(%d)", reject);
2848 
2849 	/* send final packet */
2850 	sendrecv_phase2(s, NULL, ISAKMP_EXCHANGE_IKE_QUICK,
2851 		msgid, 1, 0, 0, nonce_i, sizeof(nonce_i),
2852 		nonce_r->u.nonce.data, nonce_r->u.nonce.length);
2853 
2854 	DEBUGTOP(2, printf("S7.7 QM_packet3 sent\n"));
2855 
2856 	DEBUGTOP(2, printf("S7.8 setup ipsec tunnel\n"));
2857 	{
2858 		unsigned char *dh_shared_secret = NULL;
2859 
2860 		if (dh_grp) {
2861 			/* Determine the shared secret.  */
2862 			dh_shared_secret = xallocc(dh_getlen(dh_grp));
2863 			dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
2864 			hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
2865 		}
2866 
2867 		s->ipsec.rx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.rx.spi,
2868 			dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
2869 			nonce_i, sizeof(nonce_i), nonce_r->u.nonce.data, nonce_r->u.nonce.length);
2870 
2871 		s->ipsec.tx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.tx.spi,
2872 			dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
2873 			nonce_i, sizeof(nonce_i), nonce_r->u.nonce.data, nonce_r->u.nonce.length);
2874 
2875 		if (dh_grp)
2876 			group_free(dh_grp);
2877 		free(dh_shared_secret);
2878 		free_isakmp_packet(r);
2879 
2880 		if (s->esp_fd == 0) {
2881 			if ((opt_natt_mode == NATT_CISCO_UDP) && s->ipsec.peer_udpencap_port) {
2882 				s->esp_fd = make_socket(s, opt_udpencapport, s->ipsec.peer_udpencap_port);
2883 				s->ipsec.encap_mode = IPSEC_ENCAP_UDP_TUNNEL;
2884 				s->ipsec.natt_active_mode = NATT_ACTIVE_CISCO_UDP;
2885 			} else if (s->ipsec.encap_mode != IPSEC_ENCAP_TUNNEL) {
2886 				s->esp_fd = s->ike_fd;
2887 			} else {
2888 #ifdef IP_HDRINCL
2889 				int hincl = 1;
2890 #endif
2891 
2892 				s->esp_fd = socket(PF_INET, SOCK_RAW, IPPROTO_ESP);
2893 				if (s->esp_fd == -1) {
2894 					close_tunnel(s);
2895 					error(1, errno, "Couldn't open socket of ESP. Maybe something registered ESP already.\nPlease try '--natt-mode force-natt' or disable whatever is using ESP.\nsocket(PF_INET, SOCK_RAW, IPPROTO_ESP)");
2896 				}
2897 #ifdef FD_CLOEXEC
2898 				/* do not pass socket to vpnc-script, etc. */
2899 				fcntl(s->esp_fd, F_SETFD, FD_CLOEXEC);
2900 #endif
2901 #ifdef IP_HDRINCL
2902 				if (setsockopt(s->esp_fd, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl)) == -1) {
2903 					close_tunnel(s);
2904 					error(1, errno, "setsockopt(esp_fd, IPPROTO_IP, IP_HDRINCL, 1)");
2905 				}
2906 #endif
2907 			}
2908 		}
2909 
2910 		s->ipsec.rx.seq_id = s->ipsec.tx.seq_id = 1;
2911 	}
2912 	free(dh_public);
2913 }
2914 
send_delete_ipsec(struct sa_block * s)2915 static void send_delete_ipsec(struct sa_block *s)
2916 {
2917 	/* 2007-08-31 JKU/ZID: Sonicwall doesn't like the chained
2918 	 * request but wants them split. Cisco does fine with it. */
2919 	DEBUGTOP(2, printf("S7.10 send ipsec termination message\n"));
2920 	{
2921 		struct isakmp_payload *d_ipsec;
2922 		uint8_t del_msgid;
2923 
2924 		gcry_create_nonce((uint8_t *) & del_msgid, sizeof(del_msgid));
2925 		d_ipsec = new_isakmp_payload(ISAKMP_PAYLOAD_D);
2926 		d_ipsec->u.d.doi = ISAKMP_DOI_IPSEC;
2927 		d_ipsec->u.d.protocol = ISAKMP_IPSEC_PROTO_IPSEC_ESP;
2928 		d_ipsec->u.d.spi_length = 4;
2929 		d_ipsec->u.d.num_spi = 2;
2930 		d_ipsec->u.d.spi = xallocc(2 * sizeof(uint8_t *));
2931 		d_ipsec->u.d.spi[0] = xallocc(d_ipsec->u.d.spi_length);
2932 		memcpy(d_ipsec->u.d.spi[0], &s->ipsec.rx.spi, 4);
2933 		d_ipsec->u.d.spi[1] = xallocc(d_ipsec->u.d.spi_length);
2934 		memcpy(d_ipsec->u.d.spi[1], &s->ipsec.tx.spi, 4);
2935 		sendrecv_phase2(s, d_ipsec, ISAKMP_EXCHANGE_INFORMATIONAL,
2936 			del_msgid, 1, NULL, NULL,
2937 			NULL, 0, NULL, 0);
2938 	}
2939 }
2940 
send_delete_isakmp(struct sa_block * s)2941 static void send_delete_isakmp(struct sa_block *s)
2942 {
2943 	DEBUGTOP(2, printf("S7.11 send isakmp termination message\n"));
2944 	{
2945 		struct isakmp_payload *d_isakmp;
2946 		uint8_t del_msgid;
2947 
2948 		gcry_create_nonce((uint8_t *) & del_msgid, sizeof(del_msgid));
2949 		d_isakmp = new_isakmp_payload(ISAKMP_PAYLOAD_D);
2950 		d_isakmp->u.d.doi = ISAKMP_DOI_IPSEC;
2951 		d_isakmp->u.d.protocol = ISAKMP_IPSEC_PROTO_ISAKMP;
2952 		d_isakmp->u.d.spi_length = 2 * ISAKMP_COOKIE_LENGTH;
2953 		d_isakmp->u.d.num_spi = 1;
2954 		d_isakmp->u.d.spi = xallocc(1 * sizeof(uint8_t *));
2955 		d_isakmp->u.d.spi[0] = xallocc(2 * ISAKMP_COOKIE_LENGTH);
2956 		memcpy(d_isakmp->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 0, s->ike.i_cookie,
2957 			ISAKMP_COOKIE_LENGTH);
2958 		memcpy(d_isakmp->u.d.spi[0] + ISAKMP_COOKIE_LENGTH * 1, s->ike.r_cookie,
2959 			ISAKMP_COOKIE_LENGTH);
2960 		sendrecv_phase2(s, d_isakmp, ISAKMP_EXCHANGE_INFORMATIONAL,
2961 			del_msgid, 1, NULL, NULL,
2962 			NULL, 0, NULL, 0);
2963 	}
2964 }
2965 
do_rekey(struct sa_block * s,struct isakmp_packet * r)2966 static int do_rekey(struct sa_block *s, struct isakmp_packet *r)
2967 {
2968 	struct isakmp_payload *rp, *ke = NULL, *nonce_i = NULL;
2969 	struct isakmp_attribute *a;
2970 	int seen_enc;
2971 	int seen_auth = 0, seen_encap = 0, seen_group = 0, seen_keylen = 0;
2972 	int nonce_i_copy_len;
2973 	struct group *dh_grp = NULL;
2974 	uint8_t nonce_r[20], *dh_public = NULL, *nonce_i_copy = NULL;
2975 	unsigned char *dh_shared_secret = NULL;
2976 
2977 	if (get_dh_group_ipsec(s->ipsec.do_pfs)->my_id) {
2978 		dh_grp = group_get(get_dh_group_ipsec(s->ipsec.do_pfs)->my_id);
2979 		DEBUG(3, printf("len = %d\n", dh_getlen(dh_grp)));
2980 		dh_public = xallocc(dh_getlen(dh_grp));
2981 		dh_create_exchange(dh_grp, dh_public);
2982 		hex_dump("dh_public", dh_public, dh_getlen(dh_grp), NULL);
2983 	}
2984 
2985 	rp = r->payload->next;
2986 	/* rp->type == ISAKMP_PAYLOAD_SA, verified by caller */
2987 
2988 	if (rp->u.sa.doi != ISAKMP_DOI_IPSEC)
2989 		return ISAKMP_N_DOI_NOT_SUPPORTED;
2990 	if (rp->u.sa.situation != ISAKMP_IPSEC_SIT_IDENTITY_ONLY)
2991 		return ISAKMP_N_SITUATION_NOT_SUPPORTED;
2992 	if (rp->u.sa.proposals == NULL)
2993 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
2994 	if (rp->u.sa.proposals->u.p.prot_id != ISAKMP_IPSEC_PROTO_IPSEC_ESP)
2995 		return ISAKMP_N_INVALID_PROTOCOL_ID;
2996 	if (rp->u.sa.proposals->u.p.spi_size != 4)
2997 		return ISAKMP_N_INVALID_SPI;
2998 	if (rp->u.sa.proposals->u.p.transforms == NULL || rp->u.sa.proposals->u.p.transforms->next != NULL)
2999 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3000 
3001 	seen_enc = rp->u.sa.proposals->u.p.transforms->u.t.id;
3002 
3003 	memcpy(&s->ipsec.tx.spi, rp->u.sa.proposals->u.p.spi, 4);
3004 
3005 	for (a = rp->u.sa.proposals->u.p.transforms->u.t.attributes; a; a = a->next)
3006 		switch (a->type) {
3007 		case ISAKMP_IPSEC_ATTRIB_AUTH_ALG:
3008 			if (a->af == isakmp_attr_16)
3009 				seen_auth = a->u.attr_16;
3010 			else
3011 				return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3012 			break;
3013 		case ISAKMP_IPSEC_ATTRIB_ENCAP_MODE:
3014 			if (a->af == isakmp_attr_16 &&
3015 				a->u.attr_16 == (
3016 					(s->ipsec.natt_active_mode != NATT_ACTIVE_CISCO_UDP) ?
3017 					s->ipsec.encap_mode :
3018 					IPSEC_ENCAP_TUNNEL /* cisco-udp claims to use encap tunnel... */
3019 				))
3020 				seen_encap = 1;
3021 			else
3022 				return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3023 			break;
3024 		case ISAKMP_IPSEC_ATTRIB_GROUP_DESC:
3025 			if (dh_grp && a->af == isakmp_attr_16 &&
3026 				a->u.attr_16 == get_dh_group_ipsec(s->ipsec.do_pfs)->ipsec_sa_id)
3027 				seen_group = 1;
3028 			else
3029 				return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3030 			break;
3031 		case ISAKMP_IPSEC_ATTRIB_KEY_LENGTH:
3032 			if (a->af == isakmp_attr_16)
3033 				seen_keylen = a->u.attr_16;
3034 			else
3035 				return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3036 			break;
3037 		case ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE:
3038 			/* lifetime duration MUST follow lifetype attribute */
3039 			if (a->next->type == ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION) {
3040 				lifetime_ipsec_process(s, a);
3041 			} else
3042 				return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3043 			break;
3044 		case ISAKMP_IPSEC_ATTRIB_SA_LIFE_DURATION:
3045 			/* already processed above in ISAKMP_IPSEC_ATTRIB_SA_LIFE_TYPE: */
3046 			break;
3047 		default:
3048 			return ISAKMP_N_ATTRIBUTES_NOT_SUPPORTED;
3049 			break;
3050 		}
3051 	if (!seen_auth || !seen_encap || (dh_grp && !seen_group))
3052 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3053 
3054 	/* FIXME: Current code has a limitation that will cause problems if
3055 	 * different algorithms are negotiated during re-keying
3056 	 */
3057 	if ((get_algo(SUPP_ALGO_HASH, SUPP_ALGO_IPSEC_SA, seen_auth, NULL, 0) == NULL) ||
3058 	    (get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA, seen_enc, NULL, seen_keylen) == NULL)) {
3059 		printf("\nFIXME: vpnc doesn't support change of algorightms during rekeying\n");
3060 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3061 	}
3062 
3063 	/* we don't want to change ciphers during rekeying */
3064 	if (s->ipsec.cry_algo != get_algo(SUPP_ALGO_CRYPT, SUPP_ALGO_IPSEC_SA, seen_enc,  NULL, seen_keylen)->my_id)
3065 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3066 	if (s->ipsec.md_algo  != get_algo(SUPP_ALGO_HASH,  SUPP_ALGO_IPSEC_SA, seen_auth, NULL, 0)->my_id)
3067 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3068 
3069 	for (rp = rp->next; rp; rp = rp->next)
3070 		switch (rp->type) {
3071 		case ISAKMP_PAYLOAD_ID:
3072 			/* FIXME: Parse payload ID and add route-env in case of ipv4_prefix */
3073 			break;
3074 		case ISAKMP_PAYLOAD_KE:
3075 			ke = rp;
3076 			break;
3077 		case ISAKMP_PAYLOAD_NONCE:
3078 			nonce_i = rp;
3079 			break;
3080 		default:
3081 			return ISAKMP_N_INVALID_PAYLOAD_TYPE;
3082 			break;
3083 		}
3084 
3085 	if ((dh_grp && ke == NULL) || nonce_i == NULL)
3086 		return ISAKMP_N_BAD_PROPOSAL_SYNTAX;
3087 
3088 	DEBUG(3, printf("everything fine so far...\n"));
3089 	gcry_create_nonce((uint8_t *) nonce_r, sizeof(nonce_r));
3090 	gcry_create_nonce((uint8_t *) & s->ipsec.rx.spi, sizeof(s->ipsec.rx.spi));
3091 
3092 	if (dh_grp) {
3093 		/* Determine the shared secret.  */
3094 		dh_shared_secret = xallocc(dh_getlen(dh_grp));
3095 		dh_create_shared(dh_grp, dh_shared_secret, ke->u.ke.data);
3096 		hex_dump("dh_shared_secret", dh_shared_secret, dh_getlen(dh_grp), NULL);
3097 	}
3098 
3099 	free(s->ipsec.rx.key);
3100 	free(s->ipsec.tx.key);
3101 
3102 	s->ipsec.rx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.rx.spi,
3103 		dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
3104 		nonce_i->u.nonce.data, nonce_i->u.nonce.length, nonce_r, sizeof(nonce_r));
3105 
3106 	s->ipsec.tx.key = gen_keymat(s, ISAKMP_IPSEC_PROTO_IPSEC_ESP, s->ipsec.tx.spi,
3107 		dh_shared_secret, dh_grp ? dh_getlen(dh_grp) : 0,
3108 		nonce_i->u.nonce.data, nonce_i->u.nonce.length, nonce_r, sizeof(nonce_r));
3109 
3110 	s->ipsec.rx.key_cry = s->ipsec.rx.key;
3111 	s->ipsec.rx.key_md  = s->ipsec.rx.key + s->ipsec.key_len;
3112 	s->ipsec.tx.key_cry = s->ipsec.tx.key;
3113 	s->ipsec.tx.key_md  = s->ipsec.tx.key + s->ipsec.key_len;
3114 
3115 	nonce_i_copy_len = nonce_i->u.nonce.length;
3116 	nonce_i_copy = xallocc(nonce_i_copy_len);
3117 	memcpy(nonce_i_copy, nonce_i->u.nonce.data, nonce_i_copy_len);
3118 
3119 	s->ipsec.rx.seq_id = s->ipsec.tx.seq_id = 1;
3120 	s->ipsec.life.start = time(NULL);
3121 	s->ipsec.life.tx = 0;
3122 	s->ipsec.life.rx = 0;
3123 
3124 	if (s->ipsec.cry_algo) {
3125 		gcry_cipher_setkey(s->ipsec.rx.cry_ctx, s->ipsec.rx.key_cry, s->ipsec.key_len);
3126 		gcry_cipher_setkey(s->ipsec.tx.cry_ctx, s->ipsec.tx.key_cry, s->ipsec.key_len);
3127 	}
3128 
3129 	/* use request as template and just exchange some values */
3130 	/* this overwrites data in nonce_i, ke! */
3131 	rp = r->payload->next;
3132 	/* SA, change the SPI */
3133 	memcpy(rp->u.sa.proposals->u.p.spi, &s->ipsec.rx.spi, 4);
3134 
3135 	for (rp = rp->next; rp; rp = rp->next)
3136 		switch (rp->type) {
3137 		case ISAKMP_PAYLOAD_ID:
3138 			break;
3139 		case ISAKMP_PAYLOAD_KE:
3140 			memcpy(rp->u.ke.data, dh_public, dh_getlen(dh_grp));
3141 			break;
3142 		case ISAKMP_PAYLOAD_NONCE:
3143 			memcpy(rp->u.nonce.data, nonce_r, sizeof(nonce_r));
3144 			break;
3145 		default:
3146 			assert(0);
3147 			break;
3148 		}
3149 
3150 	sendrecv_phase2(s, r->payload->next, ISAKMP_EXCHANGE_IKE_QUICK,
3151 		r->message_id, 0, 0, 0, nonce_i_copy, nonce_i_copy_len, 0,0);
3152 	unpack_verify_phase2(s, r_packet, r_length, &r, NULL, 0);
3153 	free(nonce_i_copy);
3154 	/* don't care about answer ... */
3155 
3156 	return 0;
3157 }
3158 
process_late_ike(struct sa_block * s,uint8_t * r_packet,ssize_t r_length)3159 void process_late_ike(struct sa_block *s, uint8_t *r_packet, ssize_t r_length)
3160 {
3161 	int reject;
3162 	struct isakmp_packet *r;
3163 	struct isakmp_payload *rp;
3164 
3165 	DEBUG(2,printf("got late ike paket: %zd bytes\n", r_length));
3166 	/* we should ignore resent pakets here.
3167 	 * unpack_verify_phase2 will fail to decode them probably */
3168 	reject = unpack_verify_phase2(s, r_packet, r_length, &r, NULL, 0);
3169 
3170 	/* just ignore broken stuff for now */
3171 	if (reject != 0) {
3172 		if (r) free_isakmp_packet(r);
3173 		return;
3174 	}
3175 
3176 	/* everything must be encrypted by now */
3177 	if (r->payload == NULL || r->payload->type != ISAKMP_PAYLOAD_HASH) {
3178 		free_isakmp_packet(r);
3179 		return;
3180 	}
3181 
3182 	/* empty packet? well, nothing to see here */
3183 	if (r->payload->next == NULL) {
3184 		free_isakmp_packet(r);
3185 		return;
3186 	}
3187 
3188 	/* do we get an SA proposal for rekeying? */
3189 	if (r->exchange_type == ISAKMP_EXCHANGE_IKE_QUICK &&
3190 		r->payload->next->type == ISAKMP_PAYLOAD_SA) {
3191 		reject = do_rekey(s, r);
3192 		DEBUG(3, printf("do_rekey returned: %d\n", reject));
3193 		/* FIXME: LEAK but will create segfault for double free */
3194 		/* free_isakmp_packet(r); */
3195 		return;
3196 	}
3197 
3198 	if (r->exchange_type == ISAKMP_EXCHANGE_INFORMATIONAL) {
3199 		/* Search for notify payloads */
3200 		for (rp = r->payload->next; rp; rp = rp->next) {
3201 			if (rp->type != ISAKMP_PAYLOAD_N)
3202 				continue;
3203 			/* did we get a DPD request or ACK? */
3204 			if (rp->u.n.protocol != ISAKMP_IPSEC_PROTO_ISAKMP) {
3205 				DEBUG(2, printf("got non isakmp-notify, ignoring...\n"));
3206 				continue;
3207 			}
3208 			if (rp->u.n.type == ISAKMP_N_R_U_THERE) {
3209 				uint32_t seq;
3210 				if (rp->u.n.data_length != 4) {
3211 					DEBUG(2, printf("ignoring bad data length R-U-THERE request\n"));
3212 					continue;
3213 				}
3214 				memcpy(&seq, rp->u.n.data, 4);
3215 				send_dpd(s, 1, seq);
3216 				DEBUG(2, printf("got r-u-there request sent ack\n"));
3217 				continue;
3218 			} else if (rp->u.n.type == ISAKMP_N_R_U_THERE_ACK) {
3219 				uint32_t seqack;
3220 				if (rp->u.n.data_length != 4) {
3221 					DEBUG(2, printf("ignoring bad data length R-U-THERE-ACK\n"));
3222 					continue;
3223 				}
3224 				memcpy(&seqack, rp->u.n.data, 4);
3225 				if (seqack == s->ike.dpd_seqno) {
3226 					s->ike.dpd_seqno_ack = seqack;
3227 				} else {
3228 					DEBUG(2, printf("ignoring r-u-there ack %u (expecting %u)\n", seqack, s->ike.dpd_seqno));
3229 					continue;
3230 				}
3231 				DEBUG(2, printf("got r-u-there ack\n"));
3232 			}
3233 		}
3234 	}
3235 
3236 	/* check if our isakmp sa gets deleted */
3237 	for (rp = r->payload->next; rp; rp = rp->next) {
3238 		/* search for delete payloads */
3239 		if (rp->type != ISAKMP_PAYLOAD_D)
3240 			continue;
3241 		if (rp->u.d.protocol == ISAKMP_IPSEC_PROTO_IPSEC_ESP) {
3242 			/* RFC2408, 5.15:
3243 			 * Process the Delete payload and take appropriate action, according
3244 			 * to local security policy.  As described above, one appropriate
3245 			 * action SHOULD include cleaning up the local SA database.
3246 			 */
3247 			/* FIXME: any cleanup needed??? */
3248 
3249 			if (rp->u.d.num_spi >= 1 && memcmp(rp->u.d.spi[0], &s->ipsec.tx.spi, 4) == 0) {
3250 				free_isakmp_packet(r);
3251 				do_phase2_qm(s);
3252 				return;
3253 			} else {
3254 				DEBUG(2, printf("got isakmp delete with bogus spi, ignoring...\n"));
3255 				continue;
3256 			}
3257 		}
3258 		/* skip ipsec-esp delete */
3259 		if (rp->u.d.protocol != ISAKMP_IPSEC_PROTO_ISAKMP) {
3260 			DEBUG(2, printf("got non isakmp-delete, ignoring...\n"));
3261 			continue;
3262 		};
3263 
3264 		/*
3265 		 * RFC 2408, 3.15 Delete Payload
3266 		 * it is not stated that the SPI field of a delete
3267 		 * payload can be ignored, because it is given in
3268 		 * the headers, but I assume so. In other cases
3269 		 * RFC 2408 (notifications) states this.
3270 		 */
3271 		do_kill = -1;
3272 		DEBUG(2, printf("got isakmp-delete, terminating...\n"));
3273 		free_isakmp_packet(r);
3274 		return;
3275 	}
3276 
3277 	free_isakmp_packet(r);
3278 	return;
3279 }
3280 
main(int argc,char ** argv)3281 int main(int argc, char **argv)
3282 {
3283 	int do_load_balance;
3284 	const uint8_t hex_test[] = { 0, 1, 2, 3 };
3285 	struct sa_block oursa[1];
3286 	struct sa_block *s = oursa;
3287 
3288 	test_pack_unpack();
3289 #if defined(__CYGWIN__)
3290 	gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
3291 #endif
3292 	gcry_check_version("1.1.90");
3293 	gcry_control(GCRYCTL_INIT_SECMEM, 16384, 0);
3294 	group_init();
3295 
3296 	memset(s, 0, sizeof(*s));
3297 	s->ipsec.encap_mode = IPSEC_ENCAP_TUNNEL;
3298 	s->ike.timeout = 1000; /* 1 second */
3299 
3300 	do_config(argc, argv);
3301 
3302 	DEBUG(1, printf("\nvpnc version " VERSION "\n"));
3303 	hex_dump("hex_test", hex_test, sizeof(hex_test), NULL);
3304 
3305 	DEBUGTOP(2, printf("S1 init_sockaddr\n"));
3306 	init_sockaddr(&s->dst, config[CONFIG_IPSEC_GATEWAY]);
3307 	init_sockaddr(&s->opt_src_ip, config[CONFIG_LOCAL_ADDR]);
3308 	DEBUGTOP(2, printf("S2 make_socket\n"));
3309 	s->ike.src_port = atoi(config[CONFIG_LOCAL_PORT]);
3310 	s->ike.dst_port = ISAKMP_PORT;
3311 	s->ike_fd = make_socket(s, s->ike.src_port, s->ike.dst_port);
3312 	DEBUGTOP(2, printf("S3 setup_tunnel\n"));
3313 	setup_tunnel(s);
3314 
3315 	do_load_balance = 0;
3316 	do {
3317 		DEBUGTOP(2, printf("S4 do_phase1_am\n"));
3318 		do_phase1_am(config[CONFIG_IPSEC_ID], config[CONFIG_IPSEC_SECRET], s);
3319 		DEBUGTOP(2, printf("S5 do_phase2_xauth\n"));
3320 		/* FIXME: Create and use a generic function in supp.[hc] */
3321 		if (s->ike.auth_algo >= IKE_AUTH_HybridInitRSA)
3322 			do_load_balance = do_phase2_xauth(s);
3323 		DEBUGTOP(2, printf("S6 do_phase2_config\n"));
3324 		if ((opt_vendor == VENDOR_CISCO) && (do_load_balance == 0))
3325 			do_load_balance = do_phase2_config(s);
3326 	} while (do_load_balance);
3327 	DEBUGTOP(2, printf("S7 setup_link (phase 2 + main_loop)\n"));
3328 	DEBUGTOP(2, printf("S7.0 run interface setup script\n"));
3329 	config_tunnel(s);
3330 	do_phase2_qm(s);
3331 	DEBUGTOP(2, printf("S7.9 main loop (receive and transmit ipsec packets)\n"));
3332 	vpnc_doit(s);
3333 
3334 	/* Tear down phase 2 and 1 tunnels */
3335 	send_delete_ipsec(s);
3336 	send_delete_isakmp(s);
3337 
3338 	/* Cleanup routing */
3339 	DEBUGTOP(2, printf("S8 close_tunnel\n"));
3340 	close_tunnel(s);
3341 
3342 	/* Free resources */
3343 	DEBUGTOP(2, printf("S9 cleanup\n"));
3344 	cleanup(s);
3345 
3346 	return 0;
3347 }
3348