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