1 /* $NetBSD: session.c,v 1.7.6.2 2007/08/01 11:52:22 vanhu Exp $ */
3 /* $KAME: session.c,v 1.32 2003/09/24 02:01:17 jinmei Exp $ */
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
36 #include <sys/types.h>
37 #include <sys/param.h>
39 #include <sys/socket.h>
41 # include <sys/wait.h>
44 # define WEXITSTATUS(s) ((unsigned)(s) >> 8)
47 # define WIFEXITED(s) (((s) & 255) == 0)
50 #ifndef HAVE_NETINET6_IPSEC
51 #include <netinet/ipsec.h>
53 #include <netinet6/ipsec.h>
67 #include <netinet/in.h>
68 #include <netinet/ip.h>
69 #include <netinet/ip_icmp.h>
72 #include <TargetConditionals.h>
73 #include <vproc_priv.h>
74 #include <dispatch/dispatch.h>
88 #include "grabmyaddr.h"
89 #include "cfparse_proto.h"
90 #include "isakmp_var.h"
91 #include "isakmp_xauth.h"
92 #include "isakmp_cfg.h"
96 #include "localconf.h"
97 #include "remoteconf.h"
99 #include "nattraversal.h"
101 #include "vpn_control_var.h"
103 #include "algorithm.h" /* XXX ??? */
106 #include "power_mgmt.h"
108 #include <NetworkExtension/NEPolicy.h>
109 #include <sys/proc_info.h>
113 extern pid_t racoon_pid
;
114 extern int launchdlaunched
;
115 static void close_session (int);
116 static int init_signal (void);
117 static int set_signal (int sig
, RETSIGTYPE (*func
) (int, siginfo_t
*, void *));
118 static void check_sigreq (void);
119 static void check_flushsa_stub (void *);
120 static void check_flushsa (void);
121 static void auto_exit_do (void *);
122 static int close_sockets (void);
124 static volatile sig_atomic_t sigreq
[NSIG
+ 1];
127 static int64_t racoon_keepalive
= -1;
129 dispatch_queue_t main_queue
;
131 static NEPolicySessionRef policySession
= NULL
;
134 * This is used to (manually) update racoon's launchd keepalive, which is needed because racoon is (mostly)
135 * launched on demand and for <rdar://problem/8768510> requires a keepalive on dirty/failure exits.
136 * The launchd plist can't be used for this because RunOnLoad is required to have keepalive on a failure exit.
139 launchd_update_racoon_keepalive (Boolean enabled
)
141 if (launchdlaunched
) {
142 int64_t val
= (__typeof__(val
))enabled
;
143 /* Set our own KEEPALIVE value */
144 if (vproc_swap_integer(NULL
,
145 VPROC_GSK_BASIC_KEEPALIVE
,
147 &racoon_keepalive
)) {
149 "failed to swap launchd keepalive integer %d\n", enabled
);
152 return racoon_keepalive
;
156 copy_racoon_proc_uuid(void)
158 struct proc_uniqidentifierinfo procu
;
159 CFUUIDBytes uuidBytes
;
162 memset(&procu
, 0, sizeof(procu
));
163 size
= proc_pidinfo(getpid(), PROC_PIDUNIQIDENTIFIERINFO
, 1, &procu
, PROC_PIDUNIQIDENTIFIERINFO_SIZE
);
164 if (size
!= PROC_PIDUNIQIDENTIFIERINFO_SIZE
) {
168 memcpy(&uuidBytes
, procu
.p_uuid
, sizeof(CFUUIDBytes
));
169 return CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault
, uuidBytes
);
173 policy_session_init(void)
176 policySession
= NEPolicyCreateSession(kCFAllocatorDefault
, CFSTR("racoon"), NULL
, NULL
);
177 if (policySession
== NULL
) {
181 CFUUIDRef proc_uuid
= copy_racoon_proc_uuid();
182 if (proc_uuid
== NULL
) {
186 CFMutableArrayRef conditions
= CFArrayCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeArrayCallBacks
);
188 CFMutableDictionaryRef uuidCondition
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
190 CFDictionarySetValue(uuidCondition
, kNEPolicyConditionType
, kNEPolicyValPolicyConditionTypeApplication
);
191 CFDictionarySetValue(uuidCondition
, kNEPolicyApplicationUUID
, proc_uuid
);
192 CFArrayAppendValue(conditions
, uuidCondition
);
193 CFRelease(uuidCondition
);
198 CFMutableDictionaryRef interfacesCondition
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
199 if (interfacesCondition
) {
200 CFDictionarySetValue(interfacesCondition
, kNEPolicyConditionType
, kNEPolicyValPolicyConditionTypeAllInterfaces
);
201 CFArrayAppendValue(conditions
, interfacesCondition
);
202 CFRelease(interfacesCondition
);
210 CFMutableDictionaryRef result
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0, &kCFTypeDictionaryKeyCallBacks
, &kCFTypeDictionaryValueCallBacks
);
212 CFDictionaryAddValue(result
, kNEPolicyResult
, kNEPolicyValPolicyResultPass
);
218 success
= (NEPolicyAdd(policySession
, 0, conditions
, result
, NULL
) != kNEPolicyIDInvalid
);
225 CFRelease(conditions
);
228 CFRelease(proc_uuid
);
231 return (success
&& NEPolicyApply(policySession
));
237 // Initialize listening sockets, timers, vpn control etc.,
238 // write the PID file and call dispatch_main.
243 char pid_file
[MAXPATHLEN
];
247 main_queue
= dispatch_get_main_queue();
249 /* initialize schedular */
252 /* needs to be called after schedular */
253 if (init_power_mgmt() < 0) {
255 "failed to initialize power-mgmt.");
259 if (lcconf
->autograbaddr
== 1)
260 if (pfroute_init()) {
261 plog(ASL_LEVEL_ERR
, "failed to initialize route socket.\n");
265 if (!policy_session_init()) {
266 plog(ASL_LEVEL_ERR
, "failed to initialize NEPolicy session.\n");
270 plog(ASL_LEVEL_ERR
, "failed to initialize listening addresses.\n");
274 plog(ASL_LEVEL_ERR
, "failed to initialize isakmp");
277 #ifdef ENABLE_VPNCONTROL_PORT
278 if (vpncontrol_init()) {
279 plog(ASL_LEVEL_ERR
, "failed to initialize vpn control port");
285 plog(ASL_LEVEL_ERR
, "failed to initialize signals.\n");
289 for (i
= 0; i
<= NSIG
; i
++)
292 /* write .pid file */
294 racoon_pid
= getpid();
295 if (lcconf
->pathinfo
[LC_PATHTYPE_PIDFILE
] == NULL
)
296 strlcpy(pid_file
, _PATH_VARRUN
"racoon.pid", sizeof(pid_file
));
297 else if (lcconf
->pathinfo
[LC_PATHTYPE_PIDFILE
][0] == '/')
298 strlcpy(pid_file
, lcconf
->pathinfo
[LC_PATHTYPE_PIDFILE
], sizeof(pid_file
));
300 strlcat(pid_file
, _PATH_VARRUN
, sizeof(pid_file
));
301 strlcat(pid_file
, lcconf
->pathinfo
[LC_PATHTYPE_PIDFILE
], sizeof(pid_file
));
303 fp
= fopen(pid_file
, "w");
305 if (fchmod(fileno(fp
),
306 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
) == -1) {
307 plog(ASL_LEVEL_ERR
, "%s", strerror(errno
));
311 fprintf(fp
, "%ld\n", (long)racoon_pid
);
315 "cannot open %s", pid_file
);
319 xpc_transaction_begin();
321 #if !TARGET_OS_EMBEDDED
322 // enable keepalive for recovery (from crashes and bad exits... after init)
323 (void)launchd_update_racoon_keepalive(true);
324 #endif // !TARGET_OS_EMBEDDED
331 exit(1); // should not be reached!!!
335 /* clear all status and exit program. */
337 close_session(int error
)
340 cleanup_power_mgmt();
342 ike_session_flush_all_phase2(false);
343 ike_session_flush_all_phase1(false);
346 xpc_transaction_end();
348 #if !TARGET_OS_EMBEDDED
349 // a clean exit, so disable launchd keepalive
350 (void)launchd_update_racoon_keepalive(false);
351 #endif // !TARGET_OS_EMBEDDED
353 plog(ASL_LEVEL_INFO
, "racoon shutdown\n");
359 * waiting the termination of processing until sending DELETE message
360 * for all inbound SA will complete.
363 check_flushsa_stub(p
)
373 struct sadb_msg
*msg
, *end
, *next
;
375 caddr_t mhp
[SADB_EXT_MAX
+ 1];
378 buf
= pfkey_dump_sadb(SADB_SATYPE_UNSPEC
);
380 plog(ASL_LEVEL_DEBUG
,
381 "pfkey_dump_sadb: returned nothing.\n");
385 msg
= ALIGNED_CAST(struct sadb_msg
*)buf
->v
;
386 end
= ALIGNED_CAST(struct sadb_msg
*)(buf
->v
+ buf
->l
);
388 /* counting SA except of dead one. */
391 if (PFKEY_UNUNIT64(msg
->sadb_msg_len
) < sizeof(*msg
))
393 next
= ALIGNED_CAST(struct sadb_msg
*)((caddr_t
)msg
+ PFKEY_UNUNIT64(msg
->sadb_msg_len
)); // Wcast-align fix (void*) - aligned buffer + multiple of 64
394 if (msg
->sadb_msg_type
!= SADB_DUMP
) {
399 if (pfkey_align(msg
, mhp
) || pfkey_check(mhp
)) {
401 "pfkey_check (%s)\n", ipsec_strerror());
406 sa
= ALIGNED_CAST(struct sadb_sa
*)(mhp
[SADB_EXT_SA
]); // Wcast-align fix (void*) - mhp contains pointers to aligned structs
412 if (sa
->sadb_sa_state
!= SADB_SASTATE_DEAD
) {
425 sched_new(1, check_flushsa_stub
, NULL
);
429 #if !TARGET_OS_EMBEDDED
431 vproc_transaction_end(NULL
, lcconf
->vt
);
437 auto_exit_do(void *p
)
439 plog(ASL_LEVEL_DEBUG
,
440 "performing auto exit\n");
441 #if ENABLE_NO_SA_FLUSH
444 pfkey_send_flush(lcconf
->sock_pfkey
, SADB_SATYPE_UNSPEC
);
445 sched_new(1, check_flushsa_stub
, NULL
);
447 #endif /* ENABLE_NO_SA_FLUSH */
451 check_auto_exit(void)
453 if (lcconf
->auto_exit_sched
) { /* exit scheduled? */
454 if (lcconf
->auto_exit_state
!= LC_AUTOEXITSTATE_ENABLED
455 || vpn_control_connected() /* vpn control connected */
456 || policies_installed() /* policies installed in kernel */
457 || !no_remote_configs(FALSE
)) { /* remote or anonymous configs */
458 SCHED_KILL(lcconf
->auto_exit_sched
);
460 } else { /* exit not scheduled */
461 if (lcconf
->auto_exit_state
== LC_AUTOEXITSTATE_ENABLED
462 && !vpn_control_connected()
463 && !policies_installed()
464 && no_remote_configs(FALSE
)) {
465 if (lcconf
->auto_exit_delay
== 0) {
466 auto_exit_do(NULL
); /* immediate exit */
468 lcconf
->auto_exit_sched
= sched_new(lcconf
->auto_exit_delay
, auto_exit_do
, NULL
);
474 static int signals
[] = {
491 * XXX We are not able to tell if we got
492 * several time the same signal. This is
493 * not a problem for the current code,
494 * but we shall remember this limitation.
496 for (sig
= 0; sig
<= NSIG
; sig
++) {
497 if (sigreq
[sig
] == 0)
505 /* Catch up childs, mainly scripts.
511 if ((isakmp_cfg_init(ISAKMP_CFG_INIT_WARM
)) != 0) {
513 "ISAKMP mode config structure reset failed, "
522 * if we got a HUP... try graceful teardown of sessions before we close and reopen sockets...
523 * so that info-deletes notifications can make it to the peer.
526 ike_session_flush_all_phase2(true);
527 ike_session_flush_all_phase1(true);
530 /* Save old configuration, load new one... */
531 if (cfreparse(sig
)) {
533 "configuration read failed\n");
536 if (lcconf
->logfile_param
== NULL
&& logFileStr
[0] == 0)
537 plogresetfile(lcconf
->pathinfo
[LC_PATHTYPE_LOGFILE
]);
539 #if TARGET_OS_EMBEDDED
540 if (no_remote_configs(TRUE
)) {
541 #if ENABLE_NO_SA_FLUSH
544 pfkey_send_flush(lcconf
->sock_pfkey
, SADB_SATYPE_UNSPEC
);
545 #ifdef ENABLE_FASTQUIT
548 sched_new(1, check_flushsa_stub
, NULL
);
549 #endif /* ENABLE_FASTQUIT */
551 #endif /* ENABLE_NO_SA_FLUSH */
560 "caught signal %d\n", sig
);
561 #if ENABLE_NO_SA_FLUSH
564 pfkey_send_flush(lcconf
->sock_pfkey
,
566 if ( sig
== SIGTERM
){
567 terminated
= 1; /* in case if it hasn't been set yet */
571 sched_new(1, check_flushsa_stub
, NULL
);
574 #endif /* ENABLE_NO_SA_FLUSH */
579 "caught signal %d\n", sig
);
587 * asynchronous requests will actually dispatched in the
588 * main loop in session().
591 signal_handler(int sig
, siginfo_t
*sigi
, void *ctx
)
594 plog(ASL_LEVEL_DEBUG
,
595 "%s received signal %d from pid %d uid %d\n\n",
596 __FUNCTION__
, sig
, sigi
->si_pid
, sigi
->si_uid
);
599 /* Do not just set it to 1, because we may miss some signals by just setting
603 if ( sig
== SIGTERM
){
606 dispatch_async(main_queue
,
618 for (i
= 0; signals
[i
] != 0; i
++) {
619 if (set_signal(signals
[i
], signal_handler
) < 0) {
621 "failed to set_signal (%s)\n",
630 set_signal(int sig
, RETSIGTYPE (*func
) (int, siginfo_t
*, void *))
634 memset((caddr_t
)&sa
, 0, sizeof(sa
));
635 sa
.sa_sigaction
= func
;
636 sa
.sa_flags
= SA_RESTART
| SA_SIGINFO
;
638 if (sigemptyset(&sa
.sa_mask
) < 0)
641 if (sigaction(sig
, &sa
, (struct sigaction
*)0) < 0)
648 fatal_error(int error
)
650 close_session(error
== 0 ? -1 : error
);
653 /* suspend all socket sources except pf_key */
657 if (lcconf
->rt_source
)
658 dispatch_suspend(lcconf
->rt_source
);
659 if (lcconf
->vpncontrol_source
)
660 dispatch_suspend(lcconf
->vpncontrol_source
);
661 isakmp_suspend_sockets();
670 #ifdef ENABLE_VPNCONTROL_PORT