xref: /freebsd/sbin/hastd/hooks.c (revision 6137b5f7b8c183ee8806d79b3f1d8e5e3ddb3df3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2010 The FreeBSD Foundation
5  * Copyright (c) 2010 Pawel Jakub Dawidek <pjd@FreeBSD.org>
6  * All rights reserved.
7  *
8  * This software was developed by Pawel Jakub Dawidek under sponsorship from
9  * the FreeBSD Foundation.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/types.h>
34 #include <sys/sysctl.h>
35 #include <sys/wait.h>
36 
37 #include <errno.h>
38 #include <fcntl.h>
39 #include <paths.h>
40 #include <signal.h>
41 #include <stdbool.h>
42 #include <stdint.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <syslog.h>
47 #include <unistd.h>
48 
49 #include <pjdlog.h>
50 
51 #include "hooks.h"
52 #include "subr.h"
53 #include "synch.h"
54 
55 /* Report processes that are running for too long not often than this value. */
56 #define	REPORT_INTERVAL	60
57 
58 /* Are we initialized? */
59 static bool hooks_initialized = false;
60 
61 /*
62  * Keep all processes we forked on a global queue, so we can report nicely
63  * when they finish or report that they are running for a long time.
64  */
65 #define	HOOKPROC_MAGIC_ALLOCATED	0x80090ca
66 #define	HOOKPROC_MAGIC_ONLIST		0x80090c0
67 struct hookproc {
68 	/* Magic. */
69 	int	hp_magic;
70 	/* PID of a forked child. */
71 	pid_t	hp_pid;
72 	/* When process were forked? */
73 	time_t	hp_birthtime;
74 	/* When we logged previous reported? */
75 	time_t	hp_lastreport;
76 	/* Path to executable and all the arguments we passed. */
77 	char	hp_comm[PATH_MAX];
78 	TAILQ_ENTRY(hookproc) hp_next;
79 };
80 static TAILQ_HEAD(, hookproc) hookprocs;
81 static pthread_mutex_t hookprocs_lock;
82 
83 static void hook_remove(struct hookproc *hp);
84 static void hook_free(struct hookproc *hp);
85 
86 static void
87 descriptors(void)
88 {
89 	int fd;
90 
91 	/*
92 	 * Close all (or almost all) descriptors.
93 	 */
94 	if (pjdlog_mode_get() == PJDLOG_MODE_STD) {
95 		closefrom(MAX(MAX(STDIN_FILENO, STDOUT_FILENO),
96 		    STDERR_FILENO) + 1);
97 		return;
98 	}
99 
100 	closefrom(0);
101 
102 	/*
103 	 * Redirect stdin, stdout and stderr to /dev/null.
104 	 */
105 	fd = open(_PATH_DEVNULL, O_RDONLY);
106 	if (fd == -1) {
107 		pjdlog_errno(LOG_WARNING, "Unable to open %s for reading",
108 		    _PATH_DEVNULL);
109 	} else if (fd != STDIN_FILENO) {
110 		if (dup2(fd, STDIN_FILENO) == -1) {
111 			pjdlog_errno(LOG_WARNING,
112 			    "Unable to duplicate descriptor for stdin");
113 		}
114 		close(fd);
115 	}
116 	fd = open(_PATH_DEVNULL, O_WRONLY);
117 	if (fd == -1) {
118 		pjdlog_errno(LOG_WARNING, "Unable to open %s for writing",
119 		    _PATH_DEVNULL);
120 	} else {
121 		if (fd != STDOUT_FILENO && dup2(fd, STDOUT_FILENO) == -1) {
122 			pjdlog_errno(LOG_WARNING,
123 			    "Unable to duplicate descriptor for stdout");
124 		}
125 		if (fd != STDERR_FILENO && dup2(fd, STDERR_FILENO) == -1) {
126 			pjdlog_errno(LOG_WARNING,
127 			    "Unable to duplicate descriptor for stderr");
128 		}
129 		if (fd != STDOUT_FILENO && fd != STDERR_FILENO)
130 			close(fd);
131 	}
132 }
133 
134 void
135 hook_init(void)
136 {
137 
138 	PJDLOG_ASSERT(!hooks_initialized);
139 
140 	mtx_init(&hookprocs_lock);
141 	TAILQ_INIT(&hookprocs);
142 	hooks_initialized = true;
143 }
144 
145 void
146 hook_fini(void)
147 {
148 	struct hookproc *hp;
149 
150 	PJDLOG_ASSERT(hooks_initialized);
151 
152 	mtx_lock(&hookprocs_lock);
153 	while ((hp = TAILQ_FIRST(&hookprocs)) != NULL) {
154 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
155 		PJDLOG_ASSERT(hp->hp_pid > 0);
156 
157 		hook_remove(hp);
158 		hook_free(hp);
159 	}
160 	mtx_unlock(&hookprocs_lock);
161 
162 	mtx_destroy(&hookprocs_lock);
163 	TAILQ_INIT(&hookprocs);
164 	hooks_initialized = false;
165 }
166 
167 static struct hookproc *
168 hook_alloc(const char *path, char **args)
169 {
170 	struct hookproc *hp;
171 	unsigned int ii;
172 
173 	hp = malloc(sizeof(*hp));
174 	if (hp == NULL) {
175 		pjdlog_error("Unable to allocate %zu bytes of memory for a hook.",
176 		    sizeof(*hp));
177 		return (NULL);
178 	}
179 
180 	hp->hp_pid = 0;
181 	hp->hp_birthtime = hp->hp_lastreport = time(NULL);
182 	(void)strlcpy(hp->hp_comm, path, sizeof(hp->hp_comm));
183 	/* We start at 2nd argument as we don't want to have exec name twice. */
184 	for (ii = 1; args[ii] != NULL; ii++) {
185 		(void)snprlcat(hp->hp_comm, sizeof(hp->hp_comm), " %s",
186 		    args[ii]);
187 	}
188 	if (strlen(hp->hp_comm) >= sizeof(hp->hp_comm) - 1) {
189 		pjdlog_error("Exec path too long, correct configuration file.");
190 		free(hp);
191 		return (NULL);
192 	}
193 	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
194 	return (hp);
195 }
196 
197 static void
198 hook_add(struct hookproc *hp, pid_t pid)
199 {
200 
201 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
202 	PJDLOG_ASSERT(hp->hp_pid == 0);
203 
204 	hp->hp_pid = pid;
205 	mtx_lock(&hookprocs_lock);
206 	hp->hp_magic = HOOKPROC_MAGIC_ONLIST;
207 	TAILQ_INSERT_TAIL(&hookprocs, hp, hp_next);
208 	mtx_unlock(&hookprocs_lock);
209 }
210 
211 static void
212 hook_remove(struct hookproc *hp)
213 {
214 
215 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
216 	PJDLOG_ASSERT(hp->hp_pid > 0);
217 	PJDLOG_ASSERT(mtx_owned(&hookprocs_lock));
218 
219 	TAILQ_REMOVE(&hookprocs, hp, hp_next);
220 	hp->hp_magic = HOOKPROC_MAGIC_ALLOCATED;
221 }
222 
223 static void
224 hook_free(struct hookproc *hp)
225 {
226 
227 	PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ALLOCATED);
228 	PJDLOG_ASSERT(hp->hp_pid > 0);
229 
230 	hp->hp_magic = 0;
231 	free(hp);
232 }
233 
234 static struct hookproc *
235 hook_find(pid_t pid)
236 {
237 	struct hookproc *hp;
238 
239 	PJDLOG_ASSERT(mtx_owned(&hookprocs_lock));
240 
241 	TAILQ_FOREACH(hp, &hookprocs, hp_next) {
242 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
243 		PJDLOG_ASSERT(hp->hp_pid > 0);
244 
245 		if (hp->hp_pid == pid)
246 			break;
247 	}
248 
249 	return (hp);
250 }
251 
252 void
253 hook_check_one(pid_t pid, int status)
254 {
255 	struct hookproc *hp;
256 
257 	mtx_lock(&hookprocs_lock);
258 	hp = hook_find(pid);
259 	if (hp == NULL) {
260 		mtx_unlock(&hookprocs_lock);
261 		pjdlog_debug(1, "Unknown process pid=%u", pid);
262 		return;
263 	}
264 	hook_remove(hp);
265 	mtx_unlock(&hookprocs_lock);
266 	if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
267 		pjdlog_debug(1, "Hook exited gracefully (pid=%u, cmd=[%s]).",
268 		    pid, hp->hp_comm);
269 	} else if (WIFSIGNALED(status)) {
270 		pjdlog_error("Hook was killed (pid=%u, signal=%d, cmd=[%s]).",
271 		    pid, WTERMSIG(status), hp->hp_comm);
272 	} else {
273 		pjdlog_error("Hook exited ungracefully (pid=%u, exitcode=%d, cmd=[%s]).",
274 		    pid, WIFEXITED(status) ? WEXITSTATUS(status) : -1,
275 		    hp->hp_comm);
276 	}
277 	hook_free(hp);
278 }
279 
280 void
281 hook_check(void)
282 {
283 	struct hookproc *hp, *hp2;
284 	time_t now;
285 
286 	PJDLOG_ASSERT(hooks_initialized);
287 
288 	pjdlog_debug(2, "Checking hooks.");
289 
290 	/*
291 	 * Report about processes that are running for a long time.
292 	 */
293 	now = time(NULL);
294 	mtx_lock(&hookprocs_lock);
295 	TAILQ_FOREACH_SAFE(hp, &hookprocs, hp_next, hp2) {
296 		PJDLOG_ASSERT(hp->hp_magic == HOOKPROC_MAGIC_ONLIST);
297 		PJDLOG_ASSERT(hp->hp_pid > 0);
298 
299 		/*
300 		 * If process doesn't exists we somehow missed it.
301 		 * Not much can be done expect for logging this situation.
302 		 */
303 		if (kill(hp->hp_pid, 0) == -1 && errno == ESRCH) {
304 			pjdlog_warning("Hook disappeared (pid=%u, cmd=[%s]).",
305 			    hp->hp_pid, hp->hp_comm);
306 			hook_remove(hp);
307 			hook_free(hp);
308 			continue;
309 		}
310 
311 		/*
312 		 * Skip processes younger than 1 minute.
313 		 */
314 		if (now - hp->hp_lastreport < REPORT_INTERVAL)
315 			continue;
316 
317 		/*
318 		 * Hook is running for too long, report it.
319 		 */
320 		pjdlog_warning("Hook is running for %ju seconds (pid=%u, cmd=[%s]).",
321 		    (uintmax_t)(now - hp->hp_birthtime), hp->hp_pid,
322 		    hp->hp_comm);
323 		hp->hp_lastreport = now;
324 	}
325 	mtx_unlock(&hookprocs_lock);
326 }
327 
328 void
329 hook_exec(const char *path, ...)
330 {
331 	va_list ap;
332 
333 	va_start(ap, path);
334 	hook_execv(path, ap);
335 	va_end(ap);
336 }
337 
338 void
339 hook_execv(const char *path, va_list ap)
340 {
341 	struct hookproc *hp;
342 	char *args[64];
343 	unsigned int ii;
344 	sigset_t mask;
345 	pid_t pid;
346 
347 	PJDLOG_ASSERT(hooks_initialized);
348 
349 	if (path == NULL || path[0] == '\0')
350 		return;
351 
352 	memset(args, 0, sizeof(args));
353 	args[0] = __DECONST(char *, path);
354 	for (ii = 1; ii < sizeof(args) / sizeof(args[0]); ii++) {
355 		args[ii] = va_arg(ap, char *);
356 		if (args[ii] == NULL)
357 			break;
358 	}
359 	PJDLOG_ASSERT(ii < sizeof(args) / sizeof(args[0]));
360 
361 	hp = hook_alloc(path, args);
362 	if (hp == NULL)
363 		return;
364 
365 	pjdlog_debug(1, "Executing hook: %s", hp->hp_comm);
366 
367 	pid = fork();
368 	switch (pid) {
369 	case -1:	/* Error. */
370 		pjdlog_errno(LOG_ERR, "Unable to fork to execute %s", path);
371 		hook_free(hp);
372 		return;
373 	case 0:		/* Child. */
374 		descriptors();
375 		PJDLOG_VERIFY(sigemptyset(&mask) == 0);
376 		PJDLOG_VERIFY(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
377 		/*
378 		 * Dummy handler set for SIGCHLD in the parent will be restored
379 		 * to SIG_IGN on execv(3) below, so there is no need to do
380 		 * anything with it.
381 		 */
382 		execv(path, args);
383 		pjdlog_errno(LOG_ERR, "Unable to execute %s", path);
384 		exit(EX_SOFTWARE);
385 	default:	/* Parent. */
386 		hook_add(hp, pid);
387 		break;
388 	}
389 }
390