]> git.saurik.com Git - apple/ipsec.git/blob - ipsec-tools/racoon/isakmp.c
ipsec-92.4.tar.gz
[apple/ipsec.git] / ipsec-tools / racoon / isakmp.c
1 /* $NetBSD: isakmp.c,v 1.20.6.7 2007/08/01 11:52:20 vanhu Exp $ */
2
3 /* Id: isakmp.c,v 1.74 2006/05/07 21:32:59 manubsd Exp */
4
5 /*
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33 #ifdef __APPLE__
34 #define __APPLE_API_PRIVATE
35 #endif
36
37 #include "config.h"
38
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/socket.h>
42 #include <sys/queue.h>
43
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46
47 #ifndef HAVE_NETINET6_IPSEC
48 #include <netinet/ipsec.h>
49 #else
50 #include <netinet6/ipsec.h>
51 #endif
52
53 #include <stdlib.h>
54 #include <stdio.h>
55 #include <string.h>
56 #include <errno.h>
57 #if TIME_WITH_SYS_TIME
58 # include <sys/time.h>
59 # include <time.h>
60 #else
61 # if HAVE_SYS_TIME_H
62 # include <sys/time.h>
63 # else
64 # include <time.h>
65 # endif
66 #endif
67 #include <netdb.h>
68 #ifdef HAVE_UNISTD_H
69 #include <unistd.h>
70 #endif
71 #include <ctype.h>
72 #ifdef ENABLE_HYBRID
73 #include <resolv.h>
74 #endif
75
76 #include "var.h"
77 #include "misc.h"
78 #include "vmbuf.h"
79 #include "plog.h"
80 #include "sockmisc.h"
81 #include "schedule.h"
82 #include "debug.h"
83
84 #include "remoteconf.h"
85 #include "localconf.h"
86 #include "grabmyaddr.h"
87 #include "admin.h"
88 #include "privsep.h"
89 #include "isakmp_var.h"
90 #include "isakmp.h"
91 #include "oakley.h"
92 #include "evt.h"
93 #include "handler.h"
94 #include "proposal.h"
95 #include "ipsec_doi.h"
96 #include "pfkey.h"
97 #include "crypto_openssl.h"
98 #include "policy.h"
99 #include "isakmp_ident.h"
100 #include "isakmp_agg.h"
101 #include "isakmp_base.h"
102 #include "isakmp_quick.h"
103 #include "isakmp_inf.h"
104 #include "isakmp_newg.h"
105 #include "vpn_control.h"
106 #include "vpn_control_var.h"
107 #ifdef ENABLE_HYBRID
108 #include "vendorid.h"
109 #include "isakmp_xauth.h"
110 #include "isakmp_unity.h"
111 #include "isakmp_cfg.h"
112 #endif
113 #ifdef ENABLE_FRAG
114 #include "isakmp_frag.h"
115 #endif
116 #include "strnames.h"
117
118 #include <fcntl.h>
119
120 #ifdef ENABLE_NATT
121 # include "nattraversal.h"
122 #endif
123 #include "ike_session.h"
124 # ifdef __linux__
125 # include <linux/udp.h>
126 # include <linux/ip.h>
127 # ifndef SOL_UDP
128 # define SOL_UDP 17
129 # endif
130 # endif /* __linux__ */
131 # if defined(__NetBSD__) || defined(__FreeBSD__) || \
132 (defined(__APPLE__) && defined(__MACH__))
133 # include <netinet/in.h>
134 # include <netinet/udp.h>
135 # include <netinet/in_systm.h>
136 # include <netinet/ip.h>
137 # define SOL_UDP IPPROTO_UDP
138 # endif /* __NetBSD__ / __FreeBSD__ */
139 #include "ipsecSessionTracer.h"
140 #include "ipsecMessageTracer.h"
141
142 static int nostate1 __P((struct ph1handle *, vchar_t *));
143 static int nostate2 __P((struct ph2handle *, vchar_t *));
144
145 extern caddr_t val2str(const char *, size_t);
146
147 static int (*ph1exchange[][2][PHASE1ST_MAX])
148 __P((struct ph1handle *, vchar_t *)) = {
149 /* error */
150 { {}, {}, },
151 /* Identity Protection exchange */
152 {
153 { nostate1, ident_i1send, nostate1, ident_i2recv, ident_i2send,
154 ident_i3recv, ident_i3send, ident_i4recv, ident_i4send, nostate1, },
155 { nostate1, ident_r1recv, ident_r1send, ident_r2recv, ident_r2send,
156 ident_r3recv, ident_r3send, nostate1, nostate1, nostate1, },
157 },
158 /* Aggressive exchange */
159 {
160 { nostate1, agg_i1send, nostate1, agg_i2recv, agg_i2send,
161 nostate1, nostate1, nostate1, nostate1, nostate1, },
162 { nostate1, agg_r1recv, agg_r1send, agg_r2recv, agg_r2send,
163 nostate1, nostate1, nostate1, nostate1, nostate1, },
164 },
165 /* Base exchange */
166 {
167 { nostate1, base_i1send, nostate1, base_i2recv, base_i2send,
168 base_i3recv, base_i3send, nostate1, nostate1, nostate1, },
169 { nostate1, base_r1recv, base_r1send, base_r2recv, base_r2send,
170 nostate1, nostate1, nostate1, nostate1, nostate1, },
171 },
172 };
173
174 static int (*ph2exchange[][2][PHASE2ST_MAX])
175 __P((struct ph2handle *, vchar_t *)) = {
176 /* error */
177 { {}, {}, },
178 /* Quick mode for IKE */
179 {
180 { nostate2, nostate2, quick_i1prep, nostate2, quick_i1send,
181 quick_i2recv, quick_i2send, quick_i3recv, nostate2, nostate2, },
182 { nostate2, quick_r1recv, quick_r1prep, nostate2, quick_r2send,
183 quick_r3recv, quick_r3prep, quick_r3send, nostate2, nostate2, }
184 },
185 };
186
187 static u_char r_ck0[] = { 0,0,0,0,0,0,0,0 }; /* used to verify the r_ck. */
188
189 static int isakmp_main __P((vchar_t *, struct sockaddr *, struct sockaddr *));
190 static int ph1_main __P((struct ph1handle *, vchar_t *));
191 static int quick_main __P((struct ph2handle *, vchar_t *));
192 static int isakmp_ph1begin_r __P((vchar_t *,
193 struct sockaddr *, struct sockaddr *, u_int8_t));
194 static int isakmp_ph2begin_i __P((struct ph1handle *, struct ph2handle *));
195 static int isakmp_ph2begin_r __P((struct ph1handle *, vchar_t *));
196 static int etypesw1 __P((int));
197 static int etypesw2 __P((int));
198 #ifdef ENABLE_FRAG
199 static int frag_handler(struct ph1handle *,
200 vchar_t *, struct sockaddr *, struct sockaddr *);
201 #endif
202
203 /*
204 * isakmp packet handler
205 */
206 int
207 isakmp_handler(so_isakmp)
208 int so_isakmp;
209 {
210 struct isakmp isakmp;
211 union {
212 char buf[sizeof (isakmp) + 4];
213 u_int32_t non_esp[2];
214 char lbuf[sizeof(struct udphdr) +
215 #ifdef __linux
216 sizeof(struct iphdr) +
217 #else
218 sizeof(struct ip) +
219 #endif
220 sizeof(isakmp) + 4];
221 } x;
222 struct sockaddr_storage remote;
223 struct sockaddr_storage local;
224 unsigned int remote_len = sizeof(remote);
225 unsigned int local_len = sizeof(local);
226 int len = 0, extralen = 0;
227 u_short port;
228 vchar_t *buf = NULL, *tmpbuf = NULL;
229 int error = -1;
230
231 /* read message by MSG_PEEK */
232 while ((len = recvfromto(so_isakmp, x.buf, sizeof(x),
233 MSG_PEEK, (struct sockaddr *)&remote, &remote_len,
234 (struct sockaddr *)&local, &local_len)) < 0) {
235 if (errno == EINTR)
236 continue;
237 plog(LLV_ERROR, LOCATION, NULL,
238 "failed to receive isakmp packet: %s\n",
239 strerror (errno));
240 goto end;
241 }
242
243 /* keep-alive packet - ignore */
244 if (len == 1 && (x.buf[0]&0xff) == 0xff) {
245 /* Pull the keep-alive packet */
246 if ((len = recvfrom(so_isakmp, (char *)x.buf, 1,
247 0, (struct sockaddr *)&remote, &remote_len)) != 1) {
248 plog(LLV_ERROR, LOCATION, NULL,
249 "failed to receive keep alive packet: %s\n",
250 strerror (errno));
251 }
252 goto end;
253 }
254
255 /* Lucent IKE in UDP encapsulation */
256 {
257 struct udphdr *udp;
258 #ifdef __linux__
259 struct iphdr *ip;
260
261 udp = (struct udphdr *)&x.lbuf[0];
262 if (ntohs(udp->dest) == 501) {
263 ip = (struct iphdr *)(x.lbuf + sizeof(*udp));
264 extralen += sizeof(*udp) + ip->ihl;
265 }
266 #else
267 struct ip *ip;
268
269 udp = (struct udphdr *)&x.lbuf[0];
270 if (ntohs(udp->uh_dport) == 501) {
271 ip = (struct ip *)(x.lbuf + sizeof(*udp));
272 extralen += sizeof(*udp) + ip->ip_hl;
273 }
274 #endif
275 }
276
277 #ifdef ENABLE_NATT
278 /* we don't know about portchange yet,
279 look for non-esp marker instead */
280 if (x.non_esp[0] == 0 && x.non_esp[1] != 0)
281 extralen = NON_ESP_MARKER_LEN;
282 #endif
283
284 /* now we know if there is an extra non-esp
285 marker at the beginning or not */
286 memcpy ((char *)&isakmp, x.buf + extralen, sizeof (isakmp));
287
288 /* check isakmp header length, as well as sanity of header length */
289 if (len < sizeof(isakmp) || ntohl(isakmp.len) < sizeof(isakmp)) {
290 plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
291 "packet shorter than isakmp header size (%u, %u, %zu)\n",
292 len, ntohl(isakmp.len), sizeof(isakmp));
293 /* dummy receive */
294 if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
295 0, (struct sockaddr *)&remote, &remote_len)) < 0) {
296 plog(LLV_ERROR, LOCATION, NULL,
297 "failed to receive isakmp packet: %s\n",
298 strerror (errno));
299 }
300 goto end;
301 }
302
303 /* reject it if the size is tooooo big. */
304 if (ntohl(isakmp.len) > 0xffff) {
305 plog(LLV_ERROR, LOCATION, NULL,
306 "the length in the isakmp header is too big.\n");
307 if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
308 0, (struct sockaddr *)&remote, &remote_len)) < 0) {
309 plog(LLV_ERROR, LOCATION, NULL,
310 "failed to receive isakmp packet: %s\n",
311 strerror (errno));
312 }
313 goto end;
314 }
315
316 /* read real message */
317 if ((tmpbuf = vmalloc(ntohl(isakmp.len) + extralen)) == NULL) {
318 plog(LLV_ERROR, LOCATION, NULL,
319 "failed to allocate reading buffer (%u Bytes)\n",
320 ntohl(isakmp.len) + extralen);
321 /* dummy receive */
322 if ((len = recvfrom(so_isakmp, (char *)&isakmp, sizeof(isakmp),
323 0, (struct sockaddr *)&remote, &remote_len)) < 0) {
324 plog(LLV_ERROR, LOCATION, NULL,
325 "failed to receive isakmp packet: %s\n",
326 strerror (errno));
327 #ifdef __APPLE__
328 error = -2; /* serious problem with socket */
329 #endif
330 }
331 goto end;
332 }
333
334 while ((len = recvfromto(so_isakmp, (char *)tmpbuf->v, tmpbuf->l,
335 0, (struct sockaddr *)&remote, &remote_len,
336 (struct sockaddr *)&local, &local_len)) < 0) {
337 if (errno == EINTR)
338 continue;
339 plog(LLV_ERROR, LOCATION, NULL,
340 "failed to receive isakmp packet: %s\n",
341 strerror (errno));
342 goto end;
343 }
344
345 if ((buf = vmalloc(len - extralen)) == NULL) {
346 plog(LLV_ERROR, LOCATION, NULL,
347 "failed to allocate reading buffer (%u Bytes)\n",
348 (len - extralen));
349 goto end;
350 }
351
352 memcpy (buf->v, tmpbuf->v + extralen, buf->l);
353
354 len -= extralen;
355
356 if (len != buf->l) {
357 plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
358 "received invalid length (%d != %zu), why ?\n",
359 len, buf->l);
360 goto end;
361 }
362
363 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
364 plog(LLV_DEBUG, LOCATION, NULL,
365 "%d bytes message received %s\n",
366 len, saddr2str_fromto("from %s to %s",
367 (struct sockaddr *)&remote,
368 (struct sockaddr *)&local));
369 plogdump(LLV_DEBUG, buf->v, buf->l);
370
371 /* avoid packets with malicious port/address */
372 switch (remote.ss_family) {
373 case AF_INET:
374 port = ((struct sockaddr_in *)&remote)->sin_port;
375 break;
376 #ifdef INET6
377 case AF_INET6:
378 port = ((struct sockaddr_in6 *)&remote)->sin6_port;
379 break;
380 #endif
381 default:
382 plog(LLV_ERROR, LOCATION, NULL,
383 "invalid family: %d\n", remote.ss_family);
384 goto end;
385 }
386 if (port == 0) {
387 plog(LLV_ERROR, LOCATION, (struct sockaddr *)&remote,
388 "src port == 0 (valid as UDP but not with IKE)\n");
389 goto end;
390 }
391
392 /* XXX: check sender whether to be allowed or not to accept */
393
394 /* XXX: I don't know how to check isakmp half connection attack. */
395
396 /* simply reply if the packet was processed. */
397 if (check_recvdpkt((struct sockaddr *)&remote,
398 (struct sockaddr *)&local, buf)) {
399 plog(LLV_NOTIFY, LOCATION, NULL,
400 "the packet is retransmitted by %s.\n",
401 saddr2str((struct sockaddr *)&remote));
402 error = 0;
403 goto end;
404 }
405
406 /* isakmp main routine */
407 if (isakmp_main(buf, (struct sockaddr *)&remote,
408 (struct sockaddr *)&local) != 0) goto end;
409
410 error = 0;
411
412 end:
413 if (tmpbuf != NULL)
414 vfree(tmpbuf);
415 if (buf != NULL)
416 vfree(buf);
417
418 return(error);
419 }
420
421 /*
422 * main processing to handle isakmp payload
423 */
424 static int
425 isakmp_main(msg, remote, local)
426 vchar_t *msg;
427 struct sockaddr *remote, *local;
428 {
429 struct isakmp *isakmp = (struct isakmp *)msg->v;
430 isakmp_index *index = (isakmp_index *)isakmp;
431 u_int32_t msgid = isakmp->msgid;
432 struct ph1handle *iph1;
433
434 #ifdef HAVE_PRINT_ISAKMP_C
435 isakmp_printpacket(msg, remote, local, 0);
436 #endif
437
438 /* the initiator's cookie must not be zero */
439 if (memcmp(&isakmp->i_ck, r_ck0, sizeof(cookie_t)) == 0) {
440 plog(LLV_ERROR, LOCATION, remote,
441 "malformed cookie received.\n");
442 return -1;
443 }
444
445 /* Check the Major and Minor Version fields. */
446 /*
447 * XXX Is is right to check version here ?
448 * I think it may no be here because the version depends
449 * on exchange status.
450 */
451 if (isakmp->v < ISAKMP_VERSION_NUMBER) {
452 if (ISAKMP_GETMAJORV(isakmp->v) < ISAKMP_MAJOR_VERSION) {
453 plog(LLV_ERROR, LOCATION, remote,
454 "invalid major version %d.\n",
455 ISAKMP_GETMAJORV(isakmp->v));
456 return -1;
457 }
458 #if ISAKMP_MINOR_VERSION > 0
459 if (ISAKMP_GETMINORV(isakmp->v) < ISAKMP_MINOR_VERSION) {
460 plog(LLV_ERROR, LOCATION, remote,
461 "invalid minor version %d.\n",
462 ISAKMP_GETMINORV(isakmp->v));
463 return -1;
464 }
465 #endif
466 }
467
468 /* check the Flags field. */
469 /* XXX How is the exclusive check, E and A ? */
470 if (isakmp->flags & ~(ISAKMP_FLAG_E | ISAKMP_FLAG_C | ISAKMP_FLAG_A)) {
471 plog(LLV_ERROR, LOCATION, remote,
472 "invalid flag 0x%02x.\n", isakmp->flags);
473 return -1;
474 }
475
476 /* ignore commit bit. */
477 if (ISSET(isakmp->flags, ISAKMP_FLAG_C)) {
478 if (isakmp->msgid == 0) {
479 isakmp_info_send_nx(isakmp, remote, local,
480 ISAKMP_NTYPE_INVALID_FLAGS, NULL);
481 plog(LLV_ERROR, LOCATION, remote,
482 "Commit bit on phase1 forbidden.\n");
483 return -1;
484 }
485 }
486
487 iph1 = getph1byindex(index);
488 if (iph1 != NULL) {
489 /* validity check */
490 if (memcmp(&isakmp->r_ck, r_ck0, sizeof(cookie_t)) == 0 &&
491 iph1->side == INITIATOR) {
492 IPSECSESSIONTRACEREVENT(iph1->parent_session,
493 IPSECSESSIONEVENTCODE_IKE_PACKET_RX_FAIL,
494 CONSTSTR("malformed or unexpected cookie"),
495 CONSTSTR("Failed to process packet (malformed/unexpected cookie)"));
496 plog(LLV_DEBUG, LOCATION, remote,
497 "malformed cookie received or "
498 "the initiator's cookies collide.\n");
499 return -1;
500 }
501
502 #ifdef ENABLE_NATT
503 /* Floating ports for NAT-T */
504 if (NATT_AVAILABLE(iph1) &&
505 ! (iph1->natt_flags & NAT_PORTS_CHANGED) &&
506 ((cmpsaddrstrict(iph1->remote, remote) != 0) ||
507 (cmpsaddrstrict(iph1->local, local) != 0)))
508 {
509 /* prevent memory leak */
510 racoon_free(iph1->remote);
511 racoon_free(iph1->local);
512 iph1->remote = NULL;
513 iph1->local = NULL;
514
515 /* copy-in new addresses */
516 iph1->remote = dupsaddr(remote);
517 if (iph1->remote == NULL) {
518 IPSECSESSIONTRACEREVENT(iph1->parent_session,
519 IPSECSESSIONEVENTCODE_IKE_PACKET_RX_FAIL,
520 CONSTSTR("failed to duplicate remote address"),
521 CONSTSTR("Failed to process phase1 message (can't duplicate remote address"));
522 plog(LLV_ERROR, LOCATION, iph1->remote,
523 "phase1 failed: dupsaddr failed.\n");
524 remph1(iph1);
525 delph1(iph1);
526 return -1;
527 }
528 iph1->local = dupsaddr(local);
529 if (iph1->local == NULL) {
530 IPSECSESSIONTRACEREVENT(iph1->parent_session,
531 IPSECSESSIONEVENTCODE_IKE_PACKET_RX_FAIL,
532 CONSTSTR("failed to duplicate local address"),
533 CONSTSTR("Failed to process phase1 message (can't duplicate local address"));
534 plog(LLV_ERROR, LOCATION, iph1->remote,
535 "phase1 failed: dupsaddr failed.\n");
536 remph1(iph1);
537 delph1(iph1);
538 return -1;
539 }
540
541 /* set the flag to prevent further port floating
542 (FIXME: should we allow it? E.g. when the NAT gw
543 is rebooted?) */
544 iph1->natt_flags |= NAT_PORTS_CHANGED | NAT_ADD_NON_ESP_MARKER;
545
546 /* print some neat info */
547 plog (LLV_INFO, LOCATION, NULL,
548 "NAT-T: ports changed to: %s\n",
549 saddr2str_fromto ("%s<->%s", iph1->remote, iph1->local));
550 #ifndef __APPLE__
551 natt_keepalive_add_ph1 (iph1);
552 #endif
553 }
554 #endif
555
556 /* must be same addresses in one stream of a phase at least. */
557 if (cmpsaddrstrict(iph1->remote, remote) != 0) {
558 char *saddr_db, *saddr_act;
559
560 saddr_db = racoon_strdup(saddr2str(iph1->remote));
561 saddr_act = racoon_strdup(saddr2str(remote));
562 STRDUP_FATAL(saddr_db);
563 STRDUP_FATAL(saddr_act);
564
565 plog(LLV_WARNING, LOCATION, remote,
566 "remote address mismatched. db=%s, act=%s\n",
567 saddr_db, saddr_act);
568
569 racoon_free(saddr_db);
570 racoon_free(saddr_act);
571 }
572
573 /*
574 * don't check of exchange type here because other type will be
575 * with same index, for example, informational exchange.
576 */
577
578 /* XXX more acceptable check */
579
580 #ifdef ENABLE_DPD
581 // received ike packets: update dpd checks
582 isakmp_reschedule_info_monitor_if_pending(iph1,
583 "ike packets received from peer");
584 #endif /* DPD */
585 }
586
587 switch (isakmp->etype) {
588 case ISAKMP_ETYPE_IDENT:
589 case ISAKMP_ETYPE_AGG:
590 case ISAKMP_ETYPE_BASE:
591 /* phase 1 validity check */
592 if (isakmp->msgid != 0) {
593 plog(LLV_ERROR, LOCATION, remote,
594 "message id should be zero in phase1.\n");
595 return -1;
596 }
597
598 /* search for isakmp status record of phase 1 */
599 if (iph1 == NULL) {
600 /*
601 * the packet must be the 1st message from a initiator
602 * or the 2nd message from the responder.
603 */
604
605 /* search for phase1 handle by index without r_ck */
606 iph1 = getph1byindex0(index);
607 if (iph1 == NULL) {
608 /*it must be the 1st message from a initiator.*/
609 if (memcmp(&isakmp->r_ck, r_ck0,
610 sizeof(cookie_t)) != 0) {
611
612 plog(LLV_DEBUG, LOCATION, remote,
613 "malformed cookie received "
614 "or the spi expired.\n");
615 return -1;
616 }
617
618 /* it must be responder's 1st exchange. */
619 if (isakmp_ph1begin_r(msg, remote, local,
620 isakmp->etype) < 0)
621 return -1;
622 break;
623
624 /*NOTREACHED*/
625 }
626
627 /* it must be the 2nd message from the responder. */
628 if (iph1->side != INITIATOR) {
629 IPSECSESSIONTRACEREVENT(iph1->parent_session,
630 IPSECSESSIONEVENTCODE_IKE_PACKET_RX_FAIL,
631 CONSTSTR("malformed cookie and unexpected side"),
632 CONSTSTR("Failed to process phase1 message (unexpected side)"));
633 plog(LLV_DEBUG, LOCATION, remote,
634 "malformed cookie received. "
635 "it has to be as the initiator. %s\n",
636 isakmp_pindex(&iph1->index, 0));
637 return -1;
638 }
639 }
640
641 /*
642 * Don't delete phase 1 handler when the exchange type
643 * in handler is not equal to packet's one because of no
644 * authencication completed.
645 */
646 if (iph1->etype != isakmp->etype) {
647 IPSECSESSIONTRACEREVENT(iph1->parent_session,
648 IPSECSESSIONEVENTCODE_IKE_PACKET_RX_FAIL,
649 CONSTSTR("mismatched exchange type"),
650 CONSTSTR("Failed to process phase1 message (mismatched exchange type)"));
651 plog(LLV_ERROR, LOCATION, iph1->remote,
652 "exchange type is mismatched: "
653 "db=%s packet=%s, ignore it.\n",
654 s_isakmp_etype(iph1->etype),
655 s_isakmp_etype(isakmp->etype));
656 return -1;
657 }
658
659 #ifdef ENABLE_FRAG
660 if (isakmp->np == ISAKMP_NPTYPE_FRAG)
661 return frag_handler(iph1, msg, remote, local);
662 #endif
663
664 /* call main process of phase 1 */
665 if (ph1_main(iph1, msg) < 0) {
666 plog(LLV_ERROR, LOCATION, iph1->remote,
667 "phase1 negotiation failed.\n");
668 remph1(iph1);
669 delph1(iph1);
670 return -1;
671 }
672 break;
673
674 case ISAKMP_ETYPE_AUTH:
675 plog(LLV_INFO, LOCATION, remote,
676 "unsupported exchange %d received.\n",
677 isakmp->etype);
678 break;
679
680 case ISAKMP_ETYPE_INFO:
681 case ISAKMP_ETYPE_ACKINFO:
682 /*
683 * iph1 must be present for Information message.
684 * if iph1 is null then trying to get the phase1 status
685 * as the packet from responder againt initiator's 1st
686 * exchange in phase 1.
687 * NOTE: We think such informational exchange should be ignored.
688 */
689 if (iph1 == NULL) {
690 iph1 = getph1byindex0(index);
691 if (iph1 == NULL) {
692 plog(LLV_ERROR, LOCATION, remote,
693 "unknown Informational "
694 "exchange received.\n");
695 return -1;
696 }
697 if (cmpsaddrstrict(iph1->remote, remote) != 0) {
698 plog(LLV_WARNING, LOCATION, remote,
699 "remote address mismatched. "
700 "db=%s\n",
701 saddr2str(iph1->remote));
702 }
703 }
704
705 #ifdef ENABLE_FRAG
706 if (isakmp->np == ISAKMP_NPTYPE_FRAG)
707 return frag_handler(iph1, msg, remote, local);
708 #endif
709
710 if (isakmp_info_recv(iph1, msg) < 0)
711 return -1;
712 break;
713
714 case ISAKMP_ETYPE_QUICK:
715 {
716 struct ph2handle *iph2;
717
718 if (iph1 == NULL) {
719 isakmp_info_send_nx(isakmp, remote, local,
720 ISAKMP_NTYPE_INVALID_COOKIE, NULL);
721 plog(LLV_ERROR, LOCATION, remote,
722 "can't start the quick mode, "
723 "there is no ISAKMP-SA, %s\n",
724 isakmp_pindex((isakmp_index *)&isakmp->i_ck,
725 isakmp->msgid));
726 return -1;
727 }
728 #ifdef ENABLE_HYBRID
729 /* Reinit the IVM if it's still there */
730 if (iph1->mode_cfg && iph1->mode_cfg->ivm) {
731 oakley_delivm(iph1->mode_cfg->ivm);
732 iph1->mode_cfg->ivm = NULL;
733 }
734 #endif
735 #ifdef ENABLE_FRAG
736 if (isakmp->np == ISAKMP_NPTYPE_FRAG)
737 return frag_handler(iph1, msg, remote, local);
738 #endif
739
740 /* check status of phase 1 whether negotiated or not. */
741 if (iph1->status != PHASE1ST_ESTABLISHED) {
742 IPSECSESSIONTRACEREVENT(iph1->parent_session,
743 IPSECSESSIONEVENTCODE_IKEV1_PH2_INIT_DROP,
744 CONSTSTR("can't start phase2 without valid phase1"),
745 CONSTSTR("Failed to start phase2 resonder (no established phase1"));
746 plog(LLV_ERROR, LOCATION, remote,
747 "can't start the quick mode, "
748 "there is no valid ISAKMP-SA, %s\n",
749 isakmp_pindex(&iph1->index, iph1->msgid));
750 return -1;
751 }
752
753 /* search isakmp phase 2 stauts record. */
754 iph2 = getph2bymsgid(iph1, msgid);
755 if (iph2 == NULL) {
756 /* it must be new negotiation as responder */
757 if (isakmp_ph2begin_r(iph1, msg) < 0)
758 return -1;
759 return 0;
760 /*NOTREACHED*/
761 }
762
763 /* commit bit. */
764 /* XXX
765 * we keep to set commit bit during negotiation.
766 * When SA is configured, bit will be reset.
767 * XXX
768 * don't initiate commit bit. should be fixed in the future.
769 */
770 if (ISSET(isakmp->flags, ISAKMP_FLAG_C))
771 iph2->flags |= ISAKMP_FLAG_C;
772
773 if (ISSET(isakmp->flags, ISAKMP_FLAG_E) &&
774 (iph2->ph1 == NULL || iph2->ph1->approval == NULL)) {
775 IPSECSESSIONTRACEREVENT(iph2->parent_session,
776 IPSECSESSIONEVENTCODE_IKEV1_PH2_INIT_DROP,
777 CONSTSTR("can't continue phase2 without valid phase1"),
778 CONSTSTR("Failed to continue phase2 resonder (invalid linked phase1"));
779 plog(LLV_ERROR, LOCATION, remote,
780 "can't start the quick mode, "
781 "invalid linked ISAKMP-SA\n");
782 return -1;
783 }
784
785 /* call main process of quick mode */
786 if (quick_main(iph2, msg) < 0) {
787 plog(LLV_ERROR, LOCATION, iph1->remote,
788 "phase2 negotiation failed.\n");
789 unbindph12(iph2);
790 remph2(iph2);
791 delph2(iph2);
792 return -1;
793 }
794 }
795 break;
796
797 case ISAKMP_ETYPE_NEWGRP:
798 if (iph1 == NULL) {
799 plog(LLV_ERROR, LOCATION, remote,
800 "Unknown new group mode exchange, "
801 "there is no ISAKMP-SA.\n");
802 return -1;
803 }
804
805 #ifdef ENABLE_FRAG
806 if (isakmp->np == ISAKMP_NPTYPE_FRAG)
807 return frag_handler(iph1, msg, remote, local);
808 #endif
809
810 isakmp_newgroup_r(iph1, msg);
811 break;
812
813 #ifdef ENABLE_HYBRID
814 case ISAKMP_ETYPE_CFG:
815 if (iph1 == NULL) {
816 plog(LLV_ERROR, LOCATION, NULL,
817 "mode config %d from %s, "
818 "but we have no ISAKMP-SA.\n",
819 isakmp->etype, saddr2str(remote));
820 return -1;
821 }
822
823 #ifdef ENABLE_FRAG
824 if (isakmp->np == ISAKMP_NPTYPE_FRAG)
825 return frag_handler(iph1, msg, remote, local);
826 #endif
827
828 isakmp_cfg_r(iph1, msg);
829 break;
830 #endif
831
832 case ISAKMP_ETYPE_NONE:
833 default:
834 plog(LLV_ERROR, LOCATION, NULL,
835 "Invalid exchange type %d from %s.\n",
836 isakmp->etype, saddr2str(remote));
837 return -1;
838 }
839
840 return 0;
841 }
842
843 /*
844 * main function of phase 1.
845 */
846 static int
847 ph1_main(iph1, msg)
848 struct ph1handle *iph1;
849 vchar_t *msg;
850 {
851 int error;
852 int ini_contact = iph1->rmconf->ini_contact;
853 #ifdef ENABLE_STATS
854 struct timeval start, end;
855 #endif
856 int spi_cmp;
857 u_int rekey_lifetime;
858
859 /* ignore a packet */
860 if (iph1->status == PHASE1ST_ESTABLISHED)
861 return 0;
862
863 #ifdef ENABLE_STATS
864 gettimeofday(&start, NULL);
865 #endif
866 /* receive */
867 if (ph1exchange[etypesw1(iph1->etype)]
868 [iph1->side]
869 [iph1->status] == NULL) {
870 IPSECSESSIONTRACEREVENT(iph1->parent_session,
871 IPSECSESSIONEVENTCODE_IKE_PACKET_RX_FAIL,
872 CONSTSTR("unavailable function"),
873 CONSTSTR("Failed to process phase1 message (no state function)"));
874 plog(LLV_ERROR, LOCATION, iph1->remote,
875 "why isn't the function defined.\n");
876 return -1;
877 }
878 error = (ph1exchange[etypesw1(iph1->etype)]
879 [iph1->side]
880 [iph1->status])(iph1, msg);
881 if (error != 0) {
882
883 /* XXX
884 * When an invalid packet is received on phase1, it should
885 * be selected to process this packet. That is to respond
886 * with a notify and delete phase 1 handler, OR not to respond
887 * and keep phase 1 handler. However, in PHASE1ST_START when
888 * acting as RESPONDER we must not keep phase 1 handler or else
889 * it will stay forever.
890 */
891
892 if (iph1->side == RESPONDER && iph1->status == PHASE1ST_START) {
893 plog(LLV_ERROR, LOCATION, iph1->remote,
894 "failed to pre-process packet.\n");
895 return -1;
896 } else {
897 /* ignore the error and keep phase 1 handler */
898 return 0;
899 }
900 }
901
902 #ifndef ENABLE_FRAG
903 /* free resend buffer */
904 if (iph1->sendbuf == NULL) {
905 plog(LLV_ERROR, LOCATION, NULL,
906 "no buffer found as sendbuf\n");
907 return -1;
908 }
909 #endif
910
911 VPTRINIT(iph1->sendbuf);
912
913 /* turn off schedule */
914 SCHED_KILL(iph1->scr);
915
916 /* send */
917 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
918 if ((ph1exchange[etypesw1(iph1->etype)]
919 [iph1->side]
920 [iph1->status])(iph1, msg) != 0) {
921 plog(LLV_ERROR, LOCATION, iph1->remote,
922 "failed to process packet.\n");
923 return -1;
924 }
925
926 #ifdef ENABLE_STATS
927 gettimeofday(&end, NULL);
928 syslog(LOG_NOTICE, "%s(%s): %8.6f",
929 "phase1", s_isakmp_state(iph1->etype, iph1->side, iph1->status),
930 timedelta(&start, &end));
931 #endif
932 if (iph1->status == PHASE1ST_ESTABLISHED) {
933
934 #ifdef ENABLE_STATS
935 gettimeofday(&iph1->end, NULL);
936 syslog(LOG_NOTICE, "%s(%s): %8.6f",
937 "phase1", s_isakmp_etype(iph1->etype),
938 timedelta(&iph1->start, &iph1->end));
939 #endif
940
941 #ifdef ENABLE_VPNCONTROL_PORT
942
943 if (iph1->side == RESPONDER &&
944 iph1->local->sa_family == AF_INET) {
945
946 struct redirect *addr;
947
948 LIST_FOREACH(addr, &lcconf->redirect_addresses, chain) {
949 if (((struct sockaddr_in *)iph1->local)->sin_addr.s_addr == addr->cluster_address) {
950 vchar_t *raddr = vmalloc(sizeof(u_int32_t));
951
952 if (raddr == NULL) {
953 plog(LLV_ERROR, LOCATION, iph1->remote,
954 "failed to send redirect message - memory error.\n");
955 } else {
956 memcpy(raddr->v, &addr->redirect_address, sizeof(u_int32_t));
957 (void)isakmp_info_send_n1(iph1, ISAKMP_NTYPE_LOAD_BALANCE, raddr);
958 plog(LLV_DEBUG, LOCATION, iph1->remote, "sent redirect notification - address = %x.\n", ntohl(addr->redirect_address));
959 vfree(raddr);
960 if (addr->force) {
961 (void)ike_session_update_ph1_ph2tree(iph1);
962 isakmp_ph1delete(iph1);
963 }
964 }
965 }
966 return 0;
967 }
968 }
969 #endif
970 /* save created date. */
971 (void)time(&iph1->created);
972
973 /* add to the schedule to expire, and save back pointer. */
974 iph1->sce = sched_new(iph1->approval->lifetime,
975 isakmp_ph1expire_stub, iph1);
976
977 if (iph1->rmconf->initiate_ph1rekey) {
978 if (iph1->side == INITIATOR) {
979 spi_cmp = memcmp(&iph1->index.i_ck, &iph1->index.r_ck, sizeof(iph1->index.i_ck));
980 if (spi_cmp == 0)
981 spi_cmp = 1;
982 } else {
983 spi_cmp = memcmp(&iph1->index.r_ck, &iph1->index.i_ck, sizeof(iph1->index.r_ck));
984 if (spi_cmp == 0)
985 spi_cmp = -1;
986 }
987 rekey_lifetime = ike_session_get_rekey_lifetime((spi_cmp > 0),
988 iph1->approval->lifetime);
989 if (rekey_lifetime) {
990 iph1->sce_rekey = sched_new(rekey_lifetime,
991 isakmp_ph1rekeyexpire_stub,
992 iph1);
993 } else {
994 /* iph1->approval->lifetime is too small (e.g. 1) so why bother?
995 * LOG ERROR
996 */
997 plog(LLV_ERROR, LOCATION, iph1->remote,
998 "failed to get rekey timer - lifetime is too small... probably.\n");
999 }
1000 }
1001
1002 #ifdef ENABLE_HYBRID
1003 /* ignore xauth if it is a rekey */
1004 if (!iph1->is_rekey &&
1005 iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH) {
1006 switch(AUTHMETHOD(iph1)) {
1007 case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
1008 case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
1009 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
1010 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
1011 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
1012 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
1013 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
1014 xauth_sendreq(iph1);
1015 /* XXX Don't process INITIAL_CONTACT */
1016 ini_contact = 0;
1017 break;
1018 default:
1019 break;
1020 }
1021 }
1022 #endif
1023 #ifdef ENABLE_DPD
1024 /* Schedule the r_u_there.... */
1025 if(iph1->dpd_support && iph1->rmconf->dpd_interval)
1026 isakmp_sched_r_u(iph1, 0);
1027 #endif
1028
1029 /* INITIAL-CONTACT processing */
1030 /* ignore initial-contact if it is a rekey */
1031 /* don't send anything if local test mode. */
1032 if (!iph1->is_rekey && !f_local && ini_contact && !getcontacted(iph1->remote)) {
1033 /* send INITIAL-CONTACT */
1034 isakmp_info_send_n1(iph1,
1035 ISAKMP_NTYPE_INITIAL_CONTACT, NULL);
1036 /* insert a node into contacted list. */
1037 if (inscontacted(iph1->remote) == -1) {
1038 plog(LLV_ERROR, LOCATION, iph1->remote,
1039 "failed to add contacted list.\n");
1040 /* ignore */
1041 }
1042 }
1043
1044 log_ph1established(iph1);
1045 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1046
1047 /*
1048 * SA up shell script hook: do it now for rekeys, otherwise only
1049 * if ISAKMP mode config wasn't requested. In the later
1050 * case it is done when we receive the configuration.
1051 */
1052 if ((iph1->status == PHASE1ST_ESTABLISHED) &&
1053 (iph1->is_rekey || !iph1->rmconf->mode_cfg)) {
1054 switch (AUTHMETHOD(iph1)) {
1055 #ifdef ENABLE_HYBRID
1056 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
1057 case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
1058 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
1059 /* Unimplemeted... */
1060 case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
1061 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
1062 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
1063 case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
1064 break;
1065 #endif
1066 default:
1067 script_hook(iph1, SCRIPT_PHASE1_UP);
1068 break;
1069 }
1070 }
1071
1072 ike_session_cleanup_other_established_ph1s(iph1->parent_session, iph1);
1073
1074 #ifdef ENABLE_VPNCONTROL_PORT
1075 vpncontrol_notify_phase_change(0, FROM_LOCAL, iph1, NULL);
1076 #endif
1077
1078 }
1079
1080 return 0;
1081 }
1082
1083 /*
1084 * main function of quick mode.
1085 */
1086 static int
1087 quick_main(iph2, msg)
1088 struct ph2handle *iph2;
1089 vchar_t *msg;
1090 {
1091 struct isakmp *isakmp = (struct isakmp *)msg->v;
1092 int error;
1093 #ifdef ENABLE_STATS
1094 struct timeval start, end;
1095 #endif
1096
1097 /* ignore a packet */
1098 if (iph2->status == PHASE2ST_ESTABLISHED
1099 || iph2->status == PHASE2ST_GETSPISENT)
1100 return 0;
1101
1102 #ifdef ENABLE_STATS
1103 gettimeofday(&start, NULL);
1104 #endif
1105
1106 /* receive */
1107 if (ph2exchange[etypesw2(isakmp->etype)]
1108 [iph2->side]
1109 [iph2->status] == NULL) {
1110 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1111 "why isn't the function defined.\n");
1112 return -1;
1113 }
1114 error = (ph2exchange[etypesw2(isakmp->etype)]
1115 [iph2->side]
1116 [iph2->status])(iph2, msg);
1117 if (error != 0) {
1118 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1119 "failed to pre-process packet.\n");
1120 if (error == ISAKMP_INTERNAL_ERROR)
1121 return 0;
1122 isakmp_info_send_n1(iph2->ph1, error, NULL);
1123 return -1;
1124 }
1125
1126 /* when using commit bit, status will be reached here. */
1127 //if (iph2->status == PHASE2ST_ADDSA) //%%% BUG FIX - wrong place
1128 // return 0;
1129
1130 /* free resend buffer */
1131 if (iph2->sendbuf == NULL) {
1132 plog(LLV_ERROR, LOCATION, NULL,
1133 "no buffer found as sendbuf\n");
1134 return -1;
1135 }
1136 VPTRINIT(iph2->sendbuf);
1137
1138 /* turn off schedule */
1139 SCHED_KILL(iph2->scr);
1140
1141 /* when using commit bit, status will be reached here. */
1142 if (iph2->status == PHASE2ST_ADDSA) //%%% BUG FIX - moved to here
1143 return 0;
1144
1145 /* send */
1146 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1147 if ((ph2exchange[etypesw2(isakmp->etype)]
1148 [iph2->side]
1149 [iph2->status])(iph2, msg) != 0) {
1150 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1151 "failed to process packet.\n");
1152 return -1;
1153 }
1154
1155 #ifdef ENABLE_STATS
1156 gettimeofday(&end, NULL);
1157 syslog(LOG_NOTICE, "%s(%s): %8.6f",
1158 "phase2",
1159 s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1160 timedelta(&start, &end));
1161 #endif
1162
1163 return 0;
1164 }
1165
1166 /* new negotiation of phase 1 for initiator */
1167 int
1168 isakmp_ph1begin_i(rmconf, remote, local, started_by_api)
1169 struct remoteconf *rmconf;
1170 struct sockaddr *remote, *local;
1171 int started_by_api;
1172 {
1173 struct ph1handle *iph1;
1174 #ifdef ENABLE_STATS
1175 struct timeval start, end;
1176 #endif
1177
1178 /* get new entry to isakmp status table. */
1179 iph1 = newph1();
1180 if (iph1 == NULL)
1181 return -1;
1182
1183 iph1->status = PHASE1ST_START;
1184 iph1->rmconf = rmconf;
1185 #ifdef __APPLE__
1186 if (link_rmconf_to_ph1(rmconf) < 0) {
1187 plog(LLV_ERROR, LOCATION, remote,
1188 "couldn't link "
1189 "configuration.\n");
1190 iph1->rmconf = NULL;
1191 /* don't call remph1(iph1) until after insph1(iph1) is called */
1192 delph1(iph1);
1193 return -1;
1194 }
1195 #endif
1196 iph1->side = INITIATOR;
1197 iph1->started_by_api = started_by_api;
1198 iph1->version = ISAKMP_VERSION_NUMBER;
1199 iph1->msgid = 0;
1200 iph1->flags = 0;
1201 iph1->ph2cnt = 0;
1202 #ifdef HAVE_GSSAPI
1203 iph1->gssapi_state = NULL;
1204 #endif
1205 #ifdef ENABLE_HYBRID
1206 if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
1207 /* don't call remph1(iph1) until after insph1(iph1) is called */
1208 delph1(iph1);
1209 return -1;
1210 }
1211 #endif
1212 #ifdef ENABLE_FRAG
1213
1214 if(rmconf->ike_frag == ISAKMP_FRAG_FORCE)
1215 iph1->frag = 1;
1216 else
1217 iph1->frag = 0;
1218 iph1->frag_chain = NULL;
1219 #endif
1220 iph1->approval = NULL;
1221
1222 /* XXX copy remote address */
1223 if (copy_ph1addresses(iph1, rmconf, remote, local) < 0) {
1224 /* don't call remph1(iph1) until after insph1(iph1) is called */
1225 iph1 = NULL; /* deleted in copy_ph1addresses */
1226 return -1;
1227 }
1228
1229 (void)insph1(iph1);
1230
1231 if (ike_session_link_ph1_to_session(iph1) != 0) {
1232 plog(LLV_DEBUG, LOCATION, NULL, "Failed to link ph1 to session\n");
1233 remph1(iph1);
1234 delph1(iph1);
1235 return -1;
1236 }
1237
1238 /* start phase 1 exchange */
1239 iph1->etype = rmconf->etypes->type;
1240
1241 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1242 {
1243 char *a;
1244
1245 a = racoon_strdup(saddr2str(iph1->local));
1246 STRDUP_FATAL(a);
1247
1248 plog(LLV_INFO, LOCATION, NULL,
1249 "initiate new phase 1 negotiation: %s<=>%s\n",
1250 a, saddr2str(iph1->remote));
1251 racoon_free(a);
1252 }
1253 plog(LLV_INFO, LOCATION, NULL,
1254 "begin %s mode.\n",
1255 s_isakmp_etype(iph1->etype));
1256
1257 #ifdef ENABLE_STATS
1258 gettimeofday(&iph1->start, NULL);
1259 gettimeofday(&start, NULL);
1260 #endif
1261 /* start exchange */
1262 if ((ph1exchange[etypesw1(iph1->etype)]
1263 [iph1->side]
1264 [iph1->status])(iph1, NULL) != 0) {
1265 /* failed to start phase 1 negotiation */
1266 remph1(iph1);
1267 delph1(iph1);
1268
1269 return -1;
1270 }
1271
1272 #ifdef ENABLE_STATS
1273 gettimeofday(&end, NULL);
1274 syslog(LOG_NOTICE, "%s(%s): %8.6f",
1275 "phase1",
1276 s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1277 timedelta(&start, &end));
1278 #endif
1279
1280 #ifdef ENABLE_VPNCONTROL_PORT
1281 vpncontrol_notify_phase_change(1, FROM_LOCAL, iph1, NULL);
1282 #endif
1283
1284
1285 return 0;
1286 }
1287
1288 /* new negotiation of phase 1 for responder */
1289 static int
1290 isakmp_ph1begin_r(msg, remote, local, etype)
1291 vchar_t *msg;
1292 struct sockaddr *remote, *local;
1293 u_int8_t etype;
1294 {
1295 struct isakmp *isakmp = (struct isakmp *)msg->v;
1296 struct remoteconf *rmconf;
1297 struct ph1handle *iph1;
1298 struct etypes *etypeok;
1299 #ifdef ENABLE_STATS
1300 struct timeval start, end;
1301 #endif
1302
1303 /* look for my configuration */
1304 rmconf = getrmconf(remote);
1305 if (rmconf == NULL) {
1306 plog(LLV_ERROR, LOCATION, remote,
1307 "couldn't find "
1308 "configuration.\n");
1309 return -1;
1310 }
1311
1312 /* check to be acceptable exchange type */
1313 etypeok = check_etypeok(rmconf, etype);
1314 if (etypeok == NULL) {
1315 plog(LLV_ERROR, LOCATION, remote,
1316 "not acceptable %s mode\n", s_isakmp_etype(etype));
1317 return -1;
1318 }
1319
1320 /* get new entry to isakmp status table. */
1321 iph1 = newph1();
1322 if (iph1 == NULL)
1323 return -1;
1324
1325 memcpy(&iph1->index.i_ck, &isakmp->i_ck, sizeof(iph1->index.i_ck));
1326 iph1->status = PHASE1ST_START;
1327 iph1->rmconf = rmconf;
1328 #ifdef __APPLE__
1329 if (link_rmconf_to_ph1(rmconf) < 0) {
1330 plog(LLV_ERROR, LOCATION, remote,
1331 "couldn't link "
1332 "configuration.\n");
1333 iph1->rmconf = NULL;
1334 /* don't call remph1(iph1) until after insph1(iph1) is called */
1335 delph1(iph1);
1336 return -1;
1337 }
1338 #endif
1339 iph1->flags = 0;
1340 iph1->side = RESPONDER;
1341 iph1->started_by_api = 0;
1342 iph1->etype = etypeok->type;
1343 iph1->version = isakmp->v;
1344 iph1->msgid = 0;
1345 #ifdef HAVE_GSSAPI
1346 iph1->gssapi_state = NULL;
1347 #endif
1348 #ifdef ENABLE_HYBRID
1349 if ((iph1->mode_cfg = isakmp_cfg_mkstate()) == NULL) {
1350 /* don't call remph1(iph1) until after insph1(iph1) is called */
1351 delph1(iph1);
1352 return -1;
1353 }
1354 #endif
1355 #ifdef ENABLE_FRAG
1356 iph1->frag = 0;
1357 iph1->frag_chain = NULL;
1358 #endif
1359 iph1->approval = NULL;
1360
1361 #ifdef ENABLE_NATT
1362 /* RFC3947 says that we MUST accept new phases1 on NAT-T floated port.
1363 * We have to setup this flag now to correctly generate the first reply.
1364 * Don't know if a better check could be done for that ?
1365 */
1366 if(extract_port(local) == lcconf->port_isakmp_natt)
1367 iph1->natt_flags |= (NAT_PORTS_CHANGED);
1368 #endif
1369
1370 /* copy remote address */
1371 if (copy_ph1addresses(iph1, rmconf, remote, local) < 0) {
1372 /* don't call remph1(iph1) until after insph1(iph1) is called */
1373 iph1 = NULL; /* deleted in copy_ph1addresses */
1374 return -1;
1375 }
1376 (void)insph1(iph1);
1377
1378 if (ike_session_link_ph1_to_session(iph1) != 0) {
1379 remph1(iph1);
1380 delph1(iph1);
1381 return -1;
1382 }
1383
1384 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1385 {
1386 char *a;
1387
1388 a = racoon_strdup(saddr2str(iph1->local));
1389 STRDUP_FATAL(a);
1390
1391 plog(LLV_INFO, LOCATION, NULL,
1392 "respond new phase 1 negotiation: %s<=>%s\n",
1393 a, saddr2str(iph1->remote));
1394 racoon_free(a);
1395 }
1396 plog(LLV_INFO, LOCATION, NULL,
1397 "begin %s mode.\n", s_isakmp_etype(etype));
1398
1399 #ifdef ENABLE_STATS
1400 gettimeofday(&iph1->start, NULL);
1401 gettimeofday(&start, NULL);
1402 #endif
1403
1404 #ifndef ENABLE_FRAG
1405
1406 /* start exchange */
1407 if ((ph1exchange[etypesw1(iph1->etype)]
1408 [iph1->side]
1409 [iph1->status])(iph1, msg) < 0
1410 || (ph1exchange[etypesw1(iph1->etype)]
1411 [iph1->side]
1412 [iph1->status])(iph1, msg) < 0) {
1413 plog(LLV_ERROR, LOCATION, remote,
1414 "failed to process packet.\n");
1415 remph1(iph1);
1416 delph1(iph1);
1417 return -1;
1418 }
1419
1420 #ifdef ENABLE_STATS
1421 gettimeofday(&end, NULL);
1422 syslog(LOG_NOTICE, "%s(%s): %8.6f",
1423 "phase1",
1424 s_isakmp_state(iph1->etype, iph1->side, iph1->status),
1425 timedelta(&start, &end));
1426 #endif
1427 #ifdef ENABLE_VPNCONTROL_PORT
1428 vpncontrol_notify_phase_change(1, FROM_REMOTE, iph1, NULL);
1429 #endif
1430
1431 return 0;
1432
1433 #else /* ENABLE_FRAG */
1434
1435 /* now that we have a phase1 handle, feed back into our
1436 * main receive function to catch fragmented packets
1437 */
1438
1439 return isakmp_main(msg, remote, local);
1440
1441 #endif /* ENABLE_FRAG */
1442
1443 }
1444
1445 /* new negotiation of phase 2 for initiator */
1446 static int
1447 isakmp_ph2begin_i(iph1, iph2)
1448 struct ph1handle *iph1;
1449 struct ph2handle *iph2;
1450 {
1451 #ifdef ENABLE_HYBRID
1452 if (xauth_check(iph1) != 0) {
1453 plog(LLV_ERROR, LOCATION, NULL,
1454 "Attempt to start phase 2 whereas Xauth failed\n");
1455 return -1;
1456 }
1457 #endif
1458
1459 /* found ISAKMP-SA. */
1460 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1461 plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
1462 {
1463 char *a;
1464 a = racoon_strdup(saddr2str(iph2->src));
1465 STRDUP_FATAL(a);
1466
1467 plog(LLV_INFO, LOCATION, NULL,
1468 "initiate new phase 2 negotiation: %s<=>%s\n",
1469 a, saddr2str(iph2->dst));
1470 racoon_free(a);
1471 }
1472
1473 #ifdef ENABLE_STATS
1474 gettimeofday(&iph2->start, NULL);
1475 #endif
1476 /* found isakmp-sa */
1477 if (iph2->ph1 && iph1 != iph2->ph1) {
1478 plog(LLV_DEBUG2, LOCATION, NULL, "phase2 already bound in %s.\n",__FUNCTION__);
1479 rebindph12(iph1, iph2);
1480 } else if (!iph2->ph1) {
1481 bindph12(iph1, iph2);
1482 }
1483 iph2->is_dying = 0;
1484 if (ike_session_link_ph2_to_session(iph2) != 0) {
1485 return -1;
1486 }
1487 iph2->status = PHASE2ST_STATUS2;
1488
1489 if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1490 [iph2->side]
1491 [iph2->status])(iph2, NULL) < 0) {
1492 return -1;
1493 }
1494
1495 #ifdef ENABLE_VPNCONTROL_PORT
1496 vpncontrol_notify_phase_change(1, FROM_LOCAL, NULL, iph2);
1497 #endif
1498
1499 return 0;
1500 }
1501
1502 /* new negotiation of phase 2 for responder */
1503 static int
1504 isakmp_ph2begin_r(iph1, msg)
1505 struct ph1handle *iph1;
1506 vchar_t *msg;
1507 {
1508 struct isakmp *isakmp = (struct isakmp *)msg->v;
1509 struct ph2handle *iph2 = 0;
1510 int error;
1511 #ifdef ENABLE_STATS
1512 struct timeval start, end;
1513 #endif
1514 #ifdef ENABLE_HYBRID
1515 if (xauth_check(iph1) != 0) {
1516 plog(LLV_ERROR, LOCATION, NULL,
1517 "Attempt to start phase 2 whereas Xauth failed\n");
1518 return -1;
1519 }
1520 #endif
1521
1522 iph2 = newph2();
1523 if (iph2 == NULL) {
1524 plog(LLV_ERROR, LOCATION, NULL,
1525 "failed to allocate phase2 entry.\n");
1526 return -1;
1527 }
1528
1529 iph2->ph1 = iph1;
1530 iph2->side = RESPONDER;
1531 iph2->status = PHASE2ST_START;
1532 iph2->flags = isakmp->flags;
1533 iph2->msgid = isakmp->msgid;
1534 iph2->seq = pk_getseq();
1535 iph2->ivm = oakley_newiv2(iph1, iph2->msgid);
1536 if (iph2->ivm == NULL) {
1537 delph2(iph2);
1538 return -1;
1539 }
1540 iph2->dst = dupsaddr(iph1->remote); /* XXX should be considered */
1541 if (iph2->dst == NULL) {
1542 delph2(iph2);
1543 return -1;
1544 }
1545 switch (iph2->dst->sa_family) {
1546 case AF_INET:
1547 #ifndef ENABLE_NATT
1548 ((struct sockaddr_in *)iph2->dst)->sin_port = 0;
1549 #endif
1550 break;
1551 #ifdef INET6
1552 case AF_INET6:
1553 #ifndef ENABLE_NATT
1554 ((struct sockaddr_in6 *)iph2->dst)->sin6_port = 0;
1555 #endif
1556 break;
1557 #endif
1558 default:
1559 plog(LLV_ERROR, LOCATION, NULL,
1560 "invalid family: %d\n", iph2->dst->sa_family);
1561 delph2(iph2);
1562 return -1;
1563 }
1564
1565 iph2->src = dupsaddr(iph1->local); /* XXX should be considered */
1566 if (iph2->src == NULL) {
1567 delph2(iph2);
1568 return -1;
1569 }
1570 switch (iph2->src->sa_family) {
1571 case AF_INET:
1572 #ifndef ENABLE_NATT
1573 ((struct sockaddr_in *)iph2->src)->sin_port = 0;
1574 #endif
1575 break;
1576 #ifdef INET6
1577 case AF_INET6:
1578 #ifndef ENABLE_NATT
1579 ((struct sockaddr_in6 *)iph2->src)->sin6_port = 0;
1580 #endif
1581 break;
1582 #endif
1583 default:
1584 plog(LLV_ERROR, LOCATION, NULL,
1585 "invalid family: %d\n", iph2->src->sa_family);
1586 delph2(iph2);
1587 return -1;
1588 }
1589
1590 /* add new entry to isakmp status table */
1591 insph2(iph2);
1592 bindph12(iph1, iph2);
1593 iph2->is_dying = 0;
1594 if (ike_session_link_ph2_to_session(iph2) != 0) {
1595 unbindph12(iph2);
1596 remph2(iph2);
1597 delph2(iph2);
1598 return -1;
1599 }
1600
1601 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1602 {
1603 char *a;
1604
1605 a = racoon_strdup(saddr2str(iph2->src));
1606 STRDUP_FATAL(a);
1607
1608 plog(LLV_INFO, LOCATION, NULL,
1609 "respond new phase 2 negotiation: %s<=>%s\n",
1610 a, saddr2str(iph2->dst));
1611 racoon_free(a);
1612 }
1613
1614 #ifdef ENABLE_STATS
1615 gettimeofday(&start, NULL);
1616 #endif
1617
1618 error = (ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
1619 [iph2->side]
1620 [iph2->status])(iph2, msg);
1621 if (error != 0) {
1622 plog(LLV_ERROR, LOCATION, iph1->remote,
1623 "failed to pre-process packet.\n");
1624 if (error != ISAKMP_INTERNAL_ERROR)
1625 isakmp_info_send_n1(iph2->ph1, error, NULL);
1626 /*
1627 * release handler because it's wrong that ph2handle is kept
1628 * after failed to check message for responder's.
1629 */
1630 unbindph12(iph2);
1631 remph2(iph2);
1632 delph2(iph2);
1633 return -1;
1634 }
1635
1636 /* send */
1637 plog(LLV_DEBUG, LOCATION, NULL, "===\n");
1638 if ((ph2exchange[etypesw2(isakmp->etype)]
1639 [iph2->side]
1640 [iph2->status])(iph2, msg) < 0) {
1641 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
1642 "failed to process packet.\n");
1643 /* don't release handler */
1644 return -1;
1645 }
1646 #ifdef ENABLE_STATS
1647 gettimeofday(&end, NULL);
1648 syslog(LOG_NOTICE, "%s(%s): %8.6f",
1649 "phase2",
1650 s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
1651 timedelta(&start, &end));
1652 #endif
1653
1654 #ifdef ENABLE_VPNCONTROL_PORT
1655 vpncontrol_notify_phase_change(1, FROM_REMOTE, NULL, iph2);
1656 #endif
1657
1658
1659 return 0;
1660 }
1661
1662 /*
1663 * parse ISAKMP payloads, without ISAKMP base header.
1664 */
1665 vchar_t *
1666 isakmp_parsewoh(np0, gen, len)
1667 int np0;
1668 struct isakmp_gen *gen;
1669 int len;
1670 {
1671 u_char np = np0 & 0xff;
1672 int tlen, plen;
1673 vchar_t *result;
1674 struct isakmp_parse_t *p, *ep;
1675
1676 plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
1677
1678 /*
1679 * 5 is a magic number, but any value larger than 2 should be fine
1680 * as we do vrealloc() in the following loop.
1681 */
1682 result = vmalloc(sizeof(struct isakmp_parse_t) * 5);
1683 if (result == NULL) {
1684 plog(LLV_ERROR, LOCATION, NULL,
1685 "failed to get buffer.\n");
1686 return NULL;
1687 }
1688 p = (struct isakmp_parse_t *)result->v;
1689 ep = (struct isakmp_parse_t *)(result->v + result->l - sizeof(*ep));
1690
1691 tlen = len;
1692
1693 /* parse through general headers */
1694 while (0 < tlen && np != ISAKMP_NPTYPE_NONE) {
1695 if (tlen <= sizeof(struct isakmp_gen)) {
1696 /* don't send information, see isakmp_ident_r1() */
1697 plog(LLV_ERROR, LOCATION, NULL,
1698 "invalid length of payload\n");
1699 vfree(result);
1700 return NULL;
1701 }
1702
1703 plog(LLV_DEBUG, LOCATION, NULL,
1704 "seen nptype=%u(%s)\n", np, s_isakmp_nptype(np));
1705
1706 p->type = np;
1707 p->len = ntohs(gen->len);
1708 if (p->len < sizeof(struct isakmp_gen) || p->len > tlen) {
1709 plog(LLV_DEBUG, LOCATION, NULL,
1710 "invalid length of payload\n");
1711 vfree(result);
1712 return NULL;
1713 }
1714 p->ptr = gen;
1715 p++;
1716 if (ep <= p) {
1717 int off;
1718
1719 off = p - (struct isakmp_parse_t *)result->v;
1720 result = vrealloc(result, result->l * 2);
1721 if (result == NULL) {
1722 plog(LLV_DEBUG, LOCATION, NULL,
1723 "failed to realloc buffer.\n");
1724 vfree(result);
1725 return NULL;
1726 }
1727 ep = (struct isakmp_parse_t *)
1728 (result->v + result->l - sizeof(*ep));
1729 p = (struct isakmp_parse_t *)result->v;
1730 p += off;
1731 }
1732
1733 np = gen->np;
1734 plen = ntohs(gen->len);
1735 gen = (struct isakmp_gen *)((caddr_t)gen + plen);
1736 tlen -= plen;
1737 }
1738 p->type = ISAKMP_NPTYPE_NONE;
1739 p->len = 0;
1740 p->ptr = NULL;
1741
1742 plog(LLV_DEBUG, LOCATION, NULL, "succeed.\n");
1743
1744 return result;
1745 }
1746
1747 /*
1748 * parse ISAKMP payloads, including ISAKMP base header.
1749 */
1750 vchar_t *
1751 isakmp_parse(buf)
1752 vchar_t *buf;
1753 {
1754 struct isakmp *isakmp = (struct isakmp *)buf->v;
1755 struct isakmp_gen *gen;
1756 int tlen;
1757 vchar_t *result;
1758 u_char np;
1759
1760 np = isakmp->np;
1761 gen = (struct isakmp_gen *)(buf->v + sizeof(*isakmp));
1762 tlen = buf->l - sizeof(struct isakmp);
1763 result = isakmp_parsewoh(np, gen, tlen);
1764
1765 return result;
1766 }
1767
1768 /* %%% */
1769 #ifndef __APPLE__
1770 int
1771 isakmp_init()
1772 {
1773 /* initialize a isakmp status table */
1774 initph1tree();
1775 initph2tree();
1776 initctdtree();
1777 init_recvdpkt();
1778
1779 if (isakmp_open() < 0)
1780 goto err;
1781
1782 return(0);
1783
1784 err:
1785 isakmp_close();
1786 return(-1);
1787 }
1788 #else
1789 int
1790 isakmp_init(int ignore_phX)
1791 {
1792 /* initialize a isakmp status table */
1793 if (!ignore_phX) {
1794 initph1tree();
1795 initph2tree();
1796 }
1797 initctdtree();
1798 init_recvdpkt();
1799
1800 if (isakmp_open() < 0)
1801 goto err;
1802
1803 return(0);
1804
1805 err:
1806 isakmp_close();
1807 return(-1);
1808 }
1809 #endif /* __APPLE__ */
1810
1811 void
1812 isakmp_cleanup()
1813 {
1814 clear_recvdpkt();
1815 clear_contacted();
1816 }
1817
1818 /*
1819 * make strings containing i_cookie + r_cookie + msgid
1820 */
1821 const char *
1822 isakmp_pindex(index, msgid)
1823 const isakmp_index *index;
1824 const u_int32_t msgid;
1825 {
1826 static char buf[64];
1827 const u_char *p;
1828 int i, j;
1829
1830 memset(buf, 0, sizeof(buf));
1831
1832 /* copy index */
1833 p = (const u_char *)index;
1834 for (j = 0, i = 0; i < sizeof(isakmp_index); i++) {
1835 snprintf((char *)&buf[j], sizeof(buf) - j, "%02x", p[i]);
1836 j += 2;
1837 switch (i) {
1838 case 7:
1839 buf[j++] = ':';
1840 }
1841 }
1842
1843 if (msgid == 0)
1844 return buf;
1845
1846 /* copy msgid */
1847 snprintf((char *)&buf[j], sizeof(buf) - j, ":%08x", ntohs(msgid));
1848
1849 return buf;
1850 }
1851
1852 /* open ISAKMP sockets. */
1853 int
1854 isakmp_open()
1855 {
1856 const int yes = 1;
1857 int ifnum = 0, encap_ifnum = 0;
1858 #ifdef INET6
1859 int pktinfo;
1860 #endif
1861 struct myaddrs *p;
1862
1863 for (p = lcconf->myaddrs; p; p = p->next) {
1864 if (!p->addr)
1865 continue;
1866
1867 #ifdef __APPLE__
1868 if (p->sock != -1) {
1869 ifnum++;
1870 if (p->udp_encap)
1871 encap_ifnum++;
1872 continue; // socket already open
1873 }
1874 #endif
1875
1876 /* warn if wildcard address - should we forbid this? */
1877 switch (p->addr->sa_family) {
1878 case AF_INET:
1879 if (((struct sockaddr_in *)p->addr)->sin_addr.s_addr == 0)
1880 plog(LLV_WARNING, LOCATION, NULL,
1881 "listening to wildcard address,"
1882 "broadcast IKE packet may kill you\n");
1883 break;
1884 #ifdef INET6
1885 case AF_INET6:
1886 if (IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)p->addr)->sin6_addr))
1887 plog(LLV_WARNING, LOCATION, NULL,
1888 "listening to wildcard address, "
1889 "broadcast IKE packet may kill you\n");
1890 break;
1891 #endif
1892 default:
1893 plog(LLV_ERROR, LOCATION, NULL,
1894 "unsupported address family %d\n",
1895 lcconf->default_af);
1896 goto err_and_next;
1897 }
1898
1899 #ifdef INET6
1900 if (p->addr->sa_family == AF_INET6 &&
1901 IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)
1902 p->addr)->sin6_addr))
1903 {
1904 plog(LLV_DEBUG, LOCATION, NULL,
1905 "Ignoring multicast address %s\n",
1906 saddr2str(p->addr));
1907 racoon_free(p->addr);
1908 p->addr = NULL;
1909 continue;
1910 }
1911 #endif
1912
1913 if ((p->sock = socket(p->addr->sa_family, SOCK_DGRAM, 0)) < 0) {
1914 plog(LLV_ERROR, LOCATION, NULL,
1915 "socket (%s)\n", strerror(errno));
1916 goto err_and_next;
1917 }
1918
1919 if (fcntl(p->sock, F_SETFL, O_NONBLOCK) == -1)
1920 plog(LLV_WARNING, LOCATION, NULL,
1921 "failed to put socket in non-blocking mode\n");
1922
1923 /* receive my interface address on inbound packets. */
1924 switch (p->addr->sa_family) {
1925 case AF_INET:
1926 if (setsockopt(p->sock, IPPROTO_IP,
1927 #ifdef __linux__
1928 IP_PKTINFO,
1929 #else
1930 IP_RECVDSTADDR,
1931 #endif
1932 (const void *)&yes, sizeof(yes)) < 0) {
1933 plog(LLV_ERROR, LOCATION, NULL,
1934 "setsockopt IP_RECVDSTADDR (%s)\n",
1935 strerror(errno));
1936 goto err_and_next;
1937 }
1938 break;
1939 #ifdef INET6
1940 case AF_INET6:
1941 #ifdef INET6_ADVAPI
1942 #ifdef IPV6_RECVPKTINFO
1943 pktinfo = IPV6_RECVPKTINFO;
1944 #else /* old adv. API */
1945 pktinfo = IPV6_PKTINFO;
1946 #endif /* IPV6_RECVPKTINFO */
1947 #else
1948 pktinfo = IPV6_RECVDSTADDR;
1949 #endif
1950 if (setsockopt(p->sock, IPPROTO_IPV6, pktinfo,
1951 (const void *)&yes, sizeof(yes)) < 0)
1952 {
1953 plog(LLV_ERROR, LOCATION, NULL,
1954 "setsockopt IPV6_RECVDSTADDR (%d):%s\n",
1955 pktinfo, strerror(errno));
1956 goto err_and_next;
1957 }
1958 break;
1959 #endif
1960 }
1961
1962 #ifdef IPV6_USE_MIN_MTU
1963 if (p->addr->sa_family == AF_INET6 &&
1964 setsockopt(p->sock, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
1965 (void *)&yes, sizeof(yes)) < 0) {
1966 plog(LLV_ERROR, LOCATION, NULL,
1967 "setsockopt IPV6_USE_MIN_MTU (%s)\n",
1968 strerror(errno));
1969 return -1;
1970 }
1971 #endif
1972
1973 if (setsockopt_bypass(p->sock, p->addr->sa_family) < 0)
1974 goto err_and_next;
1975
1976 #ifdef __APPLE__
1977 if (extract_port(p->addr) == PORT_ISAKMP) {
1978 if (setsockopt(p->sock, SOL_SOCKET, SO_NOTIFYCONFLICT,
1979 (void *)&yes, sizeof(yes)) < 0) {
1980 plog(LLV_ERROR, LOCATION, p->addr,
1981 "setsockopt (%s)\n", strerror(errno));
1982 goto err_and_next;
1983 }
1984 }
1985 #endif
1986
1987 if (bind(p->sock, p->addr, sysdep_sa_len(p->addr)) < 0) {
1988 plog(LLV_ERROR, LOCATION, p->addr,
1989 "failed to bind to address %s (%s).\n",
1990 saddr2str(p->addr), strerror(errno));
1991 close(p->sock);
1992 p->sock = -1;
1993 goto err_and_next;
1994 }
1995
1996 ifnum++;
1997 #ifdef __APPLE__
1998 if (p->udp_encap)
1999 encap_ifnum++;
2000 #endif
2001
2002 plog(LLV_INFO, LOCATION, NULL,
2003 "%s used as isakmp port (fd=%d)\n",
2004 saddr2str(p->addr), p->sock);
2005
2006 #ifndef __APPLE__
2007 #ifdef ENABLE_NATT
2008 if (p->addr->sa_family == AF_INET) {
2009 int option = -1;
2010
2011 if(p->udp_encap)
2012 option = UDP_ENCAP_ESPINUDP;
2013 #if defined(ENABLE_NATT_00) || defined(ENABLE_NATT_01)
2014 else
2015 option = UDP_ENCAP_ESPINUDP_NON_IKE;
2016 #endif
2017 if(option != -1){
2018 if (setsockopt (p->sock, SOL_UDP,
2019 UDP_ENCAP, &option, sizeof (option)) < 0) {
2020 plog(LLV_WARNING, LOCATION, NULL,
2021 "setsockopt(%s): UDP_ENCAP %s\n",
2022 option == UDP_ENCAP_ESPINUDP ? "UDP_ENCAP_ESPINUDP" : "UDP_ENCAP_ESPINUDP_NON_IKE",
2023 strerror(errno));
2024 goto skip_encap;
2025 }
2026 else {
2027 plog(LLV_INFO, LOCATION, NULL,
2028 "%s used for NAT-T\n",
2029 saddr2str(p->addr));
2030 encap_ifnum++;
2031 }
2032 }
2033 }
2034 skip_encap:
2035 #endif
2036 #endif /* __APPLE__ */
2037
2038 continue;
2039
2040 err_and_next:
2041 racoon_free(p->addr);
2042 p->addr = NULL;
2043 if (! lcconf->autograbaddr && lcconf->strict_address)
2044 return -1;
2045 continue;
2046 }
2047
2048 if (!ifnum) {
2049 plog(LLV_ERROR, LOCATION, NULL,
2050 "no address could be bound.\n");
2051 return -1;
2052 }
2053
2054 #ifdef ENABLE_NATT
2055 if (natt_enabled_in_rmconf() && !encap_ifnum) {
2056 plog(LLV_WARNING, LOCATION, NULL,
2057 "NAT-T is enabled in at least one remote{} section,\n");
2058 plog(LLV_WARNING, LOCATION, NULL,
2059 "but no 'isakmp_natt' address was specified!\n");
2060 }
2061 #endif
2062
2063 return 0;
2064 }
2065
2066 void
2067 isakmp_close()
2068 {
2069 isakmp_close_sockets();
2070 clear_myaddr();
2071 }
2072
2073 void
2074 isakmp_close_sockets()
2075 {
2076 struct myaddrs *p;
2077
2078 for (p = lcconf->myaddrs; p; p = p->next) {
2079
2080 if (!p->addr)
2081 continue;
2082
2083 if (p->sock >= 0) {
2084 close(p->sock);
2085 p->sock = -1;
2086 }
2087 }
2088
2089 }
2090
2091
2092 // close sockets for addresses that have gone away
2093 void
2094 isakmp_close_unused()
2095 {
2096 struct myaddrs *p, *next, **prev;
2097
2098 prev = &(lcconf->myaddrs);
2099 for (p = lcconf->myaddrs; p; p = next) {
2100 next = p->next;
2101 if (p->in_use == 0) { // not in use ?
2102
2103 if (p->sock >= 0)
2104 close(p->sock);
2105 *prev = p->next;
2106 delmyaddr(p);
2107 } else
2108 prev = &(p->next);
2109 }
2110 }
2111
2112 int
2113 isakmp_send(iph1, sbuf)
2114 struct ph1handle *iph1;
2115 vchar_t *sbuf;
2116 {
2117 int len = 0;
2118 int s;
2119 vchar_t *vbuf = NULL;
2120
2121 #ifdef ENABLE_NATT
2122 size_t extralen = NON_ESP_MARKER_USE(iph1) ? NON_ESP_MARKER_LEN : 0;
2123
2124 #ifdef ENABLE_FRAG
2125 /*
2126 * Do not add the non ESP marker for a packet that will
2127 * be fragmented. The non ESP marker should appear in
2128 * all fragment's packets, but not in the fragmented packet
2129 */
2130 if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN)
2131 extralen = 0;
2132 #endif
2133 if (extralen)
2134 plog (LLV_DEBUG, LOCATION, NULL, "Adding NON-ESP marker\n");
2135
2136 /* If NAT-T port floating is in use, 4 zero bytes (non-ESP marker)
2137 must added just before the packet itself. For this we must
2138 allocate a new buffer and release it at the end. */
2139 if (extralen) {
2140 if ((vbuf = vmalloc (sbuf->l + extralen)) == NULL) {
2141 plog(LLV_ERROR, LOCATION, NULL,
2142 "vbuf allocation failed\n");
2143 return -1;
2144 }
2145 *(u_int32_t *)vbuf->v = 0;
2146 memcpy (vbuf->v + extralen, sbuf->v, sbuf->l);
2147 sbuf = vbuf;
2148 }
2149 #endif
2150
2151 /* select the socket to be sent */
2152 s = getsockmyaddr(iph1->local);
2153 if (s == -1){
2154 if ( vbuf != NULL )
2155 vfree(vbuf);
2156 return -1;
2157 }
2158
2159 plog (LLV_DEBUG, LOCATION, NULL, "%zu bytes %s\n", sbuf->l,
2160 saddr2str_fromto("from %s to %s", iph1->local, iph1->remote));
2161
2162 #ifdef ENABLE_FRAG
2163 if (iph1->frag && sbuf->l > ISAKMP_FRAG_MAXLEN) {
2164 if (isakmp_sendfrags(iph1, sbuf) == -1) {
2165 plog(LLV_ERROR, LOCATION, NULL,
2166 "isakmp_sendfrags failed\n");
2167 if ( vbuf != NULL )
2168 vfree(vbuf);
2169 return -1;
2170 }
2171 } else
2172 #endif
2173 {
2174 len = sendfromto(s, sbuf->v, sbuf->l,
2175 iph1->local, iph1->remote, lcconf->count_persend);
2176 if (len == -1) {
2177 plog(LLV_ERROR, LOCATION, NULL, "sendfromto failed\n");
2178 if ( vbuf != NULL )
2179 vfree(vbuf);
2180 return -1;
2181 }
2182 }
2183
2184 if ( vbuf != NULL )
2185 vfree(vbuf);
2186
2187 return 0;
2188 }
2189
2190 /* called from scheduler */
2191 void
2192 isakmp_ph1resend_stub(p)
2193 void *p;
2194 {
2195 struct ph1handle *iph1;
2196
2197 iph1=(struct ph1handle *)p;
2198 if(isakmp_ph1resend(iph1) < 0){
2199 if(iph1->scr != NULL){
2200 /* Should not happen...
2201 */
2202 sched_kill(iph1->scr);
2203 iph1->scr=NULL;
2204 }
2205
2206 remph1(iph1);
2207 delph1(iph1);
2208 }
2209 }
2210
2211 int
2212 isakmp_ph1resend(iph1)
2213 struct ph1handle *iph1;
2214 {
2215 /* Note: NEVER do the rem/del here, it will be done by the caller or by the _stub function
2216 */
2217 if (iph1->retry_counter <= 0) {
2218 IPSECSESSIONTRACEREVENT(iph1->parent_session,
2219 IPSECSESSIONEVENTCODE_IKEV1_PH1_MAX_RETRANSMIT,
2220 CONSTSTR("Phase1 Maximum Retransmits"),
2221 CONSTSTR("Phase1 negotiation failed (Maximum retransmits)"));
2222
2223 plog(LLV_ERROR, LOCATION, NULL,
2224 "phase1 negotiation failed due to time up. %s\n",
2225 isakmp_pindex(&iph1->index, iph1->msgid));
2226 EVT_PUSH(iph1->local, iph1->remote,
2227 EVTT_PEER_NO_RESPONSE, NULL);
2228 if (iph1->side == INITIATOR && iph1->is_rekey && iph1->parent_session && iph1->parent_session->is_client) {
2229 /* to get around a bug on the peer, in which rekeys to port 4500 are dropped */
2230 if (isakmp_ph1rekeyretry(iph1) == 0)
2231 return 0;
2232 }
2233 return -1;
2234 }
2235
2236 if (isakmp_send(iph1, iph1->sendbuf) < 0){
2237 if (iph1->rmconf->retry_counter != iph1->retry_counter) {
2238 IPSECSESSIONTRACEREVENT(iph1->parent_session,
2239 IPSECSESSIONEVENTCODE_IKE_PACKET_TX_FAIL,
2240 CONSTSTR("Phase1 Retransmit"),
2241 CONSTSTR("Failed to retrasmit Phase1"));
2242 }
2243 plog(LLV_ERROR, LOCATION, iph1->remote,
2244 "phase1 negotiation failed due to send error. %s\n",
2245 isakmp_pindex(&iph1->index, iph1->msgid));
2246 EVT_PUSH(iph1->local, iph1->remote,
2247 EVTT_PEER_NO_RESPONSE, NULL);
2248 return -1;
2249 }
2250
2251 if (iph1->rmconf->retry_counter != iph1->retry_counter) {
2252 IPSECSESSIONTRACEREVENT(iph1->parent_session,
2253 IPSECSESSIONEVENTCODE_IKE_PACKET_TX_SUCC,
2254 CONSTSTR("Phase1 Retransmit"),
2255 CONSTSTR(NULL));
2256 }
2257
2258 plog(LLV_DEBUG, LOCATION, iph1->remote,
2259 "resend phase1 packet %s\n",
2260 isakmp_pindex(&iph1->index, iph1->msgid));
2261
2262 iph1->retry_counter--;
2263
2264 iph1->scr = sched_new(iph1->rmconf->retry_interval,
2265 isakmp_ph1resend_stub, iph1);
2266
2267 return 0;
2268 }
2269
2270 /* called from scheduler */
2271 void
2272 isakmp_ph2resend_stub(p)
2273 void *p;
2274 {
2275 struct ph2handle *iph2;
2276
2277 iph2=(struct ph2handle *)p;
2278
2279 if(isakmp_ph2resend(iph2) < 0){
2280 unbindph12(iph2);
2281 remph2(iph2);
2282 delph2(iph2);
2283 }
2284 }
2285
2286 int
2287 isakmp_ph2resend(iph2)
2288 struct ph2handle *iph2;
2289 {
2290 /* Note: NEVER do the unbind/rem/del here, it will be done by the caller or by the _stub function
2291 */
2292 //%%% BUG FIX - related to commit bit usage - crash happened here
2293 if (iph2->ph1 == 0) {
2294 plog(LLV_ERROR, LOCATION, NULL,
2295 "internal error - attempt to re-send phase2 with no phase1 bound.\n");
2296 return -1;
2297 }
2298
2299 if (iph2->ph1->status == PHASE1ST_EXPIRED){
2300 IPSECSESSIONTRACEREVENT(iph2->ph1->parent_session,
2301 IPSECSESSIONEVENTCODE_IKEV1_PH2_MAX_RETRANSMIT,
2302 CONSTSTR("Underlying Phase1 expired"),
2303 CONSTSTR("Failed to retransmit phase2 (underlying phase1 expired)"));
2304 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2305 "phase2 negotiation failed due to phase1 expired. %s\n",
2306 isakmp_pindex(&iph2->ph1->index, iph2->msgid));
2307 return -1;
2308 }
2309
2310 if (iph2->retry_counter <= 0) {
2311 IPSECSESSIONTRACEREVENT(iph2->ph1->parent_session,
2312 IPSECSESSIONEVENTCODE_IKEV1_PH2_MAX_RETRANSMIT,
2313 CONSTSTR("Phase2 maximum retransmits"),
2314 CONSTSTR("Phase2 negotiation failed (maximum retransmits)"));
2315 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2316 "phase2 negotiation failed due to time up. %s\n",
2317 isakmp_pindex(&iph2->ph1->index, iph2->msgid));
2318 EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
2319 return -1;
2320 }
2321
2322 if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0){
2323 if (iph2->ph1->rmconf->retry_counter != iph2->retry_counter) {
2324 IPSECSESSIONTRACEREVENT(iph2->ph1->parent_session,
2325 IPSECSESSIONEVENTCODE_IKE_PACKET_TX_FAIL,
2326 CONSTSTR("Phase2 Retransmit"),
2327 CONSTSTR("Failed to retransmit Phase2 message"));
2328 }
2329 plog(LLV_ERROR, LOCATION, NULL,
2330 "phase2 negotiation failed due to send error. %s\n",
2331 isakmp_pindex(&iph2->ph1->index, iph2->msgid));
2332 EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
2333
2334 return -1;
2335 }
2336 if (iph2->ph1->rmconf->retry_counter != iph2->retry_counter) {
2337 IPSECSESSIONTRACEREVENT(iph2->ph1->parent_session,
2338 IPSECSESSIONEVENTCODE_IKE_PACKET_TX_SUCC,
2339 CONSTSTR("Phase2 Retransmit"),
2340 CONSTSTR(NULL));
2341 }
2342
2343 plog(LLV_DEBUG, LOCATION, NULL,
2344 "resend phase2 packet %s\n",
2345 isakmp_pindex(&iph2->ph1->index, iph2->msgid));
2346
2347 iph2->retry_counter--;
2348
2349 iph2->scr = sched_new(iph2->ph1->rmconf->retry_interval,
2350 isakmp_ph2resend_stub, iph2);
2351
2352 #ifdef ENABLE_DPD
2353 if (iph2->scr) {
2354 isakmp_reschedule_info_monitor_if_pending(iph2->ph1,
2355 "phase2 packets sent to peer: retransmit timer armed");
2356 }
2357 #endif /* DPD */
2358
2359 return 0;
2360 }
2361
2362 /* called from scheduler */
2363 void
2364 isakmp_ph1expire_stub(p)
2365 void *p;
2366 {
2367
2368 isakmp_ph1expire((struct ph1handle *)p);
2369 }
2370
2371 void
2372 isakmp_ph1expire(iph1)
2373 struct ph1handle *iph1;
2374 {
2375 char *src, *dst;
2376
2377 SCHED_KILL(iph1->sce);
2378 #ifdef ENABLE_DPD
2379 SCHED_KILL(iph1->dpd_r_u);
2380 #endif
2381
2382 if(iph1->status != PHASE1ST_EXPIRED){
2383 src = racoon_strdup(saddr2str(iph1->local));
2384 dst = racoon_strdup(saddr2str(iph1->remote));
2385 STRDUP_FATAL(src);
2386 STRDUP_FATAL(dst);
2387
2388 plog(LLV_INFO, LOCATION, NULL,
2389 "ISAKMP-SA expired %s-%s spi:%s\n",
2390 src, dst,
2391 isakmp_pindex(&iph1->index, 0));
2392 racoon_free(src);
2393 racoon_free(dst);
2394 iph1->status = PHASE1ST_EXPIRED;
2395 (void)ike_session_update_ph1_ph2tree(iph1);
2396 }
2397
2398 /*
2399 * the phase1 deletion is postponed until there is no phase2.
2400 */
2401 if (LIST_FIRST(&iph1->ph2tree) != NULL) {
2402 iph1->sce = sched_new(1, isakmp_ph1expire_stub, iph1);
2403 return;
2404 }
2405
2406 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
2407 }
2408
2409 /* called from scheduler */
2410 void
2411 isakmp_ph1rekeyexpire_stub(p)
2412 void *p;
2413 {
2414
2415 isakmp_ph1rekeyexpire((struct ph1handle *)p);
2416 }
2417
2418 void
2419 isakmp_ph1rekeyexpire(iph1)
2420 struct ph1handle *iph1;
2421 {
2422 char *src, *dst;
2423 struct remoteconf *rmconf;
2424
2425 SCHED_KILL(iph1->sce_rekey);
2426
2427 // early exit if iph2->sce == NULL, iph2 isn't established or if entire session is going down
2428 if (iph1->sce == NULL ||
2429 iph1->status != PHASE1ST_ESTABLISHED ||
2430 iph1->is_dying) {
2431 return;
2432 }
2433
2434 src = racoon_strdup(saddr2str(iph1->local));
2435 dst = racoon_strdup(saddr2str(iph1->remote));
2436 STRDUP_FATAL(src);
2437 STRDUP_FATAL(dst);
2438
2439 plog(LLV_INFO, LOCATION, NULL,
2440 "ISAKMP-SA rekey-timer expired %s-%s spi:%s\n",
2441 src, dst,
2442 isakmp_pindex(&iph1->index, 0));
2443 racoon_free(src);
2444 racoon_free(dst);
2445
2446 // exit if there is another ph1 that is established (with a pending rekey timer)
2447 if (ike_session_has_other_established_ph1(iph1->parent_session, iph1)) {
2448 plog(LLV_INFO, LOCATION, iph1->remote,
2449 "request for ISAKMP-SA rekey was ignored "
2450 "due to another established ph1.\n");
2451 return;
2452 }
2453
2454 // if there is another ph1 that is negotiating, postpone this rekey for a few seconds later
2455 if (ike_session_has_other_negoing_ph1(iph1->parent_session, iph1)) {
2456 plog(LLV_DEBUG, LOCATION, NULL, "reschedule Phase1 rekey.\n");
2457 iph1->sce_rekey = sched_new(1,
2458 isakmp_ph1rekeyexpire_stub,
2459 iph1);
2460 return;
2461 }
2462
2463 // get rmconf to initiate rekey with
2464 rmconf = iph1->rmconf;
2465 if (!rmconf || rmconf->to_delete || rmconf->to_remove) {
2466 rmconf = getrmconf(iph1->remote);
2467 }
2468 if (rmconf) {
2469 /* begin quick mode */
2470 plog(LLV_DEBUG, LOCATION, NULL, "begin Phase1 rekey.\n");
2471
2472 /* start phase 1 negotiation as a initiator. */
2473 if (isakmp_ph1begin_i(rmconf, iph1->remote, iph1->local, 0) < 0) {
2474 plog(LLV_DEBUG, LOCATION, NULL, "Phase1 rekey Failed.\n");
2475 }
2476 } else {
2477 plog(LLV_ERROR, LOCATION, NULL,
2478 "Phase1 rekey failed: no configuration found for %s.\n",
2479 saddrwop2str(iph1->remote));
2480 }
2481 }
2482
2483 int
2484 isakmp_ph1rekeyretry(iph1)
2485 struct ph1handle *iph1;
2486 {
2487 char *src, *dst;
2488 struct remoteconf *rmconf;
2489
2490 // this code path is meant for floated ph1 rekeys that are failing on the first message
2491 if (iph1->sce != NULL ||
2492 iph1->sce_rekey != NULL ||
2493 (iph1->status != PHASE1ST_MSG1SENT || (iph1->natt_flags & NAT_PORTS_CHANGED == 0)) ||
2494 (extract_port(iph1->local) != PORT_ISAKMP_NATT && extract_port(iph1->remote) != PORT_ISAKMP_NATT) ||
2495 iph1->is_dying) {
2496 return -1;
2497 }
2498
2499 src = racoon_strdup(saddr2str(iph1->local));
2500 dst = racoon_strdup(saddr2str(iph1->remote));
2501 STRDUP_FATAL(src);
2502 STRDUP_FATAL(dst);
2503
2504 plog(LLV_INFO, LOCATION, NULL,
2505 "ISAKMP-SA rekey failed... retrying %s-%s spi:%s\n",
2506 src, dst,
2507 isakmp_pindex(&iph1->index, 0));
2508 racoon_free(src);
2509 racoon_free(dst);
2510
2511 // exit if there is another ph1 that is established (with a pending rekey timer)
2512 if (ike_session_has_other_established_ph1(iph1->parent_session, iph1)) {
2513 plog(LLV_INFO, LOCATION, iph1->remote,
2514 "request to retry ISAKMP-SA rekey was ignored "
2515 "due to another established ph1.\n");
2516 return -1;
2517 }
2518
2519 // some servers don't like respond to 4500 for rekeys... try accomodate them
2520 if (extract_port(iph1->local) == PORT_ISAKMP_NATT) {
2521 set_port(iph1->local, PORT_ISAKMP);
2522 }
2523 if (extract_port(iph1->remote) == PORT_ISAKMP_NATT) {
2524 set_port(iph1->remote, PORT_ISAKMP);
2525 }
2526 iph1->natt_flags &= ~NAT_PORTS_CHANGED;
2527 rmconf = getrmconf(iph1->remote);
2528 if (rmconf) {
2529 /* begin quick mode */
2530 plog(LLV_DEBUG, LOCATION, NULL, "begin Phase1 rekey retry.\n");
2531
2532 /* start phase 1 negotiation as a initiator. */
2533 if (isakmp_ph1begin_i(rmconf, iph1->remote, iph1->local, 0) < 0) {
2534 plog(LLV_DEBUG, LOCATION, NULL, "Phase1 rekey retry Failed.\n");
2535 return -1;
2536 }
2537 } else {
2538 plog(LLV_ERROR, LOCATION, NULL,
2539 "Phase1 rekey retry failed: no configuration found for %s.\n",
2540 saddrwop2str(iph1->remote));
2541 return -1;
2542 }
2543 return 0;
2544 }
2545
2546 /* called from scheduler */
2547 void
2548 isakmp_ph1delete_stub(p)
2549 void *p;
2550 {
2551
2552 isakmp_ph1delete((struct ph1handle *)p);
2553 }
2554
2555 void
2556 isakmp_ph1delete(iph1)
2557 struct ph1handle *iph1;
2558 {
2559 char *src, *dst;
2560
2561 SCHED_KILL(iph1->sce);
2562 SCHED_KILL(iph1->sce_rekey);
2563 #ifdef ENABLE_DPD
2564 SCHED_KILL(iph1->dpd_r_u);
2565 #endif
2566
2567 if (LIST_FIRST(&iph1->ph2tree) != NULL) {
2568 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
2569 return;
2570 }
2571
2572 isakmp_info_send_d1(iph1);
2573
2574 /* don't re-negosiation when the phase 1 SA expires. */
2575
2576 src = racoon_strdup(saddr2str(iph1->local));
2577 dst = racoon_strdup(saddr2str(iph1->remote));
2578 STRDUP_FATAL(src);
2579 STRDUP_FATAL(dst);
2580
2581 plog(LLV_INFO, LOCATION, NULL,
2582 "ISAKMP-SA deleted %s-%s spi:%s\n",
2583 src, dst, isakmp_pindex(&iph1->index, 0));
2584 EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_DOWN, NULL);
2585 racoon_free(src);
2586 racoon_free(dst);
2587
2588 remph1(iph1);
2589 delph1(iph1);
2590
2591 return;
2592 }
2593
2594 /* called from scheduler.
2595 * this function will call only isakmp_ph2delete().
2596 * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
2597 * by something cause. That's why this function is called after phase 2 SA
2598 * expires in the userland.
2599 */
2600 void
2601 isakmp_ph2expire_stub(p)
2602 void *p;
2603 {
2604
2605 isakmp_ph2expire((struct ph2handle *)p);
2606 }
2607
2608 void
2609 isakmp_ph2expire(iph2)
2610 struct ph2handle *iph2;
2611 {
2612 char *src, *dst;
2613
2614 SCHED_KILL(iph2->sce);
2615
2616 src = racoon_strdup(saddrwop2str(iph2->src));
2617 dst = racoon_strdup(saddrwop2str(iph2->dst));
2618 STRDUP_FATAL(src);
2619 STRDUP_FATAL(dst);
2620
2621 plog(LLV_INFO, LOCATION, NULL,
2622 "phase2 sa expired %s-%s\n", src, dst);
2623 racoon_free(src);
2624 racoon_free(dst);
2625
2626 // delete outgoing SAs
2627 if (iph2->status == PHASE2ST_ESTABLISHED && iph2->approval) {
2628 struct saproto *pr;
2629
2630 for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
2631 if (pr->ok) {
2632 pfkey_send_delete(lcconf->sock_pfkey,
2633 ipsecdoi2pfkey_proto(pr->proto_id),
2634 IPSEC_MODE_ANY,
2635 iph2->src, iph2->dst, pr->spi_p /* pr->reqid_out */);
2636 }
2637 }
2638 }
2639
2640 iph2->status = PHASE2ST_EXPIRED;
2641
2642 iph2->sce = sched_new(1, isakmp_ph2delete_stub, iph2);
2643
2644 return;
2645 }
2646
2647 /* called from scheduler */
2648 void
2649 isakmp_ph2delete_stub(p)
2650 void *p;
2651 {
2652
2653 isakmp_ph2delete((struct ph2handle *)p);
2654 }
2655
2656 void
2657 isakmp_ph2delete(iph2)
2658 struct ph2handle *iph2;
2659 {
2660 char *src, *dst;
2661
2662 SCHED_KILL(iph2->sce);
2663
2664 src = racoon_strdup(saddrwop2str(iph2->src));
2665 dst = racoon_strdup(saddrwop2str(iph2->dst));
2666 STRDUP_FATAL(src);
2667 STRDUP_FATAL(dst);
2668
2669 plog(LLV_INFO, LOCATION, NULL,
2670 "phase2 sa deleted %s-%s\n", src, dst);
2671 racoon_free(src);
2672 racoon_free(dst);
2673
2674 unbindph12(iph2);
2675 remph2(iph2);
2676 delph2(iph2);
2677
2678 return;
2679 }
2680
2681 /* \f%%%
2682 * Interface between PF_KEYv2 and ISAKMP
2683 */
2684 /*
2685 * receive ACQUIRE from kernel, and begin either phase1 or phase2.
2686 * if phase1 has been finished, begin phase2.
2687 */
2688 int
2689 isakmp_post_acquire(iph2)
2690 struct ph2handle *iph2;
2691 {
2692 struct remoteconf *rmconf;
2693 struct ph1handle *iph1 = NULL;
2694
2695 plog(LLV_DEBUG, LOCATION, NULL, "in post_acquire\n");
2696
2697 /* search appropreate configuration with masking port. */
2698 rmconf = getrmconf(iph2->dst);
2699 if (rmconf == NULL) {
2700 plog(LLV_ERROR, LOCATION, NULL,
2701 "no configuration found for %s.\n",
2702 saddrwop2str(iph2->dst));
2703 return -1;
2704 }
2705
2706 /* if passive mode, ignore the acquire message */
2707 if (rmconf->passive) {
2708 plog(LLV_DEBUG, LOCATION, NULL,
2709 "because of passive mode, "
2710 "ignore the acquire message for %s.\n",
2711 saddrwop2str(iph2->dst));
2712 return 0;
2713 }
2714
2715 if (ike_session_verify_ph2_parent_session(iph2)) {
2716 plog(LLV_INFO, LOCATION, iph2->dst,
2717 "request for establishing IPsec-SA was ignored "
2718 "because there was a failure verifying parent session.\n");
2719 return -1;
2720 }
2721
2722 // what if there is another ph2 that is negotiating
2723 if (ike_session_has_other_negoing_ph2(iph2->parent_session, iph2)) {
2724 // TODO: postpone this rekey for a second later
2725 plog(LLV_INFO, LOCATION, iph2->dst,
2726 "request for establishing IPsec-SA was ignored "
2727 "due to another negoing ph2.\n");
2728 return -1;
2729 }
2730
2731 // if this is a phase2 rekeys (the policy may not have the current port number).
2732 // so, use the appropriate ports.
2733 if (iph2->is_rekey) {
2734 ike_session_update_ph2_ports(iph2);
2735 }
2736
2737 iph1 = ike_session_update_ph2_ph1bind(iph2);
2738
2739 /* no ISAKMP-SA found. */
2740 if (iph1 == NULL) {
2741 struct sched *sc;
2742
2743 iph2->retry_checkph1 = lcconf->retry_checkph1;
2744 sc = sched_new(1, isakmp_chkph1there_stub, iph2);
2745 plog(LLV_INFO, LOCATION, NULL,
2746 "IPsec-SA request for %s queued "
2747 "due to no phase1 found.\n",
2748 saddrwop2str(iph2->dst));
2749
2750 /* start phase 1 negotiation as a initiator. */
2751 if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src, 0) < 0) {
2752 SCHED_KILL(sc);
2753 return -1;
2754 }
2755
2756 return 0;
2757 /*NOTREACHED*/
2758 }
2759
2760 /* found ISAKMP-SA, but on negotiation. */
2761 if (iph1->status != PHASE1ST_ESTABLISHED) {
2762 iph2->retry_checkph1 = lcconf->retry_checkph1;
2763 sched_new(1, isakmp_chkph1there_stub, iph2);
2764 plog(LLV_INFO, LOCATION, iph2->dst,
2765 "request for establishing IPsec-SA was queued "
2766 "due to no phase1 found.\n");
2767 return 0;
2768 /*NOTREACHED*/
2769 }
2770
2771 /* found established ISAKMP-SA */
2772 /* i.e. iph1->status == PHASE1ST_ESTABLISHED */
2773
2774 /* found ISAKMP-SA. */
2775 plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
2776
2777 /* begin quick mode */
2778 if (isakmp_ph2begin_i(iph1, iph2))
2779 return -1;
2780
2781 return 0;
2782 }
2783
2784 /*
2785 * receive GETSPI from kernel.
2786 */
2787 int
2788 isakmp_post_getspi(iph2)
2789 struct ph2handle *iph2;
2790 {
2791 #ifdef ENABLE_STATS
2792 struct timeval start, end;
2793 #endif
2794
2795 /* don't process it because there is no suitable phase1-sa. */
2796 if (iph2->ph1->status == PHASE1ST_EXPIRED) {
2797 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2798 "the negotiation is stopped, "
2799 "because there is no suitable ISAKMP-SA.\n");
2800 return -1;
2801 }
2802
2803 #ifdef ENABLE_STATS
2804 gettimeofday(&start, NULL);
2805 #endif
2806 if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
2807 [iph2->side]
2808 [iph2->status])(iph2, NULL) != 0)
2809 return -1;
2810 #ifdef ENABLE_STATS
2811 gettimeofday(&end, NULL);
2812 syslog(LOG_NOTICE, "%s(%s): %8.6f",
2813 "phase2",
2814 s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
2815 timedelta(&start, &end));
2816 #endif
2817
2818 return 0;
2819 }
2820
2821 /* called by scheduler */
2822 void
2823 isakmp_chkph1there_stub(p)
2824 void *p;
2825 {
2826 isakmp_chkph1there((struct ph2handle *)p);
2827 }
2828
2829 void
2830 isakmp_chkph1there(iph2)
2831 struct ph2handle *iph2;
2832 {
2833 struct ph1handle *iph1;
2834
2835 iph2->retry_checkph1--;
2836 if (iph2->retry_checkph1 < 0 ||
2837 ike_session_verify_ph2_parent_session(iph2)) {
2838 if (iph2->retry_checkph1 < 0) {
2839 plog(LLV_ERROR, LOCATION, iph2->dst,
2840 "phase2 negotiation failed "
2841 "due to time up waiting for phase1. %s\n",
2842 sadbsecas2str(iph2->dst, iph2->src,
2843 iph2->satype, 0, 0));
2844 } else {
2845 plog(LLV_ERROR, LOCATION, iph2->dst,
2846 "phase2 negotiation failed "
2847 "due to invalid parent session. %s\n",
2848 sadbsecas2str(iph2->dst, iph2->src,
2849 iph2->satype, 0, 0));
2850 }
2851 plog(LLV_INFO, LOCATION, NULL,
2852 "delete phase 2 handler.\n");
2853
2854 /* send acquire to kernel as error */
2855 pk_sendeacquire(iph2);
2856
2857 unbindph12(iph2);
2858 remph2(iph2);
2859 delph2(iph2);
2860
2861 return;
2862 }
2863
2864 iph1 = ike_session_update_ph2_ph1bind(iph2);
2865
2866 /* XXX Even if ph1 as responder is there, should we not start
2867 * phase 2 negotiation ? */
2868 if (iph1 != NULL
2869 && iph1->status == PHASE1ST_ESTABLISHED) {
2870 /* found isakmp-sa */
2871
2872 plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: got a ph1 handler, setting ports.\n");
2873 plog(LLV_DEBUG2, LOCATION, NULL, "iph1->local: %s\n", saddr2str(iph1->local));
2874 plog(LLV_DEBUG2, LOCATION, NULL, "iph1->remote: %s\n", saddr2str(iph1->remote));
2875 plog(LLV_DEBUG2, LOCATION, NULL, "before:\n");
2876 plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2877 plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2878 set_port(iph2->src, extract_port(iph1->local));
2879 set_port(iph2->dst, extract_port(iph1->remote));
2880 plog(LLV_DEBUG2, LOCATION, NULL, "After:\n");
2881 plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2882 plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2883
2884 /* begin quick mode */
2885 if (isakmp_ph2begin_i(iph1, iph2)) {
2886 unbindph12(iph2);
2887 remph2(iph2);
2888 delph2(iph2);
2889 }
2890 return;
2891 }
2892 if (!ike_session_has_negoing_ph1(iph2->parent_session)) {
2893 struct remoteconf *rmconf = getrmconf(iph2->dst);
2894 /* start phase 1 negotiation as a initiator. */
2895 if (rmconf == NULL ||
2896 isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src, 0) < 0) {
2897 plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established/negoing ph1 handler found... failed to initiate new one\n");
2898 }
2899 }
2900
2901 plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established ph1 handler found\n");
2902
2903 /* no isakmp-sa found */
2904 sched_new(1, isakmp_chkph1there_stub, iph2);
2905
2906 return;
2907 }
2908
2909 /* copy variable data into ALLOCATED buffer. */
2910 caddr_t
2911 isakmp_set_attr_v(buf, type, val, len)
2912 caddr_t buf;
2913 int type;
2914 caddr_t val;
2915 int len;
2916 {
2917 struct isakmp_data *data;
2918
2919 data = (struct isakmp_data *)buf;
2920 data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2921 data->lorv = htons((u_int16_t)len);
2922 memcpy(data + 1, val, len);
2923
2924 return buf + sizeof(*data) + len;
2925 }
2926
2927 /* copy fixed length data into ALLOCATED buffer. */
2928 caddr_t
2929 isakmp_set_attr_l(buf, type, val)
2930 caddr_t buf;
2931 int type;
2932 u_int32_t val;
2933 {
2934 struct isakmp_data *data;
2935
2936 data = (struct isakmp_data *)buf;
2937 data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
2938 data->lorv = htons((u_int16_t)val);
2939
2940 return buf + sizeof(*data);
2941 }
2942
2943 /* add a variable data attribute to the buffer by reallocating it. */
2944 vchar_t *
2945 isakmp_add_attr_v(buf0, type, val, len)
2946 vchar_t *buf0;
2947 int type;
2948 caddr_t val;
2949 int len;
2950 {
2951 vchar_t *buf = NULL;
2952 struct isakmp_data *data;
2953 int tlen;
2954 int oldlen = 0;
2955
2956 tlen = sizeof(*data) + len;
2957
2958 if (buf0) {
2959 oldlen = buf0->l;
2960 buf = vrealloc(buf0, oldlen + tlen);
2961 } else
2962 buf = vmalloc(tlen);
2963 if (!buf) {
2964 plog(LLV_ERROR, LOCATION, NULL,
2965 "failed to get a attribute buffer.\n");
2966 return NULL;
2967 }
2968
2969 data = (struct isakmp_data *)(buf->v + oldlen);
2970 data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2971 data->lorv = htons((u_int16_t)len);
2972 memcpy(data + 1, val, len);
2973
2974 return buf;
2975 }
2976
2977 /* add a fixed data attribute to the buffer by reallocating it. */
2978 vchar_t *
2979 isakmp_add_attr_l(buf0, type, val)
2980 vchar_t *buf0;
2981 int type;
2982 u_int32_t val;
2983 {
2984 vchar_t *buf = NULL;
2985 struct isakmp_data *data;
2986 int tlen;
2987 int oldlen = 0;
2988
2989 tlen = sizeof(*data);
2990
2991 if (buf0) {
2992 oldlen = buf0->l;
2993 buf = vrealloc(buf0, oldlen + tlen);
2994 } else
2995 buf = vmalloc(tlen);
2996 if (!buf) {
2997 plog(LLV_ERROR, LOCATION, NULL,
2998 "failed to get a attribute buffer.\n");
2999 return NULL;
3000 }
3001
3002 data = (struct isakmp_data *)(buf->v + oldlen);
3003 data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
3004 data->lorv = htons((u_int16_t)val);
3005
3006 return buf;
3007 }
3008
3009 /*
3010 * calculate cookie and set.
3011 */
3012 int
3013 isakmp_newcookie(place, remote, local)
3014 caddr_t place;
3015 struct sockaddr *remote;
3016 struct sockaddr *local;
3017 {
3018 vchar_t *buf = NULL, *buf2 = NULL;
3019 char *p;
3020 int blen;
3021 int alen;
3022 caddr_t sa1, sa2;
3023 time_t t;
3024 int error = -1;
3025 u_short port;
3026
3027
3028 if (remote->sa_family != local->sa_family) {
3029 plog(LLV_ERROR, LOCATION, NULL,
3030 "address family mismatch, remote:%d local:%d\n",
3031 remote->sa_family, local->sa_family);
3032 goto end;
3033 }
3034 switch (remote->sa_family) {
3035 case AF_INET:
3036 alen = sizeof(struct in_addr);
3037 sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
3038 sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
3039 break;
3040 #ifdef INET6
3041 case AF_INET6:
3042 alen = sizeof(struct in_addr);
3043 sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
3044 sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
3045 break;
3046 #endif
3047 default:
3048 plog(LLV_ERROR, LOCATION, NULL,
3049 "invalid family: %d\n", remote->sa_family);
3050 goto end;
3051 }
3052 blen = (alen + sizeof(u_short)) * 2
3053 + sizeof(time_t) + lcconf->secret_size;
3054 buf = vmalloc(blen);
3055 if (buf == NULL) {
3056 plog(LLV_ERROR, LOCATION, NULL,
3057 "failed to get a cookie.\n");
3058 goto end;
3059 }
3060 p = buf->v;
3061
3062 /* copy my address */
3063 memcpy(p, sa1, alen);
3064 p += alen;
3065 port = ((struct sockaddr_in *)remote)->sin_port;
3066 memcpy(p, &port, sizeof(u_short));
3067 p += sizeof(u_short);
3068
3069 /* copy target address */
3070 memcpy(p, sa2, alen);
3071 p += alen;
3072 port = ((struct sockaddr_in *)local)->sin_port;
3073 memcpy(p, &port, sizeof(u_short));
3074 p += sizeof(u_short);
3075
3076 /* copy time */
3077 t = time(0);
3078 memcpy(p, (caddr_t)&t, sizeof(t));
3079 p += sizeof(t);
3080
3081 /* copy random value */
3082 buf2 = eay_set_random(lcconf->secret_size);
3083 if (buf2 == NULL)
3084 goto end;
3085 memcpy(p, buf2->v, lcconf->secret_size);
3086 p += lcconf->secret_size;
3087 vfree(buf2);
3088
3089 buf2 = eay_sha1_one(buf);
3090 memcpy(place, buf2->v, sizeof(cookie_t));
3091
3092 sa1 = val2str(place, sizeof (cookie_t));
3093 plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
3094 racoon_free(sa1);
3095
3096 error = 0;
3097 end:
3098 if (buf != NULL)
3099 vfree(buf);
3100 if (buf2 != NULL)
3101 vfree(buf2);
3102 return error;
3103 }
3104
3105 /*
3106 * save partner's(payload) data into phhandle.
3107 */
3108 int
3109 isakmp_p2ph(buf, gen)
3110 vchar_t **buf;
3111 struct isakmp_gen *gen;
3112 {
3113 /* XXX to be checked in each functions for logging. */
3114 if (*buf) {
3115 plog(LLV_WARNING, LOCATION, NULL,
3116 "ignore this payload, same payload type exist.\n");
3117 return -1;
3118 }
3119
3120 *buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
3121 if (*buf == NULL) {
3122 plog(LLV_ERROR, LOCATION, NULL,
3123 "failed to get buffer.\n");
3124 return -1;
3125 }
3126 memcpy((*buf)->v, gen + 1, (*buf)->l);
3127
3128 return 0;
3129 }
3130
3131 u_int32_t
3132 isakmp_newmsgid2(iph1)
3133 struct ph1handle *iph1;
3134 {
3135 u_int32_t msgid2;
3136
3137 do {
3138 msgid2 = eay_random();
3139 } while (getph2bymsgid(iph1, msgid2));
3140
3141 return msgid2;
3142 }
3143
3144 /*
3145 * set values into allocated buffer of isakmp header for phase 1
3146 */
3147 static caddr_t
3148 set_isakmp_header(vbuf, iph1, nptype, etype, flags, msgid)
3149 vchar_t *vbuf;
3150 struct ph1handle *iph1;
3151 int nptype;
3152 u_int8_t etype;
3153 u_int8_t flags;
3154 u_int32_t msgid;
3155 {
3156 struct isakmp *isakmp;
3157
3158 if (vbuf->l < sizeof(*isakmp))
3159 return NULL;
3160
3161 isakmp = (struct isakmp *)vbuf->v;
3162
3163 memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
3164 memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
3165 isakmp->np = nptype;
3166 isakmp->v = iph1->version;
3167 isakmp->etype = etype;
3168 isakmp->flags = flags;
3169 isakmp->msgid = msgid;
3170 isakmp->len = htonl(vbuf->l);
3171
3172 return vbuf->v + sizeof(*isakmp);
3173 }
3174
3175 /*
3176 * set values into allocated buffer of isakmp header for phase 1
3177 */
3178 caddr_t
3179 set_isakmp_header1(vbuf, iph1, nptype)
3180 vchar_t *vbuf;
3181 struct ph1handle *iph1;
3182 int nptype;
3183 {
3184 return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
3185 }
3186
3187 /*
3188 * set values into allocated buffer of isakmp header for phase 2
3189 */
3190 caddr_t
3191 set_isakmp_header2(vbuf, iph2, nptype)
3192 vchar_t *vbuf;
3193 struct ph2handle *iph2;
3194 int nptype;
3195 {
3196 return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
3197 }
3198
3199 /*
3200 * set values into allocated buffer of isakmp payload.
3201 */
3202 caddr_t
3203 set_isakmp_payload(buf, src, nptype)
3204 caddr_t buf;
3205 vchar_t *src;
3206 int nptype;
3207 {
3208 struct isakmp_gen *gen;
3209 caddr_t p = buf;
3210
3211 plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
3212 src->l, nptype);
3213
3214 gen = (struct isakmp_gen *)p;
3215 gen->np = nptype;
3216 gen->len = htons(sizeof(*gen) + src->l);
3217 p += sizeof(*gen);
3218 memcpy(p, src->v, src->l);
3219 p += src->l;
3220
3221 return p;
3222 }
3223
3224 static int
3225 etypesw1(etype)
3226 int etype;
3227 {
3228 switch (etype) {
3229 case ISAKMP_ETYPE_IDENT:
3230 return 1;
3231 case ISAKMP_ETYPE_AGG:
3232 return 2;
3233 case ISAKMP_ETYPE_BASE:
3234 return 3;
3235 default:
3236 return 0;
3237 }
3238 /*NOTREACHED*/
3239 }
3240
3241 static int
3242 etypesw2(etype)
3243 int etype;
3244 {
3245 switch (etype) {
3246 case ISAKMP_ETYPE_QUICK:
3247 return 1;
3248 default:
3249 return 0;
3250 }
3251 /*NOTREACHED*/
3252 }
3253
3254 #ifdef HAVE_PRINT_ISAKMP_C
3255 /* for print-isakmp.c */
3256 char *snapend;
3257 extern void isakmp_print __P((const u_char *, u_int, const u_char *));
3258
3259 char *getname __P((const u_char *));
3260 #ifdef INET6
3261 char *getname6 __P((const u_char *));
3262 #endif
3263 int safeputchar __P((int));
3264
3265 /*
3266 * Return a name for the IP address pointed to by ap. This address
3267 * is assumed to be in network byte order.
3268 */
3269 char *
3270 getname(ap)
3271 const u_char *ap;
3272 {
3273 struct sockaddr_in addr;
3274 static char ntop_buf[NI_MAXHOST];
3275
3276 memset(&addr, 0, sizeof(addr));
3277 #ifndef __linux__
3278 addr.sin_len = sizeof(struct sockaddr_in);
3279 #endif
3280 addr.sin_family = AF_INET;
3281 memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
3282 if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
3283 ntop_buf, sizeof(ntop_buf), NULL, 0,
3284 NI_NUMERICHOST | niflags))
3285 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
3286
3287 return ntop_buf;
3288 }
3289
3290 #ifdef INET6
3291 /*
3292 * Return a name for the IP6 address pointed to by ap. This address
3293 * is assumed to be in network byte order.
3294 */
3295 char *
3296 getname6(ap)
3297 const u_char *ap;
3298 {
3299 struct sockaddr_in6 addr;
3300 static char ntop_buf[NI_MAXHOST];
3301
3302 memset(&addr, 0, sizeof(addr));
3303 addr.sin6_len = sizeof(struct sockaddr_in6);
3304 addr.sin6_family = AF_INET6;
3305 memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
3306 if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
3307 ntop_buf, sizeof(ntop_buf), NULL, 0,
3308 NI_NUMERICHOST | niflags))
3309 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
3310
3311 return ntop_buf;
3312 }
3313 #endif /* INET6 */
3314
3315 int
3316 safeputchar(c)
3317 int c;
3318 {
3319 unsigned char ch;
3320
3321 ch = (unsigned char)(c & 0xff);
3322 if (c < 0x80 && isprint(c))
3323 return printf("%c", c & 0xff);
3324 else
3325 return printf("\\%03o", c & 0xff);
3326 }
3327
3328 void
3329 isakmp_printpacket(msg, from, my, decoded)
3330 vchar_t *msg;
3331 struct sockaddr *from;
3332 struct sockaddr *my;
3333 int decoded;
3334 {
3335 #ifdef YIPS_DEBUG
3336 struct timeval tv;
3337 int s;
3338 char hostbuf[NI_MAXHOST];
3339 char portbuf[NI_MAXSERV];
3340 struct isakmp *isakmp;
3341 vchar_t *buf;
3342 #endif
3343
3344 if (loglevel < LLV_DEBUG)
3345 return;
3346
3347 #ifdef YIPS_DEBUG
3348 plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
3349
3350 gettimeofday(&tv, NULL);
3351 s = tv.tv_sec % 3600;
3352 printf("%02d:%02d.%06u ", s / 60, s % 60, (u_int32_t)tv.tv_usec);
3353
3354 if (from) {
3355 if (getnameinfo(from, sysdep_sa_len(from), hostbuf, sizeof(hostbuf),
3356 portbuf, sizeof(portbuf),
3357 NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
3358 strlcpy(hostbuf, "?", sizeof(hostbuf));
3359 strlcpy(portbuf, "?", sizeof(portbuf));
3360 }
3361 printf("%s:%s", hostbuf, portbuf);
3362 } else
3363 printf("?");
3364 printf(" -> ");
3365 if (my) {
3366 if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
3367 portbuf, sizeof(portbuf),
3368 NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
3369 strlcpy(hostbuf, "?", sizeof(hostbuf));
3370 strlcpy(portbuf, "?", sizeof(portbuf));
3371 }
3372 printf("%s:%s", hostbuf, portbuf);
3373 } else
3374 printf("?");
3375 printf(": ");
3376
3377 buf = vdup(msg);
3378 if (!buf) {
3379 printf("(malloc fail)\n");
3380 return;
3381 }
3382 if (decoded) {
3383 isakmp = (struct isakmp *)buf->v;
3384 if (isakmp->flags & ISAKMP_FLAG_E) {
3385 #if 0
3386 int pad;
3387 pad = *(u_char *)(buf->v + buf->l - 1);
3388 if (buf->l < pad && 2 < vflag)
3389 printf("(wrong padding)");
3390 #endif
3391 isakmp->flags &= ~ISAKMP_FLAG_E;
3392 }
3393 }
3394
3395 snapend = buf->v + buf->l;
3396 isakmp_print(buf->v, buf->l, NULL);
3397 vfree(buf);
3398 printf("\n");
3399 fflush(stdout);
3400
3401 return;
3402 #endif
3403 }
3404 #endif /*HAVE_PRINT_ISAKMP_C*/
3405
3406 int
3407 copy_ph1addresses(iph1, rmconf, remote, local)
3408 struct ph1handle *iph1;
3409 struct remoteconf *rmconf;
3410 struct sockaddr *remote, *local;
3411 {
3412 u_short *port = NULL;
3413
3414 /* address portion must be grabbed from real remote address "remote" */
3415 iph1->remote = dupsaddr(remote);
3416 if (iph1->remote == NULL) {
3417 delph1(iph1);
3418 return -1;
3419 }
3420
3421 /*
3422 * if remote has no port # (in case of initiator - from ACQUIRE msg)
3423 * - if remote.conf specifies port #, use that
3424 * - if remote.conf does not, use 500
3425 * if remote has port # (in case of responder - from recvfrom(2))
3426 * respect content of "remote".
3427 */
3428 switch (iph1->remote->sa_family) {
3429 case AF_INET:
3430 port = &((struct sockaddr_in *)iph1->remote)->sin_port;
3431 if (*port)
3432 break;
3433 *port = ((struct sockaddr_in *)rmconf->remote)->sin_port;
3434 if (*port)
3435 break;
3436 *port = htons(PORT_ISAKMP);
3437 break;
3438 #ifdef INET6
3439 case AF_INET6:
3440 port = &((struct sockaddr_in6 *)iph1->remote)->sin6_port;
3441 if (*port)
3442 break;
3443 *port = ((struct sockaddr_in6 *)rmconf->remote)->sin6_port;
3444 if (*port)
3445 break;
3446 *port = htons(PORT_ISAKMP);
3447 break;
3448 #endif
3449 default:
3450 plog(LLV_ERROR, LOCATION, NULL,
3451 "invalid family: %d\n", iph1->remote->sa_family);
3452 delph1(iph1);
3453 return -1;
3454 }
3455
3456 if (local == NULL)
3457 iph1->local = getlocaladdr(iph1->remote);
3458 else
3459 iph1->local = dupsaddr(local);
3460 if (iph1->local == NULL) {
3461 delph1(iph1);
3462 return -1;
3463 }
3464 port = NULL;
3465 switch (iph1->local->sa_family) {
3466 case AF_INET:
3467 port = &((struct sockaddr_in *)iph1->local)->sin_port;
3468 if (*port)
3469 break;
3470 *port = ((struct sockaddr_in *)iph1->local)->sin_port;
3471 if (*port)
3472 break;
3473 *port = getmyaddrsport(iph1->local);
3474 break;
3475 #ifdef INET6
3476 case AF_INET6:
3477 port = &((struct sockaddr_in6 *)iph1->local)->sin6_port;
3478 if (*port)
3479 break;
3480 *port = ((struct sockaddr_in6 *)iph1->local)->sin6_port;
3481 if (*port)
3482 break;
3483 *port = getmyaddrsport(iph1->local);
3484 break;
3485 #endif
3486 default:
3487 plog(LLV_ERROR, LOCATION, NULL,
3488 "invalid family: %d\n", iph1->local->sa_family);
3489 delph1(iph1);
3490 return -1;
3491 }
3492 #ifdef ENABLE_NATT
3493 if ( port != NULL && *port == htons(lcconf->port_isakmp_natt) ) {
3494 plog (LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
3495 iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
3496 }
3497 #endif
3498
3499 return 0;
3500 }
3501
3502 static int
3503 nostate1(iph1, msg)
3504 struct ph1handle *iph1;
3505 vchar_t *msg;
3506 {
3507 plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
3508 iph1->status);
3509 return -1;
3510 }
3511
3512 static int
3513 nostate2(iph2, msg)
3514 struct ph2handle *iph2;
3515 vchar_t *msg;
3516 {
3517 plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
3518 iph2->status);
3519 return -1;
3520 }
3521
3522 void
3523 log_ph1established(iph1)
3524 const struct ph1handle *iph1;
3525 {
3526 char *src, *dst;
3527
3528 src = racoon_strdup(saddr2str(iph1->local));
3529 dst = racoon_strdup(saddr2str(iph1->remote));
3530 STRDUP_FATAL(src);
3531 STRDUP_FATAL(dst);
3532
3533 plog(LLV_INFO, LOCATION, NULL,
3534 "ISAKMP-SA established %s-%s spi:%s\n",
3535 src, dst,
3536 isakmp_pindex(&iph1->index, 0));
3537 EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_UP, NULL);
3538 if(!iph1->rmconf->mode_cfg)
3539 EVT_PUSH(iph1->local, iph1->remote, EVTT_NO_ISAKMP_CFG, NULL);
3540
3541 racoon_free(src);
3542 racoon_free(dst);
3543
3544 return;
3545 }
3546
3547 struct payload_list *
3548 isakmp_plist_append (struct payload_list *plist, vchar_t *payload, int payload_type)
3549 {
3550 if (! plist) {
3551 plist = racoon_malloc (sizeof (struct payload_list));
3552 plist->prev = NULL;
3553 }
3554 else {
3555 plist->next = racoon_malloc (sizeof (struct payload_list));
3556 plist->next->prev = plist;
3557 plist = plist->next;
3558 }
3559
3560 plist->next = NULL;
3561 plist->payload = payload;
3562 plist->payload_type = payload_type;
3563
3564 return plist;
3565 }
3566
3567 vchar_t *
3568 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
3569 {
3570 struct payload_list *ptr = *plist, *first;
3571 size_t tlen = sizeof (struct isakmp), n = 0;
3572 vchar_t *buf = NULL;
3573 char *p;
3574
3575 /* Seek to the first item. */
3576 while (ptr->prev) ptr = ptr->prev;
3577 first = ptr;
3578
3579 /* Compute the whole length. */
3580 while (ptr) {
3581 tlen += ptr->payload->l + sizeof (struct isakmp_gen);
3582 ptr = ptr->next;
3583 }
3584
3585 buf = vmalloc(tlen);
3586 if (buf == NULL) {
3587 plog(LLV_ERROR, LOCATION, NULL,
3588 "failed to get buffer to send.\n");
3589 goto end;
3590 }
3591
3592 ptr = first;
3593
3594 p = set_isakmp_header1(buf, iph1, ptr->payload_type);
3595 if (p == NULL)
3596 goto end;
3597
3598 while (ptr)
3599 {
3600 p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
3601 first = ptr;
3602 ptr = ptr->next;
3603 racoon_free (first);
3604 /* ptr->prev = NULL; first = NULL; ... omitted. */
3605 n++;
3606 }
3607
3608 *plist = NULL;
3609
3610 return buf;
3611 end:
3612 if (buf != NULL)
3613 vfree(buf);
3614 return NULL;
3615 }
3616
3617 #ifdef ENABLE_FRAG
3618 int
3619 frag_handler(iph1, msg, remote, local)
3620 struct ph1handle *iph1;
3621 vchar_t *msg;
3622 struct sockaddr *remote;
3623 struct sockaddr *local;
3624 {
3625 vchar_t *newmsg;
3626
3627 if (isakmp_frag_extract(iph1, msg) == 1) {
3628 if ((newmsg = isakmp_frag_reassembly(iph1)) == NULL) {
3629 plog(LLV_ERROR, LOCATION, remote,
3630 "Packet reassembly failed\n");
3631 return -1;
3632 }
3633 return isakmp_main(newmsg, remote, local);
3634 }
3635
3636 return 0;
3637 }
3638 #endif
3639
3640 void
3641 script_hook(iph1, script)
3642 struct ph1handle *iph1;
3643 int script;
3644 {
3645 #define IP_MAX 40
3646 #define PORT_MAX 6
3647 char addrstr[IP_MAX];
3648 char portstr[PORT_MAX];
3649 char **envp = NULL;
3650 int envc = 1;
3651 struct sockaddr_in *sin;
3652 char **c;
3653
3654 if (iph1 == NULL ||
3655 iph1->rmconf == NULL ||
3656 iph1->rmconf->script[script] == NULL)
3657 return;
3658
3659 #ifdef ENABLE_HYBRID
3660 (void)isakmp_cfg_setenv(iph1, &envp, &envc);
3661 #endif
3662
3663 /* local address */
3664 sin = (struct sockaddr_in *)iph1->local;
3665 inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
3666 snprintf(portstr, sizeof(portstr), "%d", ntohs(sin->sin_port));
3667
3668 if (script_env_append(&envp, &envc, "LOCAL_ADDR", addrstr) != 0) {
3669 plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_ADDR\n");
3670 goto out;
3671 }
3672
3673 if (script_env_append(&envp, &envc, "LOCAL_PORT", portstr) != 0) {
3674 plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_PORT\n");
3675 goto out;
3676 }
3677
3678 /* Peer address */
3679 if (iph1->remote != NULL) {
3680 sin = (struct sockaddr_in *)iph1->remote;
3681 inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
3682 snprintf(portstr, sizeof(portstr), "%d", ntohs(sin->sin_port));
3683
3684 if (script_env_append(&envp, &envc,
3685 "REMOTE_ADDR", addrstr) != 0) {
3686 plog(LLV_ERROR, LOCATION, NULL,
3687 "Cannot set REMOTE_ADDR\n");
3688 goto out;
3689 }
3690
3691 if (script_env_append(&envp, &envc,
3692 "REMOTE_PORT", portstr) != 0) {
3693 plog(LLV_ERROR, LOCATION, NULL,
3694 "Cannot set REMOTEL_PORT\n");
3695 goto out;
3696 }
3697 }
3698
3699 if (privsep_script_exec(iph1->rmconf->script[script]->v,
3700 script, envp) != 0)
3701 plog(LLV_ERROR, LOCATION, NULL,
3702 "Script %s execution failed\n", script_names[script]);
3703
3704 out:
3705 for (c = envp; *c; c++)
3706 racoon_free(*c);
3707
3708 racoon_free(envp);
3709
3710 return;
3711 }
3712
3713 int
3714 script_env_append(envp, envc, name, value)
3715 char ***envp;
3716 int *envc;
3717 char *name;
3718 char *value;
3719 {
3720 char *envitem;
3721 char **newenvp;
3722 int newenvc;
3723 int envitem_len;
3724
3725 envitem_len = strlen(name) + 1 + strlen(value) + 1;
3726 envitem = racoon_malloc(envitem_len);
3727 if (envitem == NULL) {
3728 plog(LLV_ERROR, LOCATION, NULL,
3729 "Cannot allocate memory: %s\n", strerror(errno));
3730 return -1;
3731 }
3732 snprintf(envitem, envitem_len, "%s=%s", name, value);
3733
3734 newenvc = (*envc) + 1;
3735 newenvp = racoon_realloc(*envp, newenvc * sizeof(char *));
3736 if (newenvp == NULL) {
3737 plog(LLV_ERROR, LOCATION, NULL,
3738 "Cannot allocate memory: %s\n", strerror(errno));
3739 racoon_free(envitem);
3740 return -1;
3741 }
3742
3743 newenvp[newenvc - 2] = envitem;
3744 newenvp[newenvc - 1] = NULL;
3745
3746 *envp = newenvp;
3747 *envc = newenvc;
3748 return 0;
3749 }
3750
3751 int
3752 script_exec(script, name, envp)
3753 char *script;
3754 int name;
3755 char *const envp[];
3756 {
3757 char *argv[] = { NULL, NULL, NULL };
3758
3759 argv[0] = script;
3760 argv[1] = script_names[name];
3761 argv[2] = NULL;
3762
3763 switch (fork()) {
3764 case 0:
3765 execve(argv[0], argv, envp);
3766 plog(LLV_ERROR, LOCATION, NULL,
3767 "execve(\"%s\") failed: %s\n",
3768 argv[0], strerror(errno));
3769 _exit(1);
3770 break;
3771 case -1:
3772 plog(LLV_ERROR, LOCATION, NULL,
3773 "Cannot fork: %s\n", strerror(errno));
3774 return -1;
3775 break;
3776 default:
3777 break;
3778 }
3779
3780 return 0;
3781 }
3782
3783 void
3784 purge_remote(iph1)
3785 struct ph1handle *iph1;
3786 {
3787 vchar_t *buf = NULL;
3788 struct sadb_msg *msg, *next, *end;
3789 struct sadb_sa *sa;
3790 struct sockaddr *src, *dst;
3791 caddr_t mhp[SADB_EXT_MAX + 1];
3792 u_int proto_id;
3793 struct ph2handle *iph2;
3794 struct ph1handle *new_iph1;
3795
3796 plog(LLV_INFO, LOCATION, NULL,
3797 "purging ISAKMP-SA spi=%s.\n",
3798 isakmp_pindex(&(iph1->index), iph1->msgid));
3799
3800 /* Mark as expired. */
3801 iph1->status = PHASE1ST_EXPIRED;
3802
3803 new_iph1 = ike_session_update_ph1_ph2tree(iph1);
3804
3805 /*
3806 * Delete all orphaned or binded to the deleting ph1handle phase2 SAs.
3807 * Keep all others phase2 SAs.
3808 */
3809 buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
3810 if (buf == NULL) {
3811 plog(LLV_DEBUG, LOCATION, NULL,
3812 "pfkey_dump_sadb returned nothing.\n");
3813 return;
3814 }
3815
3816 msg = (struct sadb_msg *)buf->v;
3817 end = (struct sadb_msg *)(buf->v + buf->l);
3818
3819 while (msg < end) {
3820 if ((msg->sadb_msg_len << 3) < sizeof(*msg))
3821 break;
3822 next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
3823 if (msg->sadb_msg_type != SADB_DUMP) {
3824 msg = next;
3825 continue;
3826 }
3827
3828 if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
3829 plog(LLV_ERROR, LOCATION, NULL,
3830 "pfkey_check (%s)\n", ipsec_strerror());
3831 msg = next;
3832 continue;
3833 }
3834
3835 sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
3836 if (!sa ||
3837 !mhp[SADB_EXT_ADDRESS_SRC] ||
3838 !mhp[SADB_EXT_ADDRESS_DST]) {
3839 msg = next;
3840 continue;
3841 }
3842 src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
3843 dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
3844
3845 if (sa->sadb_sa_state != SADB_SASTATE_LARVAL &&
3846 sa->sadb_sa_state != SADB_SASTATE_MATURE &&
3847 sa->sadb_sa_state != SADB_SASTATE_DYING) {
3848 msg = next;
3849 continue;
3850 }
3851
3852 /*
3853 * check in/outbound SAs.
3854 * Select only SAs where src == local and dst == remote (outgoing)
3855 * or src == remote and dst == local (incoming).
3856 */
3857 if ((CMPSADDR(iph1->local, src) || CMPSADDR(iph1->remote, dst)) &&
3858 (CMPSADDR(iph1->local, dst) || CMPSADDR(iph1->remote, src))) {
3859 msg = next;
3860 continue;
3861 }
3862
3863 proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
3864 iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
3865
3866 /* Check if there is another valid ISAKMP-SA */
3867 if (new_iph1 != NULL) {
3868
3869 if (iph2 == NULL) {
3870 /* No handler... still send a pfkey_delete message, but log this !*/
3871 plog(LLV_INFO, LOCATION, NULL,
3872 "Unknown IPsec-SA spi=%u, hmmmm?\n",
3873 ntohl(sa->sadb_sa_spi));
3874 }else{
3875
3876 /*
3877 * If we have a new ph1, do not purge IPsec-SAs binded
3878 * to a different ISAKMP-SA
3879 */
3880 if (iph2->ph1 != NULL && iph2->ph1 != iph1){
3881 msg = next;
3882 continue;
3883 }
3884
3885 /* If the ph2handle is established, do not purge IPsec-SA */
3886 if (iph2->status == PHASE2ST_ESTABLISHED ||
3887 iph2->status == PHASE2ST_EXPIRED) {
3888
3889 plog(LLV_INFO, LOCATION, NULL,
3890 "keeping IPsec-SA spi=%u - found valid ISAKMP-SA spi=%s.\n",
3891 ntohl(sa->sadb_sa_spi),
3892 isakmp_pindex(&(new_iph1->index), new_iph1->msgid));
3893 msg = next;
3894 continue;
3895 }
3896 }
3897 }
3898
3899
3900 pfkey_send_delete(lcconf->sock_pfkey,
3901 msg->sadb_msg_satype,
3902 IPSEC_MODE_ANY,
3903 src, dst, sa->sadb_sa_spi);
3904
3905 /* delete a relative phase 2 handle. */
3906 if (iph2 != NULL) {
3907 delete_spd(iph2);
3908 unbindph12(iph2);
3909 remph2(iph2);
3910 delph2(iph2);
3911 }
3912
3913 plog(LLV_INFO, LOCATION, NULL,
3914 "purged IPsec-SA spi=%u.\n",
3915 ntohl(sa->sadb_sa_spi));
3916
3917 msg = next;
3918 }
3919
3920 if (buf)
3921 vfree(buf);
3922
3923 /* Mark the phase1 handler as EXPIRED */
3924 plog(LLV_INFO, LOCATION, NULL,
3925 "purged ISAKMP-SA spi=%s.\n",
3926 isakmp_pindex(&(iph1->index), iph1->msgid));
3927
3928 SCHED_KILL(iph1->sce);
3929
3930 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
3931 }
3932
3933 void
3934 delete_spd(iph2)
3935 struct ph2handle *iph2;
3936 {
3937 if (iph2 == NULL)
3938 return;
3939
3940 /* Delete the SPD entry if we generated it
3941 */
3942 if (iph2->generated_spidx) {
3943 struct policyindex spidx;
3944 struct sockaddr_storage addr;
3945 u_int8_t pref;
3946 struct sockaddr *src = iph2->src;
3947 struct sockaddr *dst = iph2->dst;
3948 int error;
3949 int idi2type = 0;/* switch whether copy IDs into id[src,dst]. */
3950
3951 plog(LLV_INFO, LOCATION, NULL,
3952 "generated policy, deleting it.\n");
3953
3954 memset(&spidx, 0, sizeof(spidx));
3955 iph2->spidx_gen = (caddr_t )&spidx;
3956
3957 /* make inbound policy */
3958 iph2->src = dst;
3959 iph2->dst = src;
3960 spidx.dir = IPSEC_DIR_INBOUND;
3961 spidx.ul_proto = 0;
3962
3963 /*
3964 * Note: code from get_proposal_r
3965 */
3966
3967 #define _XIDT(d) ((struct ipsecdoi_id_b *)(d)->v)->type
3968
3969 /*
3970 * make destination address in spidx from either ID payload
3971 * or phase 1 address into a address in spidx.
3972 */
3973 if (iph2->id != NULL
3974 && (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
3975 || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR
3976 || _XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR_SUBNET
3977 || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
3978 /* get a destination address of a policy */
3979 error = ipsecdoi_id2sockaddr(iph2->id,
3980 (struct sockaddr *)&spidx.dst,
3981 &spidx.prefd, &spidx.ul_proto);
3982 if (error)
3983 goto purge;
3984
3985 #ifdef INET6
3986 /*
3987 * get scopeid from the SA address.
3988 * note that the phase 1 source address is used as
3989 * a destination address to search for a inbound
3990 * policy entry because rcoon is responder.
3991 */
3992 if (_XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR) {
3993 if ((error =
3994 setscopeid((struct sockaddr *)&spidx.dst,
3995 iph2->src)) != 0)
3996 goto purge;
3997 }
3998 #endif
3999
4000 if (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
4001 || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR)
4002 idi2type = _XIDT(iph2->id);
4003
4004 } else {
4005
4006 plog(LLV_DEBUG, LOCATION, NULL,
4007 "get a destination address of SP index "
4008 "from phase1 address "
4009 "due to no ID payloads found "
4010 "OR because ID type is not address.\n");
4011
4012 /*
4013 * copy the SOURCE address of IKE into the
4014 * DESTINATION address of the key to search the
4015 * SPD because the direction of policy is inbound.
4016 */
4017 memcpy(&spidx.dst, iph2->src, sysdep_sa_len(iph2->src));
4018 switch (spidx.dst.ss_family) {
4019 case AF_INET:
4020 spidx.prefd =
4021 sizeof(struct in_addr) << 3;
4022 break;
4023 #ifdef INET6
4024 case AF_INET6:
4025 spidx.prefd =
4026 sizeof(struct in6_addr) << 3;
4027 break;
4028 #endif
4029 default:
4030 spidx.prefd = 0;
4031 break;
4032 }
4033 }
4034
4035 /* make source address in spidx */
4036 if (iph2->id_p != NULL
4037 && (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR
4038 || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR
4039 || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR_SUBNET
4040 || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
4041 /* get a source address of inbound SA */
4042 error = ipsecdoi_id2sockaddr(iph2->id_p,
4043 (struct sockaddr *)&spidx.src,
4044 &spidx.prefs, &spidx.ul_proto);
4045 if (error)
4046 goto purge;
4047
4048 #ifdef INET6
4049 /*
4050 * get scopeid from the SA address.
4051 * for more detail, see above of this function.
4052 */
4053 if (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR) {
4054 error =
4055 setscopeid((struct sockaddr *)&spidx.src,
4056 iph2->dst);
4057 if (error)
4058 goto purge;
4059 }
4060 #endif
4061
4062 /* make id[src,dst] if both ID types are IP address and same */
4063 if (_XIDT(iph2->id_p) == idi2type
4064 && spidx.dst.ss_family == spidx.src.ss_family) {
4065 iph2->src_id =
4066 dupsaddr((struct sockaddr *)&spidx.dst);
4067 iph2->dst_id =
4068 dupsaddr((struct sockaddr *)&spidx.src);
4069 }
4070
4071 } else {
4072 plog(LLV_DEBUG, LOCATION, NULL,
4073 "get a source address of SP index "
4074 "from phase1 address "
4075 "due to no ID payloads found "
4076 "OR because ID type is not address.\n");
4077
4078 /* see above comment. */
4079 memcpy(&spidx.src, iph2->dst, sysdep_sa_len(iph2->dst));
4080 switch (spidx.src.ss_family) {
4081 case AF_INET:
4082 spidx.prefs =
4083 sizeof(struct in_addr) << 3;
4084 break;
4085 #ifdef INET6
4086 case AF_INET6:
4087 spidx.prefs =
4088 sizeof(struct in6_addr) << 3;
4089 break;
4090 #endif
4091 default:
4092 spidx.prefs = 0;
4093 break;
4094 }
4095 }
4096
4097 #undef _XIDT
4098
4099 plog(LLV_DEBUG, LOCATION, NULL,
4100 "get a src address from ID payload "
4101 "%s prefixlen=%u ul_proto=%u\n",
4102 saddr2str((struct sockaddr *)&spidx.src),
4103 spidx.prefs, spidx.ul_proto);
4104 plog(LLV_DEBUG, LOCATION, NULL,
4105 "get dst address from ID payload "
4106 "%s prefixlen=%u ul_proto=%u\n",
4107 saddr2str((struct sockaddr *)&spidx.dst),
4108 spidx.prefd, spidx.ul_proto);
4109
4110 /*
4111 * convert the ul_proto if it is 0
4112 * because 0 in ID payload means a wild card.
4113 */
4114 if (spidx.ul_proto == 0)
4115 spidx.ul_proto = IPSEC_ULPROTO_ANY;
4116
4117 #undef _XIDT
4118
4119 /* End of code from get_proposal_r
4120 */
4121
4122 if (pk_sendspddelete(iph2) < 0) {
4123 plog(LLV_ERROR, LOCATION, NULL,
4124 "pfkey spddelete(inbound) failed.\n");
4125 }else{
4126 plog(LLV_DEBUG, LOCATION, NULL,
4127 "pfkey spddelete(inbound) sent.\n");
4128 }
4129
4130 #ifdef HAVE_POLICY_FWD
4131 /* make forward policy if required */
4132 if (tunnel_mode_prop(iph2->approval)) {
4133 spidx.dir = IPSEC_DIR_FWD;
4134 if (pk_sendspddelete(iph2) < 0) {
4135 plog(LLV_ERROR, LOCATION, NULL,
4136 "pfkey spddelete(forward) failed.\n");
4137 }else{
4138 plog(LLV_DEBUG, LOCATION, NULL,
4139 "pfkey spddelete(forward) sent.\n");
4140 }
4141 }
4142 #endif
4143
4144 /* make outbound policy */
4145 iph2->src = src;
4146 iph2->dst = dst;
4147 spidx.dir = IPSEC_DIR_OUTBOUND;
4148 addr = spidx.src;
4149 spidx.src = spidx.dst;
4150 spidx.dst = addr;
4151 pref = spidx.prefs;
4152 spidx.prefs = spidx.prefd;
4153 spidx.prefd = pref;
4154
4155 if (pk_sendspddelete(iph2) < 0) {
4156 plog(LLV_ERROR, LOCATION, NULL,
4157 "pfkey spddelete(outbound) failed.\n");
4158 }else{
4159 plog(LLV_DEBUG, LOCATION, NULL,
4160 "pfkey spddelete(outbound) sent.\n");
4161 }
4162 purge:
4163 iph2->spidx_gen=NULL;
4164 }
4165 }
4166
4167 #ifdef INET6
4168 u_int32_t
4169 setscopeid(sp_addr0, sa_addr0)
4170 struct sockaddr *sp_addr0, *sa_addr0;
4171 {
4172 struct sockaddr_in6 *sp_addr, *sa_addr;
4173
4174 sp_addr = (struct sockaddr_in6 *)sp_addr0;
4175 sa_addr = (struct sockaddr_in6 *)sa_addr0;
4176
4177 if (!IN6_IS_ADDR_LINKLOCAL(&sp_addr->sin6_addr)
4178 && !IN6_IS_ADDR_SITELOCAL(&sp_addr->sin6_addr)
4179 && !IN6_IS_ADDR_MULTICAST(&sp_addr->sin6_addr))
4180 return 0;
4181
4182 /* this check should not be here ? */
4183 if (sa_addr->sin6_family != AF_INET6) {
4184 plog(LLV_ERROR, LOCATION, NULL,
4185 "can't get scope ID: family mismatch\n");
4186 return -1;
4187 }
4188
4189 if (!IN6_IS_ADDR_LINKLOCAL(&sa_addr->sin6_addr)) {
4190 plog(LLV_ERROR, LOCATION, NULL,
4191 "scope ID is not supported except of lladdr.\n");
4192 return -1;
4193 }
4194
4195 sp_addr->sin6_scope_id = sa_addr->sin6_scope_id;
4196
4197 return 0;
4198 }
4199 #endif