]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/charon-tkm/src/charon-tkm.c
charon-tkm: Unlink PID file after deinit
[thirdparty/strongswan.git] / src / charon-tkm / src / charon-tkm.c
1 /*
2 * Copyright (C) 2012-2017 Tobias Brunner
3 * Copyright (C) 2012 Reto Buerki
4 * Copyright (C) 2012 Adrian-Ken Rueegsegger
5 * HSR Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 #define _GNU_SOURCE
19
20 #include <stdio.h>
21 #include <syslog.h>
22 #include <signal.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 #include <libgen.h>
27 #include <fcntl.h>
28 #include <errno.h>
29
30 #include <daemon.h>
31 #include <library.h>
32 #include <utils/backtrace.h>
33 #include <threading/thread.h>
34 #include <sa/keymat.h>
35 #include <credentials/credential_manager.h>
36
37 #include "tkm.h"
38 #include "tkm_nonceg.h"
39 #include "tkm_diffie_hellman.h"
40 #include "tkm_keymat.h"
41 #include "tkm_listener.h"
42 #include "tkm_kernel_ipsec.h"
43 #include "tkm_public_key.h"
44 #include "tkm_cred.h"
45 #include "tkm_encoder.h"
46 #include "tkm_spi_generator.h"
47
48 /**
49 * TKM bus listener for IKE authorize events.
50 */
51 static tkm_listener_t *listener;
52
53 /**
54 * Name of the daemon
55 */
56 static char *dmn_name;
57
58 /**
59 * PID file, in which charon-tkm stores its process id
60 */
61 static char *pidfile_name = NULL;
62
63 /**
64 * Global reference to PID file (required to truncate, if undeletable)
65 */
66 static FILE *pidfile = NULL;
67
68 /**
69 * Hook in library for debugging messages
70 */
71 extern void (*dbg) (debug_t group, level_t level, char *fmt, ...);
72
73 /**
74 * Simple logging hook for library logs, using syslog output
75 */
76 static void dbg_syslog(debug_t group, level_t level, char *fmt, ...)
77 {
78 if (level <= 1)
79 {
80 char buffer[8192];
81 va_list args;
82
83 va_start(args, fmt);
84 /* write in memory buffer first */
85 vsnprintf(buffer, sizeof(buffer), fmt, args);
86 syslog(LOG_DAEMON|LOG_INFO, "00[%s] %s", debug_names->names[group],
87 buffer);
88 va_end(args);
89 }
90 }
91
92 /**
93 * Run the daemon and handle unix signals
94 */
95 static void run()
96 {
97 sigset_t set;
98
99 /* handle SIGINT and SIGTERM in this handler */
100 sigemptyset(&set);
101 sigaddset(&set, SIGINT);
102 sigaddset(&set, SIGTERM);
103 sigprocmask(SIG_BLOCK, &set, NULL);
104
105 while (TRUE)
106 {
107 int sig;
108
109 sig = sigwaitinfo(&set, NULL);
110 if (sig == -1)
111 {
112 if (errno == EINTR)
113 { /* ignore signals we didn't wait for */
114 continue;
115 }
116 DBG1(DBG_DMN, "waiting for signal failed: %s", strerror(errno));
117 return;
118 }
119 switch (sig)
120 {
121 case SIGINT:
122 {
123 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
124 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
125 return;
126 }
127 case SIGTERM:
128 {
129 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
130 charon->bus->alert(charon->bus, ALERT_SHUTDOWN_SIGNAL, sig);
131 return;
132 }
133 }
134 }
135 }
136
137 /**
138 * Handle SIGSEGV/SIGILL signals raised by threads
139 */
140 static void segv_handler(int signal)
141 {
142 backtrace_t *backtrace;
143
144 DBG1(DBG_DMN, "thread %u received %d", thread_current_id(), signal);
145 backtrace = backtrace_create(2);
146 backtrace->log(backtrace, stderr, TRUE);
147 backtrace->destroy(backtrace);
148
149 DBG1(DBG_DMN, "killing ourself, received critical signal");
150 abort();
151 }
152
153 /**
154 * Lookup UID and GID
155 */
156 static bool lookup_uid_gid()
157 {
158 #ifdef IPSEC_USER
159 if (!lib->caps->resolve_uid(lib->caps, IPSEC_USER))
160 {
161 return FALSE;
162 }
163 #endif
164 #ifdef IPSEC_GROUP
165 if (!lib->caps->resolve_gid(lib->caps, IPSEC_GROUP))
166 {
167 return FALSE;
168 }
169 #endif
170 return TRUE;
171 }
172
173 /**
174 * Check/create PID file, return TRUE if already running
175 */
176 static bool check_pidfile()
177 {
178 struct stat stb;
179
180 if (stat(pidfile_name, &stb) == 0)
181 {
182 pidfile = fopen(pidfile_name, "r");
183 if (pidfile)
184 {
185 char buf[64];
186 pid_t pid = 0;
187
188 memset(buf, 0, sizeof(buf));
189 if (fread(buf, 1, sizeof(buf), pidfile))
190 {
191 buf[sizeof(buf) - 1] = '\0';
192 pid = atoi(buf);
193 }
194 fclose(pidfile);
195 pidfile = NULL;
196 if (pid && kill(pid, 0) == 0)
197 {
198 DBG1(DBG_DMN, "%s already running ('%s' exists)", dmn_name,
199 pidfile_name);
200 return TRUE;
201 }
202 }
203 DBG1(DBG_DMN, "removing pidfile '%s', process not running", pidfile_name);
204 unlink(pidfile_name);
205 }
206
207 /* create new pidfile */
208 pidfile = fopen(pidfile_name, "w");
209 if (pidfile)
210 {
211 int fd;
212
213 fd = fileno(pidfile);
214 if (fd == -1 || fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
215 {
216 DBG1(DBG_LIB, "setting FD_CLOEXEC for '%s' failed: %s",
217 pidfile_name, strerror(errno));
218 }
219 ignore_result(fchown(fd,
220 lib->caps->get_uid(lib->caps),
221 lib->caps->get_gid(lib->caps)));
222 fprintf(pidfile, "%d\n", getpid());
223 fflush(pidfile);
224 return FALSE;
225 }
226 else
227 {
228 DBG1(DBG_DMN, "unable to create pidfile '%s'", pidfile_name);
229 return TRUE;
230 }
231 }
232
233 /**
234 * Delete/truncate the PID file
235 */
236 static void unlink_pidfile()
237 {
238 /* because unlinking the PID file may fail, we truncate it to ensure the
239 * daemon can be properly restarted. one probable cause for this is the
240 * combination of not running as root and the effective user lacking
241 * permissions on the parent dir(s) of the PID file */
242 if (pidfile)
243 {
244 ignore_result(ftruncate(fileno(pidfile), 0));
245 fclose(pidfile);
246 unlink(pidfile_name);
247 }
248 }
249
250 /**
251 * Main function, starts TKM backend.
252 */
253 int main(int argc, char *argv[])
254 {
255 if (argc > 0 && strlen(argv[0]) > 0)
256 {
257 dmn_name = basename(argv[0]);
258 }
259 else
260 {
261 dmn_name = "charon-tkm";
262 }
263
264 /* TKM credential set */
265 tkm_cred_t *creds;
266
267 struct sigaction action;
268 int status = SS_RC_INITIALIZATION_FAILED;
269
270 /* logging for library during initialization, as we have no bus yet */
271 dbg = dbg_syslog;
272
273 /* initialize library */
274 if (!library_init(NULL, dmn_name))
275 {
276 library_deinit();
277 exit(status);
278 }
279
280 if (!libcharon_init())
281 {
282 dbg_syslog(DBG_DMN, 1, "initialization failed - aborting %s", dmn_name);
283 goto deinit;
284 }
285
286 if (!lookup_uid_gid())
287 {
288 dbg_syslog(DBG_DMN, 1, "invalid uid/gid - aborting %s", dmn_name);
289 goto deinit;
290 }
291
292 /* the authorize hook currently does not support RFC 7427 signature auth */
293 lib->settings->set_bool(lib->settings, "%s.signature_authentication", FALSE,
294 dmn_name);
295
296 /* make sure we log to the DAEMON facility by default */
297 lib->settings->set_int(lib->settings, "%s.syslog.daemon.default",
298 lib->settings->get_int(lib->settings, "%s.syslog.daemon.default", 1,
299 dmn_name), dmn_name);
300 charon->load_loggers(charon);
301
302 DBG1(DBG_DMN, "Starting charon with TKM backend (strongSwan "VERSION")");
303
304 /* register TKM specific plugins */
305 static plugin_feature_t features[] = {
306 PLUGIN_REGISTER(NONCE_GEN, tkm_nonceg_create),
307 PLUGIN_PROVIDE(NONCE_GEN),
308 PLUGIN_REGISTER(PUBKEY, tkm_public_key_load, TRUE),
309 PLUGIN_PROVIDE(PUBKEY, KEY_RSA),
310 PLUGIN_PROVIDE(PUBKEY_VERIFY, SIGN_RSA_EMSA_PKCS1_SHA1),
311 PLUGIN_PROVIDE(PUBKEY_VERIFY, SIGN_RSA_EMSA_PKCS1_SHA2_256),
312 PLUGIN_CALLBACK(kernel_ipsec_register, tkm_kernel_ipsec_create),
313 PLUGIN_PROVIDE(CUSTOM, "kernel-ipsec"),
314 PLUGIN_CALLBACK(tkm_spi_generator_register, NULL),
315 PLUGIN_PROVIDE(CUSTOM, "tkm-spi-generator"),
316 PLUGIN_DEPENDS(CUSTOM, "libcharon-sa-managers"),
317 };
318 lib->plugins->add_static_features(lib->plugins, "tkm-backend", features,
319 countof(features), TRUE, NULL, NULL);
320
321 if (!register_dh_mapping())
322 {
323 DBG1(DBG_DMN, "no DH group mapping defined - aborting %s", dmn_name);
324 goto deinit;
325 }
326
327 /* register TKM keymat variant */
328 keymat_register_constructor(IKEV2, (keymat_constructor_t)tkm_keymat_create);
329
330 /* initialize daemon */
331 if (!charon->initialize(charon, PLUGINS))
332 {
333 DBG1(DBG_DMN, "initialization failed - aborting %s", dmn_name);
334 goto deinit;
335 }
336 lib->plugins->status(lib->plugins, LEVEL_CTRL);
337
338 /* set global pidfile name depending on daemon name */
339 if (asprintf(&pidfile_name, IPSEC_PIDDIR"/%s.pid", dmn_name) < 0)
340 {
341 DBG1(DBG_DMN, "unable to set pidfile name - aborting %s", dmn_name);
342 goto deinit;
343 };
344
345 if (check_pidfile())
346 {
347 goto deinit;
348 }
349
350 if (!lib->caps->drop(lib->caps))
351 {
352 DBG1(DBG_DMN, "capability dropping failed - aborting %s", dmn_name);
353 goto deinit;
354 }
355
356 /* initialize TKM client */
357 if (!tkm_init())
358 {
359 DBG1(DBG_DMN, "init of TKM client failed - aborting %s", dmn_name);
360 goto deinit;
361 }
362
363 /* register TKM authorization hook */
364 listener = tkm_listener_create();
365 charon->bus->add_listener(charon->bus, &listener->listener);
366
367 /* register TKM credential set */
368 creds = tkm_cred_create();
369 lib->credmgr->add_set(lib->credmgr, (credential_set_t*)creds);
370
371 /* register TKM credential encoder */
372 lib->encoding->add_encoder(lib->encoding, tkm_encoder_encode);
373
374 /* add handler for SEGV and ILL,
375 * INT and TERM are handled by sigwaitinfo() in run() */
376 action.sa_handler = segv_handler;
377 action.sa_flags = 0;
378 sigemptyset(&action.sa_mask);
379 sigaddset(&action.sa_mask, SIGINT);
380 sigaddset(&action.sa_mask, SIGTERM);
381 sigaction(SIGSEGV, &action, NULL);
382 sigaction(SIGILL, &action, NULL);
383 sigaction(SIGBUS, &action, NULL);
384 action.sa_handler = SIG_IGN;
385 sigaction(SIGPIPE, &action, NULL);
386
387 pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);
388
389 /* start daemon (i.e. the threads in the thread-pool) */
390 charon->start(charon);
391
392 /* main thread goes to run loop */
393 run();
394
395 status = 0;
396 charon->bus->remove_listener(charon->bus, &listener->listener);
397 listener->destroy(listener);
398 creds->destroy(creds);
399 lib->encoding->remove_encoder(lib->encoding, tkm_encoder_encode);
400
401 deinit:
402 destroy_dh_mapping();
403 libcharon_deinit();
404 tkm_deinit();
405 unlink_pidfile();
406 free(pidfile_name);
407 library_deinit();
408 return status;
409 }