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