]> git.saurik.com Git - apple/ipsec.git/blob - ipsec-tools/racoon/isakmp.c
050ca4216a127b169a9e06491de39006802bae2b
[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 } else {
2321 ike_session_ph2_retransmits(iph2);
2322 }
2323
2324 if (isakmp_send(iph2->ph1, iph2->sendbuf) < 0){
2325 if (iph2->ph1->rmconf->retry_counter != iph2->retry_counter) {
2326 IPSECSESSIONTRACEREVENT(iph2->ph1->parent_session,
2327 IPSECSESSIONEVENTCODE_IKE_PACKET_TX_FAIL,
2328 CONSTSTR("Phase2 Retransmit"),
2329 CONSTSTR("Failed to retransmit Phase2 message"));
2330 }
2331 plog(LLV_ERROR, LOCATION, NULL,
2332 "phase2 negotiation failed due to send error. %s\n",
2333 isakmp_pindex(&iph2->ph1->index, iph2->msgid));
2334 EVT_PUSH(iph2->src, iph2->dst, EVTT_PEER_NO_RESPONSE, NULL);
2335
2336 return -1;
2337 }
2338 if (iph2->ph1->rmconf->retry_counter != iph2->retry_counter) {
2339 IPSECSESSIONTRACEREVENT(iph2->ph1->parent_session,
2340 IPSECSESSIONEVENTCODE_IKE_PACKET_TX_SUCC,
2341 CONSTSTR("Phase2 Retransmit"),
2342 CONSTSTR(NULL));
2343 }
2344
2345 plog(LLV_DEBUG, LOCATION, NULL,
2346 "resend phase2 packet %s\n",
2347 isakmp_pindex(&iph2->ph1->index, iph2->msgid));
2348
2349 iph2->retry_counter--;
2350
2351 iph2->scr = sched_new(iph2->ph1->rmconf->retry_interval,
2352 isakmp_ph2resend_stub, iph2);
2353
2354 #ifdef ENABLE_DPD
2355 if (iph2->scr) {
2356 isakmp_reschedule_info_monitor_if_pending(iph2->ph1,
2357 "phase2 packets sent to peer: retransmit timer armed");
2358 }
2359 #endif /* DPD */
2360
2361 return 0;
2362 }
2363
2364 /* called from scheduler */
2365 void
2366 isakmp_ph1expire_stub(p)
2367 void *p;
2368 {
2369
2370 isakmp_ph1expire((struct ph1handle *)p);
2371 }
2372
2373 void
2374 isakmp_ph1expire(iph1)
2375 struct ph1handle *iph1;
2376 {
2377 char *src, *dst;
2378
2379 SCHED_KILL(iph1->sce);
2380 #ifdef ENABLE_DPD
2381 SCHED_KILL(iph1->dpd_r_u);
2382 #endif
2383
2384 if(iph1->status != PHASE1ST_EXPIRED){
2385 src = racoon_strdup(saddr2str(iph1->local));
2386 dst = racoon_strdup(saddr2str(iph1->remote));
2387 STRDUP_FATAL(src);
2388 STRDUP_FATAL(dst);
2389
2390 plog(LLV_INFO, LOCATION, NULL,
2391 "ISAKMP-SA expired %s-%s spi:%s\n",
2392 src, dst,
2393 isakmp_pindex(&iph1->index, 0));
2394 racoon_free(src);
2395 racoon_free(dst);
2396 iph1->status = PHASE1ST_EXPIRED;
2397 (void)ike_session_update_ph1_ph2tree(iph1);
2398 }
2399
2400 /*
2401 * the phase1 deletion is postponed until there is no phase2.
2402 */
2403 if (LIST_FIRST(&iph1->ph2tree) != NULL) {
2404 iph1->sce = sched_new(1, isakmp_ph1expire_stub, iph1);
2405 return;
2406 }
2407
2408 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
2409 }
2410
2411 /* called from scheduler */
2412 void
2413 isakmp_ph1rekeyexpire_stub(p)
2414 void *p;
2415 {
2416
2417 isakmp_ph1rekeyexpire((struct ph1handle *)p, FALSE);
2418 }
2419
2420 void
2421 isakmp_ph1rekeyexpire(iph1, ignore_sess_drop_policy)
2422 struct ph1handle *iph1;
2423 int ignore_sess_drop_policy;
2424 {
2425 char *src, *dst;
2426 struct remoteconf *rmconf;
2427
2428 SCHED_KILL(iph1->sce_rekey);
2429
2430 // early exit if iph2->sce == NULL, iph2 isn't established or if entire session is going down
2431 if (iph1->sce == NULL ||
2432 iph1->status != PHASE1ST_ESTABLISHED ||
2433 iph1->is_dying) {
2434 return;
2435 }
2436
2437 src = racoon_strdup(saddr2str(iph1->local));
2438 dst = racoon_strdup(saddr2str(iph1->remote));
2439 STRDUP_FATAL(src);
2440 STRDUP_FATAL(dst);
2441
2442 plog(LLV_INFO, LOCATION, NULL,
2443 "ISAKMP-SA rekey-timer expired %s-%s spi:%s\n",
2444 src, dst,
2445 isakmp_pindex(&iph1->index, 0));
2446 racoon_free(src);
2447 racoon_free(dst);
2448
2449 if (!ignore_sess_drop_policy && ike_session_drop_rekey(iph1->parent_session)) {
2450 return;
2451 }
2452
2453 // exit if there is another ph1 that is established (with a pending rekey timer)
2454 if (ike_session_has_other_established_ph1(iph1->parent_session, iph1)) {
2455 plog(LLV_INFO, LOCATION, iph1->remote,
2456 "request for ISAKMP-SA rekey was ignored "
2457 "due to another established ph1.\n");
2458 return;
2459 }
2460
2461 // if there is another ph1 that is negotiating, postpone this rekey for a few seconds later
2462 if (ike_session_has_other_negoing_ph1(iph1->parent_session, iph1)) {
2463 plog(LLV_DEBUG, LOCATION, NULL, "reschedule Phase1 rekey.\n");
2464 iph1->sce_rekey = sched_new(1,
2465 isakmp_ph1rekeyexpire_stub,
2466 iph1);
2467 return;
2468 }
2469
2470 // get rmconf to initiate rekey with
2471 rmconf = iph1->rmconf;
2472 if (!rmconf || rmconf->to_delete || rmconf->to_remove) {
2473 rmconf = getrmconf(iph1->remote);
2474 }
2475 if (rmconf) {
2476 /* begin quick mode */
2477 plog(LLV_DEBUG, LOCATION, NULL, "begin Phase1 rekey.\n");
2478
2479 /* start phase 1 negotiation as a initiator. */
2480 if (isakmp_ph1begin_i(rmconf, iph1->remote, iph1->local, 0) < 0) {
2481 plog(LLV_DEBUG, LOCATION, NULL, "Phase1 rekey Failed.\n");
2482 }
2483 } else {
2484 plog(LLV_ERROR, LOCATION, NULL,
2485 "Phase1 rekey failed: no configuration found for %s.\n",
2486 saddrwop2str(iph1->remote));
2487 }
2488 }
2489
2490 int
2491 isakmp_ph1rekeyretry(iph1)
2492 struct ph1handle *iph1;
2493 {
2494 char *src, *dst;
2495 struct remoteconf *rmconf;
2496
2497 // this code path is meant for floated ph1 rekeys that are failing on the first message
2498 if (iph1->sce != NULL ||
2499 iph1->sce_rekey != NULL ||
2500 (iph1->status != PHASE1ST_MSG1SENT || (iph1->natt_flags & NAT_PORTS_CHANGED == 0)) ||
2501 (extract_port(iph1->local) != PORT_ISAKMP_NATT && extract_port(iph1->remote) != PORT_ISAKMP_NATT) ||
2502 iph1->is_dying) {
2503 return -1;
2504 }
2505
2506 src = racoon_strdup(saddr2str(iph1->local));
2507 dst = racoon_strdup(saddr2str(iph1->remote));
2508 STRDUP_FATAL(src);
2509 STRDUP_FATAL(dst);
2510
2511 plog(LLV_INFO, LOCATION, NULL,
2512 "ISAKMP-SA rekey failed... retrying %s-%s spi:%s\n",
2513 src, dst,
2514 isakmp_pindex(&iph1->index, 0));
2515 racoon_free(src);
2516 racoon_free(dst);
2517
2518 // exit if there is another ph1 that is established (with a pending rekey timer)
2519 if (ike_session_has_other_established_ph1(iph1->parent_session, iph1)) {
2520 plog(LLV_INFO, LOCATION, iph1->remote,
2521 "request to retry ISAKMP-SA rekey was ignored "
2522 "due to another established ph1.\n");
2523 return -1;
2524 }
2525
2526 // some servers don't like respond to 4500 for rekeys... try accomodate them
2527 if (extract_port(iph1->local) == PORT_ISAKMP_NATT) {
2528 set_port(iph1->local, PORT_ISAKMP);
2529 }
2530 if (extract_port(iph1->remote) == PORT_ISAKMP_NATT) {
2531 set_port(iph1->remote, PORT_ISAKMP);
2532 }
2533 iph1->natt_flags &= ~NAT_PORTS_CHANGED;
2534 rmconf = getrmconf(iph1->remote);
2535 if (rmconf) {
2536 /* begin quick mode */
2537 plog(LLV_DEBUG, LOCATION, NULL, "begin Phase1 rekey retry.\n");
2538
2539 /* start phase 1 negotiation as a initiator. */
2540 if (isakmp_ph1begin_i(rmconf, iph1->remote, iph1->local, 0) < 0) {
2541 plog(LLV_DEBUG, LOCATION, NULL, "Phase1 rekey retry Failed.\n");
2542 return -1;
2543 }
2544 } else {
2545 plog(LLV_ERROR, LOCATION, NULL,
2546 "Phase1 rekey retry failed: no configuration found for %s.\n",
2547 saddrwop2str(iph1->remote));
2548 return -1;
2549 }
2550 return 0;
2551 }
2552
2553 /* called from scheduler */
2554 void
2555 isakmp_ph1delete_stub(p)
2556 void *p;
2557 {
2558
2559 isakmp_ph1delete((struct ph1handle *)p);
2560 }
2561
2562 void
2563 isakmp_ph1delete(iph1)
2564 struct ph1handle *iph1;
2565 {
2566 char *src, *dst;
2567
2568 SCHED_KILL(iph1->sce);
2569 SCHED_KILL(iph1->sce_rekey);
2570 #ifdef ENABLE_DPD
2571 SCHED_KILL(iph1->dpd_r_u);
2572 #endif
2573
2574 if (LIST_FIRST(&iph1->ph2tree) != NULL) {
2575 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
2576 return;
2577 }
2578
2579 isakmp_info_send_d1(iph1);
2580
2581 /* don't re-negosiation when the phase 1 SA expires. */
2582
2583 src = racoon_strdup(saddr2str(iph1->local));
2584 dst = racoon_strdup(saddr2str(iph1->remote));
2585 STRDUP_FATAL(src);
2586 STRDUP_FATAL(dst);
2587
2588 plog(LLV_INFO, LOCATION, NULL,
2589 "ISAKMP-SA deleted %s-%s spi:%s\n",
2590 src, dst, isakmp_pindex(&iph1->index, 0));
2591 EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_DOWN, NULL);
2592 racoon_free(src);
2593 racoon_free(dst);
2594
2595 remph1(iph1);
2596 delph1(iph1);
2597
2598 return;
2599 }
2600
2601 /* called from scheduler.
2602 * this function will call only isakmp_ph2delete().
2603 * phase 2 handler remain forever if kernel doesn't cry a expire of phase 2 SA
2604 * by something cause. That's why this function is called after phase 2 SA
2605 * expires in the userland.
2606 */
2607 void
2608 isakmp_ph2expire_stub(p)
2609 void *p;
2610 {
2611
2612 isakmp_ph2expire((struct ph2handle *)p);
2613 }
2614
2615 void
2616 isakmp_ph2expire(iph2)
2617 struct ph2handle *iph2;
2618 {
2619 char *src, *dst;
2620
2621 if (iph2->status == PHASE2ST_EXPIRED) {
2622 return;
2623 }
2624
2625 SCHED_KILL(iph2->sce);
2626
2627 src = racoon_strdup(saddrwop2str(iph2->src));
2628 dst = racoon_strdup(saddrwop2str(iph2->dst));
2629 STRDUP_FATAL(src);
2630 STRDUP_FATAL(dst);
2631
2632 plog(LLV_INFO, LOCATION, NULL,
2633 "phase2 sa expired %s-%s\n", src, dst);
2634 racoon_free(src);
2635 racoon_free(dst);
2636
2637 // delete outgoing SAs
2638 if (iph2->status == PHASE2ST_ESTABLISHED && iph2->approval) {
2639 struct saproto *pr;
2640
2641 for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
2642 if (pr->ok) {
2643 pfkey_send_delete(lcconf->sock_pfkey,
2644 ipsecdoi2pfkey_proto(pr->proto_id),
2645 IPSEC_MODE_ANY,
2646 iph2->src, iph2->dst, pr->spi_p /* pr->reqid_out */);
2647 }
2648 }
2649 }
2650
2651 iph2->status = PHASE2ST_EXPIRED;
2652
2653 iph2->sce = sched_new(1, isakmp_ph2delete_stub, iph2);
2654
2655 return;
2656 }
2657
2658 /* called from scheduler */
2659 void
2660 isakmp_ph2delete_stub(p)
2661 void *p;
2662 {
2663
2664 isakmp_ph2delete((struct ph2handle *)p);
2665 }
2666
2667 void
2668 isakmp_ph2delete(iph2)
2669 struct ph2handle *iph2;
2670 {
2671 char *src, *dst;
2672
2673 SCHED_KILL(iph2->sce);
2674
2675 src = racoon_strdup(saddrwop2str(iph2->src));
2676 dst = racoon_strdup(saddrwop2str(iph2->dst));
2677 STRDUP_FATAL(src);
2678 STRDUP_FATAL(dst);
2679
2680 plog(LLV_INFO, LOCATION, NULL,
2681 "phase2 sa deleted %s-%s\n", src, dst);
2682 racoon_free(src);
2683 racoon_free(dst);
2684
2685 unbindph12(iph2);
2686 remph2(iph2);
2687 delph2(iph2);
2688
2689 return;
2690 }
2691
2692 /* \f%%%
2693 * Interface between PF_KEYv2 and ISAKMP
2694 */
2695 /*
2696 * receive ACQUIRE from kernel, and begin either phase1 or phase2.
2697 * if phase1 has been finished, begin phase2.
2698 */
2699 int
2700 isakmp_post_acquire(iph2)
2701 struct ph2handle *iph2;
2702 {
2703 struct remoteconf *rmconf;
2704 struct ph1handle *iph1 = NULL;
2705
2706 plog(LLV_DEBUG, LOCATION, NULL, "in post_acquire\n");
2707
2708 /* search appropreate configuration with masking port. */
2709 rmconf = getrmconf(iph2->dst);
2710 if (rmconf == NULL) {
2711 plog(LLV_ERROR, LOCATION, NULL,
2712 "no configuration found for %s.\n",
2713 saddrwop2str(iph2->dst));
2714 return -1;
2715 }
2716
2717 /* if passive mode, ignore the acquire message */
2718 if (rmconf->passive) {
2719 plog(LLV_DEBUG, LOCATION, NULL,
2720 "because of passive mode, "
2721 "ignore the acquire message for %s.\n",
2722 saddrwop2str(iph2->dst));
2723 return 0;
2724 }
2725
2726 if (ike_session_verify_ph2_parent_session(iph2)) {
2727 plog(LLV_INFO, LOCATION, iph2->dst,
2728 "request for establishing IPsec-SA was ignored "
2729 "because there was a failure verifying parent session.\n");
2730 return -1;
2731 }
2732
2733 // what if there is another ph2 that is negotiating
2734 if (ike_session_has_other_negoing_ph2(iph2->parent_session, iph2)) {
2735 // TODO: postpone this rekey for a second later
2736 plog(LLV_INFO, LOCATION, iph2->dst,
2737 "request for establishing IPsec-SA was ignored "
2738 "due to another negoing ph2.\n");
2739 return -1;
2740 }
2741
2742 // if this is a phase2 rekeys (the policy may not have the current port number).
2743 // so, use the appropriate ports.
2744 if (iph2->is_rekey) {
2745 ike_session_update_ph2_ports(iph2);
2746 }
2747
2748 iph1 = ike_session_update_ph2_ph1bind(iph2);
2749
2750 /* no ISAKMP-SA found. */
2751 if (iph1 == NULL) {
2752 struct sched *sc;
2753
2754 iph2->retry_checkph1 = lcconf->retry_checkph1;
2755 sc = sched_new(1, isakmp_chkph1there_stub, iph2);
2756 plog(LLV_INFO, LOCATION, NULL,
2757 "IPsec-SA request for %s queued "
2758 "due to no phase1 found.\n",
2759 saddrwop2str(iph2->dst));
2760
2761 /* start phase 1 negotiation as a initiator. */
2762 if (isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src, 0) < 0) {
2763 SCHED_KILL(sc);
2764 return -1;
2765 }
2766
2767 return 0;
2768 /*NOTREACHED*/
2769 }
2770
2771 /* found ISAKMP-SA, but on negotiation. */
2772 if (iph1->status != PHASE1ST_ESTABLISHED) {
2773 iph2->retry_checkph1 = lcconf->retry_checkph1;
2774 sched_new(1, isakmp_chkph1there_stub, iph2);
2775 plog(LLV_INFO, LOCATION, iph2->dst,
2776 "request for establishing IPsec-SA was queued "
2777 "due to no phase1 found.\n");
2778 return 0;
2779 /*NOTREACHED*/
2780 }
2781
2782 /* found established ISAKMP-SA */
2783 /* i.e. iph1->status == PHASE1ST_ESTABLISHED */
2784
2785 /* found ISAKMP-SA. */
2786 plog(LLV_DEBUG, LOCATION, NULL, "begin QUICK mode.\n");
2787
2788 /* begin quick mode */
2789 if (isakmp_ph2begin_i(iph1, iph2))
2790 return -1;
2791
2792 return 0;
2793 }
2794
2795 /*
2796 * receive GETSPI from kernel.
2797 */
2798 int
2799 isakmp_post_getspi(iph2)
2800 struct ph2handle *iph2;
2801 {
2802 #ifdef ENABLE_STATS
2803 struct timeval start, end;
2804 #endif
2805
2806 /* don't process it because there is no suitable phase1-sa. */
2807 if (iph2->ph1->status == PHASE1ST_EXPIRED) {
2808 plog(LLV_ERROR, LOCATION, iph2->ph1->remote,
2809 "the negotiation is stopped, "
2810 "because there is no suitable ISAKMP-SA.\n");
2811 return -1;
2812 }
2813
2814 #ifdef ENABLE_STATS
2815 gettimeofday(&start, NULL);
2816 #endif
2817 if ((ph2exchange[etypesw2(ISAKMP_ETYPE_QUICK)]
2818 [iph2->side]
2819 [iph2->status])(iph2, NULL) != 0)
2820 return -1;
2821 #ifdef ENABLE_STATS
2822 gettimeofday(&end, NULL);
2823 syslog(LOG_NOTICE, "%s(%s): %8.6f",
2824 "phase2",
2825 s_isakmp_state(ISAKMP_ETYPE_QUICK, iph2->side, iph2->status),
2826 timedelta(&start, &end));
2827 #endif
2828
2829 return 0;
2830 }
2831
2832 /* called by scheduler */
2833 void
2834 isakmp_chkph1there_stub(p)
2835 void *p;
2836 {
2837 isakmp_chkph1there((struct ph2handle *)p);
2838 }
2839
2840 void
2841 isakmp_chkph1there(iph2)
2842 struct ph2handle *iph2;
2843 {
2844 struct ph1handle *iph1;
2845
2846 iph2->retry_checkph1--;
2847 if (iph2->retry_checkph1 < 0 ||
2848 ike_session_verify_ph2_parent_session(iph2)) {
2849 if (iph2->retry_checkph1 < 0) {
2850 plog(LLV_ERROR, LOCATION, iph2->dst,
2851 "phase2 negotiation failed "
2852 "due to time up waiting for phase1. %s\n",
2853 sadbsecas2str(iph2->dst, iph2->src,
2854 iph2->satype, 0, 0));
2855 } else {
2856 plog(LLV_ERROR, LOCATION, iph2->dst,
2857 "phase2 negotiation failed "
2858 "due to invalid parent session. %s\n",
2859 sadbsecas2str(iph2->dst, iph2->src,
2860 iph2->satype, 0, 0));
2861 }
2862 plog(LLV_INFO, LOCATION, NULL,
2863 "delete phase 2 handler.\n");
2864
2865 /* send acquire to kernel as error */
2866 pk_sendeacquire(iph2);
2867
2868 unbindph12(iph2);
2869 remph2(iph2);
2870 delph2(iph2);
2871
2872 return;
2873 }
2874
2875 iph1 = ike_session_update_ph2_ph1bind(iph2);
2876
2877 /* XXX Even if ph1 as responder is there, should we not start
2878 * phase 2 negotiation ? */
2879 if (iph1 != NULL
2880 && iph1->status == PHASE1ST_ESTABLISHED) {
2881 /* found isakmp-sa */
2882
2883 plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: got a ph1 handler, setting ports.\n");
2884 plog(LLV_DEBUG2, LOCATION, NULL, "iph1->local: %s\n", saddr2str(iph1->local));
2885 plog(LLV_DEBUG2, LOCATION, NULL, "iph1->remote: %s\n", saddr2str(iph1->remote));
2886 plog(LLV_DEBUG2, LOCATION, NULL, "before:\n");
2887 plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2888 plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2889 set_port(iph2->src, extract_port(iph1->local));
2890 set_port(iph2->dst, extract_port(iph1->remote));
2891 plog(LLV_DEBUG2, LOCATION, NULL, "After:\n");
2892 plog(LLV_DEBUG2, LOCATION, NULL, "src: %s\n", saddr2str(iph2->src));
2893 plog(LLV_DEBUG2, LOCATION, NULL, "dst: %s\n", saddr2str(iph2->dst));
2894
2895 /* begin quick mode */
2896 if (isakmp_ph2begin_i(iph1, iph2)) {
2897 unbindph12(iph2);
2898 remph2(iph2);
2899 delph2(iph2);
2900 }
2901 return;
2902 }
2903 if (!ike_session_has_negoing_ph1(iph2->parent_session)) {
2904 struct remoteconf *rmconf = getrmconf(iph2->dst);
2905 /* start phase 1 negotiation as a initiator. */
2906 if (rmconf == NULL ||
2907 isakmp_ph1begin_i(rmconf, iph2->dst, iph2->src, 0) < 0) {
2908 plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established/negoing ph1 handler found... failed to initiate new one\n");
2909 }
2910 }
2911
2912 plog(LLV_DEBUG2, LOCATION, NULL, "CHKPH1THERE: no established ph1 handler found\n");
2913
2914 /* no isakmp-sa found */
2915 sched_new(1, isakmp_chkph1there_stub, iph2);
2916
2917 return;
2918 }
2919
2920 /* copy variable data into ALLOCATED buffer. */
2921 caddr_t
2922 isakmp_set_attr_v(buf, type, val, len)
2923 caddr_t buf;
2924 int type;
2925 caddr_t val;
2926 int len;
2927 {
2928 struct isakmp_data *data;
2929
2930 data = (struct isakmp_data *)buf;
2931 data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2932 data->lorv = htons((u_int16_t)len);
2933 memcpy(data + 1, val, len);
2934
2935 return buf + sizeof(*data) + len;
2936 }
2937
2938 /* copy fixed length data into ALLOCATED buffer. */
2939 caddr_t
2940 isakmp_set_attr_l(buf, type, val)
2941 caddr_t buf;
2942 int type;
2943 u_int32_t val;
2944 {
2945 struct isakmp_data *data;
2946
2947 data = (struct isakmp_data *)buf;
2948 data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
2949 data->lorv = htons((u_int16_t)val);
2950
2951 return buf + sizeof(*data);
2952 }
2953
2954 /* add a variable data attribute to the buffer by reallocating it. */
2955 vchar_t *
2956 isakmp_add_attr_v(buf0, type, val, len)
2957 vchar_t *buf0;
2958 int type;
2959 caddr_t val;
2960 int len;
2961 {
2962 vchar_t *buf = NULL;
2963 struct isakmp_data *data;
2964 int tlen;
2965 int oldlen = 0;
2966
2967 tlen = sizeof(*data) + len;
2968
2969 if (buf0) {
2970 oldlen = buf0->l;
2971 buf = vrealloc(buf0, oldlen + tlen);
2972 } else
2973 buf = vmalloc(tlen);
2974 if (!buf) {
2975 plog(LLV_ERROR, LOCATION, NULL,
2976 "failed to get a attribute buffer.\n");
2977 return NULL;
2978 }
2979
2980 data = (struct isakmp_data *)(buf->v + oldlen);
2981 data->type = htons((u_int16_t)type | ISAKMP_GEN_TLV);
2982 data->lorv = htons((u_int16_t)len);
2983 memcpy(data + 1, val, len);
2984
2985 return buf;
2986 }
2987
2988 /* add a fixed data attribute to the buffer by reallocating it. */
2989 vchar_t *
2990 isakmp_add_attr_l(buf0, type, val)
2991 vchar_t *buf0;
2992 int type;
2993 u_int32_t val;
2994 {
2995 vchar_t *buf = NULL;
2996 struct isakmp_data *data;
2997 int tlen;
2998 int oldlen = 0;
2999
3000 tlen = sizeof(*data);
3001
3002 if (buf0) {
3003 oldlen = buf0->l;
3004 buf = vrealloc(buf0, oldlen + tlen);
3005 } else
3006 buf = vmalloc(tlen);
3007 if (!buf) {
3008 plog(LLV_ERROR, LOCATION, NULL,
3009 "failed to get a attribute buffer.\n");
3010 return NULL;
3011 }
3012
3013 data = (struct isakmp_data *)(buf->v + oldlen);
3014 data->type = htons((u_int16_t)type | ISAKMP_GEN_TV);
3015 data->lorv = htons((u_int16_t)val);
3016
3017 return buf;
3018 }
3019
3020 /*
3021 * calculate cookie and set.
3022 */
3023 int
3024 isakmp_newcookie(place, remote, local)
3025 caddr_t place;
3026 struct sockaddr *remote;
3027 struct sockaddr *local;
3028 {
3029 vchar_t *buf = NULL, *buf2 = NULL;
3030 char *p;
3031 int blen;
3032 int alen;
3033 caddr_t sa1, sa2;
3034 time_t t;
3035 int error = -1;
3036 u_short port;
3037
3038
3039 if (remote->sa_family != local->sa_family) {
3040 plog(LLV_ERROR, LOCATION, NULL,
3041 "address family mismatch, remote:%d local:%d\n",
3042 remote->sa_family, local->sa_family);
3043 goto end;
3044 }
3045 switch (remote->sa_family) {
3046 case AF_INET:
3047 alen = sizeof(struct in_addr);
3048 sa1 = (caddr_t)&((struct sockaddr_in *)remote)->sin_addr;
3049 sa2 = (caddr_t)&((struct sockaddr_in *)local)->sin_addr;
3050 break;
3051 #ifdef INET6
3052 case AF_INET6:
3053 alen = sizeof(struct in_addr);
3054 sa1 = (caddr_t)&((struct sockaddr_in6 *)remote)->sin6_addr;
3055 sa2 = (caddr_t)&((struct sockaddr_in6 *)local)->sin6_addr;
3056 break;
3057 #endif
3058 default:
3059 plog(LLV_ERROR, LOCATION, NULL,
3060 "invalid family: %d\n", remote->sa_family);
3061 goto end;
3062 }
3063 blen = (alen + sizeof(u_short)) * 2
3064 + sizeof(time_t) + lcconf->secret_size;
3065 buf = vmalloc(blen);
3066 if (buf == NULL) {
3067 plog(LLV_ERROR, LOCATION, NULL,
3068 "failed to get a cookie.\n");
3069 goto end;
3070 }
3071 p = buf->v;
3072
3073 /* copy my address */
3074 memcpy(p, sa1, alen);
3075 p += alen;
3076 port = ((struct sockaddr_in *)remote)->sin_port;
3077 memcpy(p, &port, sizeof(u_short));
3078 p += sizeof(u_short);
3079
3080 /* copy target address */
3081 memcpy(p, sa2, alen);
3082 p += alen;
3083 port = ((struct sockaddr_in *)local)->sin_port;
3084 memcpy(p, &port, sizeof(u_short));
3085 p += sizeof(u_short);
3086
3087 /* copy time */
3088 t = time(0);
3089 memcpy(p, (caddr_t)&t, sizeof(t));
3090 p += sizeof(t);
3091
3092 /* copy random value */
3093 buf2 = eay_set_random(lcconf->secret_size);
3094 if (buf2 == NULL)
3095 goto end;
3096 memcpy(p, buf2->v, lcconf->secret_size);
3097 p += lcconf->secret_size;
3098 vfree(buf2);
3099
3100 buf2 = eay_sha1_one(buf);
3101 memcpy(place, buf2->v, sizeof(cookie_t));
3102
3103 sa1 = val2str(place, sizeof (cookie_t));
3104 plog(LLV_DEBUG, LOCATION, NULL, "new cookie:\n%s\n", sa1);
3105 racoon_free(sa1);
3106
3107 error = 0;
3108 end:
3109 if (buf != NULL)
3110 vfree(buf);
3111 if (buf2 != NULL)
3112 vfree(buf2);
3113 return error;
3114 }
3115
3116 /*
3117 * save partner's(payload) data into phhandle.
3118 */
3119 int
3120 isakmp_p2ph(buf, gen)
3121 vchar_t **buf;
3122 struct isakmp_gen *gen;
3123 {
3124 /* XXX to be checked in each functions for logging. */
3125 if (*buf) {
3126 plog(LLV_WARNING, LOCATION, NULL,
3127 "ignore this payload, same payload type exist.\n");
3128 return -1;
3129 }
3130
3131 *buf = vmalloc(ntohs(gen->len) - sizeof(*gen));
3132 if (*buf == NULL) {
3133 plog(LLV_ERROR, LOCATION, NULL,
3134 "failed to get buffer.\n");
3135 return -1;
3136 }
3137 memcpy((*buf)->v, gen + 1, (*buf)->l);
3138
3139 return 0;
3140 }
3141
3142 u_int32_t
3143 isakmp_newmsgid2(iph1)
3144 struct ph1handle *iph1;
3145 {
3146 u_int32_t msgid2;
3147
3148 do {
3149 msgid2 = eay_random();
3150 } while (getph2bymsgid(iph1, msgid2));
3151
3152 return msgid2;
3153 }
3154
3155 /*
3156 * set values into allocated buffer of isakmp header for phase 1
3157 */
3158 static caddr_t
3159 set_isakmp_header(vbuf, iph1, nptype, etype, flags, msgid)
3160 vchar_t *vbuf;
3161 struct ph1handle *iph1;
3162 int nptype;
3163 u_int8_t etype;
3164 u_int8_t flags;
3165 u_int32_t msgid;
3166 {
3167 struct isakmp *isakmp;
3168
3169 if (vbuf->l < sizeof(*isakmp))
3170 return NULL;
3171
3172 isakmp = (struct isakmp *)vbuf->v;
3173
3174 memcpy(&isakmp->i_ck, &iph1->index.i_ck, sizeof(cookie_t));
3175 memcpy(&isakmp->r_ck, &iph1->index.r_ck, sizeof(cookie_t));
3176 isakmp->np = nptype;
3177 isakmp->v = iph1->version;
3178 isakmp->etype = etype;
3179 isakmp->flags = flags;
3180 isakmp->msgid = msgid;
3181 isakmp->len = htonl(vbuf->l);
3182
3183 return vbuf->v + sizeof(*isakmp);
3184 }
3185
3186 /*
3187 * set values into allocated buffer of isakmp header for phase 1
3188 */
3189 caddr_t
3190 set_isakmp_header1(vbuf, iph1, nptype)
3191 vchar_t *vbuf;
3192 struct ph1handle *iph1;
3193 int nptype;
3194 {
3195 return set_isakmp_header (vbuf, iph1, nptype, iph1->etype, iph1->flags, iph1->msgid);
3196 }
3197
3198 /*
3199 * set values into allocated buffer of isakmp header for phase 2
3200 */
3201 caddr_t
3202 set_isakmp_header2(vbuf, iph2, nptype)
3203 vchar_t *vbuf;
3204 struct ph2handle *iph2;
3205 int nptype;
3206 {
3207 return set_isakmp_header (vbuf, iph2->ph1, nptype, ISAKMP_ETYPE_QUICK, iph2->flags, iph2->msgid);
3208 }
3209
3210 /*
3211 * set values into allocated buffer of isakmp payload.
3212 */
3213 caddr_t
3214 set_isakmp_payload(buf, src, nptype)
3215 caddr_t buf;
3216 vchar_t *src;
3217 int nptype;
3218 {
3219 struct isakmp_gen *gen;
3220 caddr_t p = buf;
3221
3222 plog(LLV_DEBUG, LOCATION, NULL, "add payload of len %zu, next type %d\n",
3223 src->l, nptype);
3224
3225 gen = (struct isakmp_gen *)p;
3226 gen->np = nptype;
3227 gen->len = htons(sizeof(*gen) + src->l);
3228 p += sizeof(*gen);
3229 memcpy(p, src->v, src->l);
3230 p += src->l;
3231
3232 return p;
3233 }
3234
3235 static int
3236 etypesw1(etype)
3237 int etype;
3238 {
3239 switch (etype) {
3240 case ISAKMP_ETYPE_IDENT:
3241 return 1;
3242 case ISAKMP_ETYPE_AGG:
3243 return 2;
3244 case ISAKMP_ETYPE_BASE:
3245 return 3;
3246 default:
3247 return 0;
3248 }
3249 /*NOTREACHED*/
3250 }
3251
3252 static int
3253 etypesw2(etype)
3254 int etype;
3255 {
3256 switch (etype) {
3257 case ISAKMP_ETYPE_QUICK:
3258 return 1;
3259 default:
3260 return 0;
3261 }
3262 /*NOTREACHED*/
3263 }
3264
3265 #ifdef HAVE_PRINT_ISAKMP_C
3266 /* for print-isakmp.c */
3267 char *snapend;
3268 extern void isakmp_print __P((const u_char *, u_int, const u_char *));
3269
3270 char *getname __P((const u_char *));
3271 #ifdef INET6
3272 char *getname6 __P((const u_char *));
3273 #endif
3274 int safeputchar __P((int));
3275
3276 /*
3277 * Return a name for the IP address pointed to by ap. This address
3278 * is assumed to be in network byte order.
3279 */
3280 char *
3281 getname(ap)
3282 const u_char *ap;
3283 {
3284 struct sockaddr_in addr;
3285 static char ntop_buf[NI_MAXHOST];
3286
3287 memset(&addr, 0, sizeof(addr));
3288 #ifndef __linux__
3289 addr.sin_len = sizeof(struct sockaddr_in);
3290 #endif
3291 addr.sin_family = AF_INET;
3292 memcpy(&addr.sin_addr, ap, sizeof(addr.sin_addr));
3293 if (getnameinfo((struct sockaddr *)&addr, sizeof(addr),
3294 ntop_buf, sizeof(ntop_buf), NULL, 0,
3295 NI_NUMERICHOST | niflags))
3296 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
3297
3298 return ntop_buf;
3299 }
3300
3301 #ifdef INET6
3302 /*
3303 * Return a name for the IP6 address pointed to by ap. This address
3304 * is assumed to be in network byte order.
3305 */
3306 char *
3307 getname6(ap)
3308 const u_char *ap;
3309 {
3310 struct sockaddr_in6 addr;
3311 static char ntop_buf[NI_MAXHOST];
3312
3313 memset(&addr, 0, sizeof(addr));
3314 addr.sin6_len = sizeof(struct sockaddr_in6);
3315 addr.sin6_family = AF_INET6;
3316 memcpy(&addr.sin6_addr, ap, sizeof(addr.sin6_addr));
3317 if (getnameinfo((struct sockaddr *)&addr, addr.sin6_len,
3318 ntop_buf, sizeof(ntop_buf), NULL, 0,
3319 NI_NUMERICHOST | niflags))
3320 strlcpy(ntop_buf, "?", sizeof(ntop_buf));
3321
3322 return ntop_buf;
3323 }
3324 #endif /* INET6 */
3325
3326 int
3327 safeputchar(c)
3328 int c;
3329 {
3330 unsigned char ch;
3331
3332 ch = (unsigned char)(c & 0xff);
3333 if (c < 0x80 && isprint(c))
3334 return printf("%c", c & 0xff);
3335 else
3336 return printf("\\%03o", c & 0xff);
3337 }
3338
3339 void
3340 isakmp_printpacket(msg, from, my, decoded)
3341 vchar_t *msg;
3342 struct sockaddr *from;
3343 struct sockaddr *my;
3344 int decoded;
3345 {
3346 #ifdef YIPS_DEBUG
3347 struct timeval tv;
3348 int s;
3349 char hostbuf[NI_MAXHOST];
3350 char portbuf[NI_MAXSERV];
3351 struct isakmp *isakmp;
3352 vchar_t *buf;
3353 #endif
3354
3355 if (loglevel < LLV_DEBUG)
3356 return;
3357
3358 #ifdef YIPS_DEBUG
3359 plog(LLV_DEBUG, LOCATION, NULL, "begin.\n");
3360
3361 gettimeofday(&tv, NULL);
3362 s = tv.tv_sec % 3600;
3363 printf("%02d:%02d.%06u ", s / 60, s % 60, (u_int32_t)tv.tv_usec);
3364
3365 if (from) {
3366 if (getnameinfo(from, sysdep_sa_len(from), 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 if (my) {
3377 if (getnameinfo(my, sysdep_sa_len(my), hostbuf, sizeof(hostbuf),
3378 portbuf, sizeof(portbuf),
3379 NI_NUMERICHOST | NI_NUMERICSERV | niflags)) {
3380 strlcpy(hostbuf, "?", sizeof(hostbuf));
3381 strlcpy(portbuf, "?", sizeof(portbuf));
3382 }
3383 printf("%s:%s", hostbuf, portbuf);
3384 } else
3385 printf("?");
3386 printf(": ");
3387
3388 buf = vdup(msg);
3389 if (!buf) {
3390 printf("(malloc fail)\n");
3391 return;
3392 }
3393 if (decoded) {
3394 isakmp = (struct isakmp *)buf->v;
3395 if (isakmp->flags & ISAKMP_FLAG_E) {
3396 #if 0
3397 int pad;
3398 pad = *(u_char *)(buf->v + buf->l - 1);
3399 if (buf->l < pad && 2 < vflag)
3400 printf("(wrong padding)");
3401 #endif
3402 isakmp->flags &= ~ISAKMP_FLAG_E;
3403 }
3404 }
3405
3406 snapend = buf->v + buf->l;
3407 isakmp_print(buf->v, buf->l, NULL);
3408 vfree(buf);
3409 printf("\n");
3410 fflush(stdout);
3411
3412 return;
3413 #endif
3414 }
3415 #endif /*HAVE_PRINT_ISAKMP_C*/
3416
3417 int
3418 copy_ph1addresses(iph1, rmconf, remote, local)
3419 struct ph1handle *iph1;
3420 struct remoteconf *rmconf;
3421 struct sockaddr *remote, *local;
3422 {
3423 u_short *port = NULL;
3424
3425 /* address portion must be grabbed from real remote address "remote" */
3426 iph1->remote = dupsaddr(remote);
3427 if (iph1->remote == NULL) {
3428 delph1(iph1);
3429 return -1;
3430 }
3431
3432 /*
3433 * if remote has no port # (in case of initiator - from ACQUIRE msg)
3434 * - if remote.conf specifies port #, use that
3435 * - if remote.conf does not, use 500
3436 * if remote has port # (in case of responder - from recvfrom(2))
3437 * respect content of "remote".
3438 */
3439 switch (iph1->remote->sa_family) {
3440 case AF_INET:
3441 port = &((struct sockaddr_in *)iph1->remote)->sin_port;
3442 if (*port)
3443 break;
3444 *port = ((struct sockaddr_in *)rmconf->remote)->sin_port;
3445 if (*port)
3446 break;
3447 *port = htons(PORT_ISAKMP);
3448 break;
3449 #ifdef INET6
3450 case AF_INET6:
3451 port = &((struct sockaddr_in6 *)iph1->remote)->sin6_port;
3452 if (*port)
3453 break;
3454 *port = ((struct sockaddr_in6 *)rmconf->remote)->sin6_port;
3455 if (*port)
3456 break;
3457 *port = htons(PORT_ISAKMP);
3458 break;
3459 #endif
3460 default:
3461 plog(LLV_ERROR, LOCATION, NULL,
3462 "invalid family: %d\n", iph1->remote->sa_family);
3463 delph1(iph1);
3464 return -1;
3465 }
3466
3467 if (local == NULL)
3468 iph1->local = getlocaladdr(iph1->remote);
3469 else
3470 iph1->local = dupsaddr(local);
3471 if (iph1->local == NULL) {
3472 delph1(iph1);
3473 return -1;
3474 }
3475 port = NULL;
3476 switch (iph1->local->sa_family) {
3477 case AF_INET:
3478 port = &((struct sockaddr_in *)iph1->local)->sin_port;
3479 if (*port)
3480 break;
3481 *port = ((struct sockaddr_in *)iph1->local)->sin_port;
3482 if (*port)
3483 break;
3484 *port = getmyaddrsport(iph1->local);
3485 break;
3486 #ifdef INET6
3487 case AF_INET6:
3488 port = &((struct sockaddr_in6 *)iph1->local)->sin6_port;
3489 if (*port)
3490 break;
3491 *port = ((struct sockaddr_in6 *)iph1->local)->sin6_port;
3492 if (*port)
3493 break;
3494 *port = getmyaddrsport(iph1->local);
3495 break;
3496 #endif
3497 default:
3498 plog(LLV_ERROR, LOCATION, NULL,
3499 "invalid family: %d\n", iph1->local->sa_family);
3500 delph1(iph1);
3501 return -1;
3502 }
3503 #ifdef ENABLE_NATT
3504 if ( port != NULL && *port == htons(lcconf->port_isakmp_natt) ) {
3505 plog (LLV_DEBUG, LOCATION, NULL, "Marking ports as changed\n");
3506 iph1->natt_flags |= NAT_ADD_NON_ESP_MARKER;
3507 }
3508 #endif
3509
3510 return 0;
3511 }
3512
3513 static int
3514 nostate1(iph1, msg)
3515 struct ph1handle *iph1;
3516 vchar_t *msg;
3517 {
3518 plog(LLV_ERROR, LOCATION, iph1->remote, "wrong state %u.\n",
3519 iph1->status);
3520 return -1;
3521 }
3522
3523 static int
3524 nostate2(iph2, msg)
3525 struct ph2handle *iph2;
3526 vchar_t *msg;
3527 {
3528 plog(LLV_ERROR, LOCATION, iph2->ph1->remote, "wrong state %u.\n",
3529 iph2->status);
3530 return -1;
3531 }
3532
3533 void
3534 log_ph1established(iph1)
3535 const struct ph1handle *iph1;
3536 {
3537 char *src, *dst;
3538
3539 src = racoon_strdup(saddr2str(iph1->local));
3540 dst = racoon_strdup(saddr2str(iph1->remote));
3541 STRDUP_FATAL(src);
3542 STRDUP_FATAL(dst);
3543
3544 plog(LLV_INFO, LOCATION, NULL,
3545 "ISAKMP-SA established %s-%s spi:%s\n",
3546 src, dst,
3547 isakmp_pindex(&iph1->index, 0));
3548 EVT_PUSH(iph1->local, iph1->remote, EVTT_PHASE1_UP, NULL);
3549 if(!iph1->rmconf->mode_cfg)
3550 EVT_PUSH(iph1->local, iph1->remote, EVTT_NO_ISAKMP_CFG, NULL);
3551
3552 racoon_free(src);
3553 racoon_free(dst);
3554
3555 return;
3556 }
3557
3558 struct payload_list *
3559 isakmp_plist_append (struct payload_list *plist, vchar_t *payload, int payload_type)
3560 {
3561 if (! plist) {
3562 plist = racoon_malloc (sizeof (struct payload_list));
3563 plist->prev = NULL;
3564 }
3565 else {
3566 plist->next = racoon_malloc (sizeof (struct payload_list));
3567 plist->next->prev = plist;
3568 plist = plist->next;
3569 }
3570
3571 plist->next = NULL;
3572 plist->payload = payload;
3573 plist->payload_type = payload_type;
3574
3575 return plist;
3576 }
3577
3578 vchar_t *
3579 isakmp_plist_set_all (struct payload_list **plist, struct ph1handle *iph1)
3580 {
3581 struct payload_list *ptr = *plist, *first;
3582 size_t tlen = sizeof (struct isakmp), n = 0;
3583 vchar_t *buf = NULL;
3584 char *p;
3585
3586 /* Seek to the first item. */
3587 while (ptr->prev) ptr = ptr->prev;
3588 first = ptr;
3589
3590 /* Compute the whole length. */
3591 while (ptr) {
3592 tlen += ptr->payload->l + sizeof (struct isakmp_gen);
3593 ptr = ptr->next;
3594 }
3595
3596 buf = vmalloc(tlen);
3597 if (buf == NULL) {
3598 plog(LLV_ERROR, LOCATION, NULL,
3599 "failed to get buffer to send.\n");
3600 goto end;
3601 }
3602
3603 ptr = first;
3604
3605 p = set_isakmp_header1(buf, iph1, ptr->payload_type);
3606 if (p == NULL)
3607 goto end;
3608
3609 while (ptr)
3610 {
3611 p = set_isakmp_payload (p, ptr->payload, ptr->next ? ptr->next->payload_type : ISAKMP_NPTYPE_NONE);
3612 first = ptr;
3613 ptr = ptr->next;
3614 racoon_free (first);
3615 /* ptr->prev = NULL; first = NULL; ... omitted. */
3616 n++;
3617 }
3618
3619 *plist = NULL;
3620
3621 return buf;
3622 end:
3623 if (buf != NULL)
3624 vfree(buf);
3625 return NULL;
3626 }
3627
3628 #ifdef ENABLE_FRAG
3629 int
3630 frag_handler(iph1, msg, remote, local)
3631 struct ph1handle *iph1;
3632 vchar_t *msg;
3633 struct sockaddr *remote;
3634 struct sockaddr *local;
3635 {
3636 vchar_t *newmsg;
3637
3638 if (isakmp_frag_extract(iph1, msg) == 1) {
3639 if ((newmsg = isakmp_frag_reassembly(iph1)) == NULL) {
3640 plog(LLV_ERROR, LOCATION, remote,
3641 "Packet reassembly failed\n");
3642 return -1;
3643 }
3644 return isakmp_main(newmsg, remote, local);
3645 }
3646
3647 return 0;
3648 }
3649 #endif
3650
3651 void
3652 script_hook(iph1, script)
3653 struct ph1handle *iph1;
3654 int script;
3655 {
3656 #define IP_MAX 40
3657 #define PORT_MAX 6
3658 char addrstr[IP_MAX];
3659 char portstr[PORT_MAX];
3660 char **envp = NULL;
3661 int envc = 1;
3662 struct sockaddr_in *sin;
3663 char **c;
3664
3665 if (iph1 == NULL ||
3666 iph1->rmconf == NULL ||
3667 iph1->rmconf->script[script] == NULL)
3668 return;
3669
3670 #ifdef ENABLE_HYBRID
3671 (void)isakmp_cfg_setenv(iph1, &envp, &envc);
3672 #endif
3673
3674 /* local address */
3675 sin = (struct sockaddr_in *)iph1->local;
3676 inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
3677 snprintf(portstr, sizeof(portstr), "%d", ntohs(sin->sin_port));
3678
3679 if (script_env_append(&envp, &envc, "LOCAL_ADDR", addrstr) != 0) {
3680 plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_ADDR\n");
3681 goto out;
3682 }
3683
3684 if (script_env_append(&envp, &envc, "LOCAL_PORT", portstr) != 0) {
3685 plog(LLV_ERROR, LOCATION, NULL, "Cannot set LOCAL_PORT\n");
3686 goto out;
3687 }
3688
3689 /* Peer address */
3690 if (iph1->remote != NULL) {
3691 sin = (struct sockaddr_in *)iph1->remote;
3692 inet_ntop(sin->sin_family, &sin->sin_addr, addrstr, IP_MAX);
3693 snprintf(portstr, sizeof(portstr), "%d", ntohs(sin->sin_port));
3694
3695 if (script_env_append(&envp, &envc,
3696 "REMOTE_ADDR", addrstr) != 0) {
3697 plog(LLV_ERROR, LOCATION, NULL,
3698 "Cannot set REMOTE_ADDR\n");
3699 goto out;
3700 }
3701
3702 if (script_env_append(&envp, &envc,
3703 "REMOTE_PORT", portstr) != 0) {
3704 plog(LLV_ERROR, LOCATION, NULL,
3705 "Cannot set REMOTEL_PORT\n");
3706 goto out;
3707 }
3708 }
3709
3710 if (privsep_script_exec(iph1->rmconf->script[script]->v,
3711 script, envp) != 0)
3712 plog(LLV_ERROR, LOCATION, NULL,
3713 "Script %s execution failed\n", script_names[script]);
3714
3715 out:
3716 for (c = envp; *c; c++)
3717 racoon_free(*c);
3718
3719 racoon_free(envp);
3720
3721 return;
3722 }
3723
3724 int
3725 script_env_append(envp, envc, name, value)
3726 char ***envp;
3727 int *envc;
3728 char *name;
3729 char *value;
3730 {
3731 char *envitem;
3732 char **newenvp;
3733 int newenvc;
3734 int envitem_len;
3735
3736 envitem_len = strlen(name) + 1 + strlen(value) + 1;
3737 envitem = racoon_malloc(envitem_len);
3738 if (envitem == NULL) {
3739 plog(LLV_ERROR, LOCATION, NULL,
3740 "Cannot allocate memory: %s\n", strerror(errno));
3741 return -1;
3742 }
3743 snprintf(envitem, envitem_len, "%s=%s", name, value);
3744
3745 newenvc = (*envc) + 1;
3746 newenvp = racoon_realloc(*envp, newenvc * sizeof(char *));
3747 if (newenvp == NULL) {
3748 plog(LLV_ERROR, LOCATION, NULL,
3749 "Cannot allocate memory: %s\n", strerror(errno));
3750 racoon_free(envitem);
3751 return -1;
3752 }
3753
3754 newenvp[newenvc - 2] = envitem;
3755 newenvp[newenvc - 1] = NULL;
3756
3757 *envp = newenvp;
3758 *envc = newenvc;
3759 return 0;
3760 }
3761
3762 int
3763 script_exec(script, name, envp)
3764 char *script;
3765 int name;
3766 char *const envp[];
3767 {
3768 char *argv[] = { NULL, NULL, NULL };
3769
3770 argv[0] = script;
3771 argv[1] = script_names[name];
3772 argv[2] = NULL;
3773
3774 switch (fork()) {
3775 case 0:
3776 execve(argv[0], argv, envp);
3777 plog(LLV_ERROR, LOCATION, NULL,
3778 "execve(\"%s\") failed: %s\n",
3779 argv[0], strerror(errno));
3780 _exit(1);
3781 break;
3782 case -1:
3783 plog(LLV_ERROR, LOCATION, NULL,
3784 "Cannot fork: %s\n", strerror(errno));
3785 return -1;
3786 break;
3787 default:
3788 break;
3789 }
3790
3791 return 0;
3792 }
3793
3794 void
3795 purge_remote(iph1)
3796 struct ph1handle *iph1;
3797 {
3798 vchar_t *buf = NULL;
3799 struct sadb_msg *msg, *next, *end;
3800 struct sadb_sa *sa;
3801 struct sockaddr *src, *dst;
3802 caddr_t mhp[SADB_EXT_MAX + 1];
3803 u_int proto_id;
3804 struct ph2handle *iph2;
3805 struct ph1handle *new_iph1;
3806
3807 plog(LLV_INFO, LOCATION, NULL,
3808 "purging ISAKMP-SA spi=%s.\n",
3809 isakmp_pindex(&(iph1->index), iph1->msgid));
3810
3811 /* Mark as expired. */
3812 iph1->status = PHASE1ST_EXPIRED;
3813
3814 new_iph1 = ike_session_update_ph1_ph2tree(iph1);
3815
3816 /*
3817 * Delete all orphaned or binded to the deleting ph1handle phase2 SAs.
3818 * Keep all others phase2 SAs.
3819 */
3820 buf = pfkey_dump_sadb(SADB_SATYPE_UNSPEC);
3821 if (buf == NULL) {
3822 plog(LLV_DEBUG, LOCATION, NULL,
3823 "pfkey_dump_sadb returned nothing.\n");
3824 return;
3825 }
3826
3827 msg = (struct sadb_msg *)buf->v;
3828 end = (struct sadb_msg *)(buf->v + buf->l);
3829
3830 while (msg < end) {
3831 if ((msg->sadb_msg_len << 3) < sizeof(*msg))
3832 break;
3833 next = (struct sadb_msg *)((caddr_t)msg + (msg->sadb_msg_len << 3));
3834 if (msg->sadb_msg_type != SADB_DUMP) {
3835 msg = next;
3836 continue;
3837 }
3838
3839 if (pfkey_align(msg, mhp) || pfkey_check(mhp)) {
3840 plog(LLV_ERROR, LOCATION, NULL,
3841 "pfkey_check (%s)\n", ipsec_strerror());
3842 msg = next;
3843 continue;
3844 }
3845
3846 sa = (struct sadb_sa *)(mhp[SADB_EXT_SA]);
3847 if (!sa ||
3848 !mhp[SADB_EXT_ADDRESS_SRC] ||
3849 !mhp[SADB_EXT_ADDRESS_DST]) {
3850 msg = next;
3851 continue;
3852 }
3853 src = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_SRC]);
3854 dst = PFKEY_ADDR_SADDR(mhp[SADB_EXT_ADDRESS_DST]);
3855
3856 if (sa->sadb_sa_state != SADB_SASTATE_LARVAL &&
3857 sa->sadb_sa_state != SADB_SASTATE_MATURE &&
3858 sa->sadb_sa_state != SADB_SASTATE_DYING) {
3859 msg = next;
3860 continue;
3861 }
3862
3863 /*
3864 * check in/outbound SAs.
3865 * Select only SAs where src == local and dst == remote (outgoing)
3866 * or src == remote and dst == local (incoming).
3867 */
3868 if ((CMPSADDR(iph1->local, src) || CMPSADDR(iph1->remote, dst)) &&
3869 (CMPSADDR(iph1->local, dst) || CMPSADDR(iph1->remote, src))) {
3870 msg = next;
3871 continue;
3872 }
3873
3874 proto_id = pfkey2ipsecdoi_proto(msg->sadb_msg_satype);
3875 iph2 = getph2bysaidx(src, dst, proto_id, sa->sadb_sa_spi);
3876
3877 /* Check if there is another valid ISAKMP-SA */
3878 if (new_iph1 != NULL) {
3879
3880 if (iph2 == NULL) {
3881 /* No handler... still send a pfkey_delete message, but log this !*/
3882 plog(LLV_INFO, LOCATION, NULL,
3883 "Unknown IPsec-SA spi=%u, hmmmm?\n",
3884 ntohl(sa->sadb_sa_spi));
3885 }else{
3886
3887 /*
3888 * If we have a new ph1, do not purge IPsec-SAs binded
3889 * to a different ISAKMP-SA
3890 */
3891 if (iph2->ph1 != NULL && iph2->ph1 != iph1){
3892 msg = next;
3893 continue;
3894 }
3895
3896 /* If the ph2handle is established, do not purge IPsec-SA */
3897 if (iph2->status == PHASE2ST_ESTABLISHED ||
3898 iph2->status == PHASE2ST_EXPIRED) {
3899
3900 plog(LLV_INFO, LOCATION, NULL,
3901 "keeping IPsec-SA spi=%u - found valid ISAKMP-SA spi=%s.\n",
3902 ntohl(sa->sadb_sa_spi),
3903 isakmp_pindex(&(new_iph1->index), new_iph1->msgid));
3904 msg = next;
3905 continue;
3906 }
3907 }
3908 }
3909
3910
3911 pfkey_send_delete(lcconf->sock_pfkey,
3912 msg->sadb_msg_satype,
3913 IPSEC_MODE_ANY,
3914 src, dst, sa->sadb_sa_spi);
3915
3916 /* delete a relative phase 2 handle. */
3917 if (iph2 != NULL) {
3918 delete_spd(iph2);
3919 unbindph12(iph2);
3920 remph2(iph2);
3921 delph2(iph2);
3922 }
3923
3924 plog(LLV_INFO, LOCATION, NULL,
3925 "purged IPsec-SA spi=%u.\n",
3926 ntohl(sa->sadb_sa_spi));
3927
3928 msg = next;
3929 }
3930
3931 if (buf)
3932 vfree(buf);
3933
3934 /* Mark the phase1 handler as EXPIRED */
3935 plog(LLV_INFO, LOCATION, NULL,
3936 "purged ISAKMP-SA spi=%s.\n",
3937 isakmp_pindex(&(iph1->index), iph1->msgid));
3938
3939 SCHED_KILL(iph1->sce);
3940
3941 iph1->sce = sched_new(1, isakmp_ph1delete_stub, iph1);
3942 }
3943
3944 void
3945 delete_spd(iph2)
3946 struct ph2handle *iph2;
3947 {
3948 if (iph2 == NULL)
3949 return;
3950
3951 /* Delete the SPD entry if we generated it
3952 */
3953 if (iph2->generated_spidx) {
3954 struct policyindex spidx;
3955 struct sockaddr_storage addr;
3956 u_int8_t pref;
3957 struct sockaddr *src = iph2->src;
3958 struct sockaddr *dst = iph2->dst;
3959 int error;
3960 int idi2type = 0;/* switch whether copy IDs into id[src,dst]. */
3961
3962 plog(LLV_INFO, LOCATION, NULL,
3963 "generated policy, deleting it.\n");
3964
3965 memset(&spidx, 0, sizeof(spidx));
3966 iph2->spidx_gen = (caddr_t )&spidx;
3967
3968 /* make inbound policy */
3969 iph2->src = dst;
3970 iph2->dst = src;
3971 spidx.dir = IPSEC_DIR_INBOUND;
3972 spidx.ul_proto = 0;
3973
3974 /*
3975 * Note: code from get_proposal_r
3976 */
3977
3978 #define _XIDT(d) ((struct ipsecdoi_id_b *)(d)->v)->type
3979
3980 /*
3981 * make destination address in spidx from either ID payload
3982 * or phase 1 address into a address in spidx.
3983 */
3984 if (iph2->id != NULL
3985 && (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
3986 || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR
3987 || _XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR_SUBNET
3988 || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
3989 /* get a destination address of a policy */
3990 error = ipsecdoi_id2sockaddr(iph2->id,
3991 (struct sockaddr *)&spidx.dst,
3992 &spidx.prefd, &spidx.ul_proto);
3993 if (error)
3994 goto purge;
3995
3996 #ifdef INET6
3997 /*
3998 * get scopeid from the SA address.
3999 * note that the phase 1 source address is used as
4000 * a destination address to search for a inbound
4001 * policy entry because rcoon is responder.
4002 */
4003 if (_XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR) {
4004 if ((error =
4005 setscopeid((struct sockaddr *)&spidx.dst,
4006 iph2->src)) != 0)
4007 goto purge;
4008 }
4009 #endif
4010
4011 if (_XIDT(iph2->id) == IPSECDOI_ID_IPV4_ADDR
4012 || _XIDT(iph2->id) == IPSECDOI_ID_IPV6_ADDR)
4013 idi2type = _XIDT(iph2->id);
4014
4015 } else {
4016
4017 plog(LLV_DEBUG, LOCATION, NULL,
4018 "get a destination address of SP index "
4019 "from phase1 address "
4020 "due to no ID payloads found "
4021 "OR because ID type is not address.\n");
4022
4023 /*
4024 * copy the SOURCE address of IKE into the
4025 * DESTINATION address of the key to search the
4026 * SPD because the direction of policy is inbound.
4027 */
4028 memcpy(&spidx.dst, iph2->src, sysdep_sa_len(iph2->src));
4029 switch (spidx.dst.ss_family) {
4030 case AF_INET:
4031 spidx.prefd =
4032 sizeof(struct in_addr) << 3;
4033 break;
4034 #ifdef INET6
4035 case AF_INET6:
4036 spidx.prefd =
4037 sizeof(struct in6_addr) << 3;
4038 break;
4039 #endif
4040 default:
4041 spidx.prefd = 0;
4042 break;
4043 }
4044 }
4045
4046 /* make source address in spidx */
4047 if (iph2->id_p != NULL
4048 && (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR
4049 || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR
4050 || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV4_ADDR_SUBNET
4051 || _XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR_SUBNET)) {
4052 /* get a source address of inbound SA */
4053 error = ipsecdoi_id2sockaddr(iph2->id_p,
4054 (struct sockaddr *)&spidx.src,
4055 &spidx.prefs, &spidx.ul_proto);
4056 if (error)
4057 goto purge;
4058
4059 #ifdef INET6
4060 /*
4061 * get scopeid from the SA address.
4062 * for more detail, see above of this function.
4063 */
4064 if (_XIDT(iph2->id_p) == IPSECDOI_ID_IPV6_ADDR) {
4065 error =
4066 setscopeid((struct sockaddr *)&spidx.src,
4067 iph2->dst);
4068 if (error)
4069 goto purge;
4070 }
4071 #endif
4072
4073 /* make id[src,dst] if both ID types are IP address and same */
4074 if (_XIDT(iph2->id_p) == idi2type
4075 && spidx.dst.ss_family == spidx.src.ss_family) {
4076 iph2->src_id =
4077 dupsaddr((struct sockaddr *)&spidx.dst);
4078 iph2->dst_id =
4079 dupsaddr((struct sockaddr *)&spidx.src);
4080 }
4081
4082 } else {
4083 plog(LLV_DEBUG, LOCATION, NULL,
4084 "get a source address of SP index "
4085 "from phase1 address "
4086 "due to no ID payloads found "
4087 "OR because ID type is not address.\n");
4088
4089 /* see above comment. */
4090 memcpy(&spidx.src, iph2->dst, sysdep_sa_len(iph2->dst));
4091 switch (spidx.src.ss_family) {
4092 case AF_INET:
4093 spidx.prefs =
4094 sizeof(struct in_addr) << 3;
4095 break;
4096 #ifdef INET6
4097 case AF_INET6:
4098 spidx.prefs =
4099 sizeof(struct in6_addr) << 3;
4100 break;
4101 #endif
4102 default:
4103 spidx.prefs = 0;
4104 break;
4105 }
4106 }
4107
4108 #undef _XIDT
4109
4110 plog(LLV_DEBUG, LOCATION, NULL,
4111 "get a src address from ID payload "
4112 "%s prefixlen=%u ul_proto=%u\n",
4113 saddr2str((struct sockaddr *)&spidx.src),
4114 spidx.prefs, spidx.ul_proto);
4115 plog(LLV_DEBUG, LOCATION, NULL,
4116 "get dst address from ID payload "
4117 "%s prefixlen=%u ul_proto=%u\n",
4118 saddr2str((struct sockaddr *)&spidx.dst),
4119 spidx.prefd, spidx.ul_proto);
4120
4121 /*
4122 * convert the ul_proto if it is 0
4123 * because 0 in ID payload means a wild card.
4124 */
4125 if (spidx.ul_proto == 0)
4126 spidx.ul_proto = IPSEC_ULPROTO_ANY;
4127
4128 #undef _XIDT
4129
4130 /* End of code from get_proposal_r
4131 */
4132
4133 if (pk_sendspddelete(iph2) < 0) {
4134 plog(LLV_ERROR, LOCATION, NULL,
4135 "pfkey spddelete(inbound) failed.\n");
4136 }else{
4137 plog(LLV_DEBUG, LOCATION, NULL,
4138 "pfkey spddelete(inbound) sent.\n");
4139 }
4140
4141 #ifdef HAVE_POLICY_FWD
4142 /* make forward policy if required */
4143 if (tunnel_mode_prop(iph2->approval)) {
4144 spidx.dir = IPSEC_DIR_FWD;
4145 if (pk_sendspddelete(iph2) < 0) {
4146 plog(LLV_ERROR, LOCATION, NULL,
4147 "pfkey spddelete(forward) failed.\n");
4148 }else{
4149 plog(LLV_DEBUG, LOCATION, NULL,
4150 "pfkey spddelete(forward) sent.\n");
4151 }
4152 }
4153 #endif
4154
4155 /* make outbound policy */
4156 iph2->src = src;
4157 iph2->dst = dst;
4158 spidx.dir = IPSEC_DIR_OUTBOUND;
4159 addr = spidx.src;
4160 spidx.src = spidx.dst;
4161 spidx.dst = addr;
4162 pref = spidx.prefs;
4163 spidx.prefs = spidx.prefd;
4164 spidx.prefd = pref;
4165
4166 if (pk_sendspddelete(iph2) < 0) {
4167 plog(LLV_ERROR, LOCATION, NULL,
4168 "pfkey spddelete(outbound) failed.\n");
4169 }else{
4170 plog(LLV_DEBUG, LOCATION, NULL,
4171 "pfkey spddelete(outbound) sent.\n");
4172 }
4173 purge:
4174 iph2->spidx_gen=NULL;
4175 }
4176 }
4177
4178 #ifdef INET6
4179 u_int32_t
4180 setscopeid(sp_addr0, sa_addr0)
4181 struct sockaddr *sp_addr0, *sa_addr0;
4182 {
4183 struct sockaddr_in6 *sp_addr, *sa_addr;
4184
4185 sp_addr = (struct sockaddr_in6 *)sp_addr0;
4186 sa_addr = (struct sockaddr_in6 *)sa_addr0;
4187
4188 if (!IN6_IS_ADDR_LINKLOCAL(&sp_addr->sin6_addr)
4189 && !IN6_IS_ADDR_SITELOCAL(&sp_addr->sin6_addr)
4190 && !IN6_IS_ADDR_MULTICAST(&sp_addr->sin6_addr))
4191 return 0;
4192
4193 /* this check should not be here ? */
4194 if (sa_addr->sin6_family != AF_INET6) {
4195 plog(LLV_ERROR, LOCATION, NULL,
4196 "can't get scope ID: family mismatch\n");
4197 return -1;
4198 }
4199
4200 if (!IN6_IS_ADDR_LINKLOCAL(&sa_addr->sin6_addr)) {
4201 plog(LLV_ERROR, LOCATION, NULL,
4202 "scope ID is not supported except of lladdr.\n");
4203 return -1;
4204 }
4205
4206 sp_addr->sin6_scope_id = sa_addr->sin6_scope_id;
4207
4208 return 0;
4209 }
4210 #endif