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