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