1
/* -*- coding: utf-8 -*- */
3
* Mandos plugin runner - Run Mandos plugins
5
* Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
7
* This program is free software: you can redistribute it and/or
8
* modify it under the terms of the GNU General Public License as
9
* published by the Free Software Foundation, either version 3 of the
10
* License, or (at your option) any later version.
12
* This program is distributed in the hope that it will be useful, but
13
* WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
* General Public License for more details.
17
* You should have received a copy of the GNU General Public License
18
* along with this program. If not, see
19
* <http://www.gnu.org/licenses/>.
21
* Contact the authors at <mandos@fukt.bsnet.se>.
24
#define _GNU_SOURCE /* TEMP_FAILURE_RETRY(), getline(),
26
#include <stddef.h> /* size_t, NULL */
27
#include <stdlib.h> /* malloc(), exit(), EXIT_FAILURE,
28
EXIT_SUCCESS, realloc() */
29
#include <stdbool.h> /* bool, true, false */
30
#include <stdio.h> /* perror, popen(), fileno(),
31
fprintf(), stderr, STDOUT_FILENO */
32
#include <sys/types.h> /* DIR, opendir(), stat(), struct
33
stat, waitpid(), WIFEXITED(),
34
WEXITSTATUS(), wait(), pid_t,
35
uid_t, gid_t, getuid(), getgid(),
37
#include <sys/select.h> /* fd_set, select(), FD_ZERO(),
38
FD_SET(), FD_ISSET(), FD_CLR */
39
#include <sys/wait.h> /* wait(), waitpid(), WIFEXITED(),
41
#include <sys/stat.h> /* struct stat, stat(), S_ISREG() */
42
#include <iso646.h> /* and, or, not */
43
#include <dirent.h> /* DIR, struct dirent, opendir(),
44
readdir(), closedir(), dirfd() */
45
#include <unistd.h> /* struct stat, stat(), S_ISREG(),
46
fcntl(), setuid(), setgid(),
47
F_GETFD, F_SETFD, FD_CLOEXEC,
48
access(), pipe(), fork(), close()
49
dup2, STDOUT_FILENO, _exit(),
50
execv(), write(), read(),
52
#include <fcntl.h> /* fcntl(), F_GETFD, F_SETFD,
54
#include <string.h> /* strsep, strlen(), asprintf() */
55
#include <errno.h> /* errno */
56
#include <argp.h> /* struct argp_option, struct
57
argp_state, struct argp,
58
argp_parse(), ARGP_ERR_UNKNOWN,
59
ARGP_KEY_END, ARGP_KEY_ARG, error_t */
60
#include <signal.h> /* struct sigaction, sigemptyset(),
61
sigaddset(), sigaction(),
62
sigprocmask(), SIG_BLOCK, SIGCHLD,
63
SIG_UNBLOCK, kill() */
64
#include <errno.h> /* errno, EBADF */
66
#define BUFFER_SIZE 256
67
#define ARGFILE "/conf/conf.d/mandos/plugin-runner.conf"
69
const char *argp_program_version = "plugin-runner 1.0";
70
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
74
typedef struct process{
86
typedef struct plugin{
87
char *name; /* can be NULL or any plugin name */
96
static plugin *getplugin(char *name, plugin **plugin_list){
97
for (plugin *p = *plugin_list; p != NULL; p = p->next){
99
or (p->name and name and (strcmp(p->name, name) == 0))){
103
/* Create a new plugin */
104
plugin *new_plugin = malloc(sizeof(plugin));
105
if (new_plugin == NULL){
108
char *copy_name = NULL;
110
copy_name = strdup(name);
111
if(copy_name == NULL){
116
*new_plugin = (plugin) { .name = copy_name,
120
.next = *plugin_list };
122
new_plugin->argv = malloc(sizeof(char *) * 2);
123
if (new_plugin->argv == NULL){
128
new_plugin->argv[0] = copy_name;
129
new_plugin->argv[1] = NULL;
131
new_plugin->environ = malloc(sizeof(char *));
132
if(new_plugin->environ == NULL){
134
free(new_plugin->argv);
138
new_plugin->environ[0] = NULL;
139
/* Append the new plugin to the list */
140
*plugin_list = new_plugin;
144
/* Helper function for add_argument and add_environment */
145
static bool add_to_char_array(const char *new, char ***array,
147
/* Resize the pointed-to array to hold one more pointer */
148
*array = realloc(*array, sizeof(char *)
149
* (size_t) ((*len) + 2));
154
/* Make a copy of the new string */
155
char *copy = strdup(new);
159
/* Insert the copy */
160
(*array)[*len] = copy;
162
/* Add a new terminating NULL pointer to the last element */
163
(*array)[*len] = NULL;
167
/* Add to a plugin's argument vector */
168
static bool add_argument(plugin *p, const char *arg){
172
return add_to_char_array(arg, &(p->argv), &(p->argc));
175
/* Add to a plugin's environment */
176
static bool add_environment(plugin *p, const char *def){
180
return add_to_char_array(def, &(p->environ), &(p->envc));
185
* Based on the example in the GNU LibC manual chapter 13.13 "File
187
* *Note File Descriptor Flags:(libc)Descriptor Flags.
189
static int set_cloexec_flag(int fd)
191
int ret = fcntl(fd, F_GETFD, 0);
192
/* If reading the flags failed, return error indication now. */
196
/* Store modified flag word in the descriptor. */
197
return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
200
process *process_list = NULL;
202
/* Mark processes as completed when it exits, and save its exit
204
void handle_sigchld(__attribute__((unused)) int sig){
205
process *proc = process_list;
208
pid_t pid = waitpid(-1, &status, WNOHANG);
213
if (errno != ECHILD){
219
while(proc != NULL and proc->pid != pid){
223
/* Process not found in process list */
226
proc->status = status;
227
proc->completed = true;
231
bool print_out_password(const char *buffer, size_t length){
233
if(length>0 and buffer[length-1] == '\n'){
236
for(size_t written = 0; written < length; written += (size_t)ret){
237
ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
246
char **add_to_argv(char **argv, int *argc, char *arg){
249
argv = malloc(sizeof(char*) * 2);
253
argv[0] = NULL; /* Will be set to argv[0] in main before parsing */
257
argv = realloc(argv, sizeof(char *)
258
* ((unsigned int) *argc + 1));
267
static void free_plugin_list(plugin *plugin_list){
268
for(plugin *next; plugin_list != NULL; plugin_list = next){
269
next = plugin_list->next;
270
for(char **arg = plugin_list->argv; *arg != NULL; arg++){
273
free(plugin_list->argv);
274
for(char **env = plugin_list->environ; *env != NULL; env++){
277
free(plugin_list->environ);
282
int main(int argc, char *argv[]){
283
const char *plugindir = "/lib/mandos/plugins.d";
284
const char *argfile = ARGFILE;
288
struct dirent *dirst;
295
int exitstatus = EXIT_SUCCESS;
296
struct sigaction old_sigchld_action;
297
struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
298
.sa_flags = SA_NOCLDSTOP };
299
char **custom_argv = NULL;
302
/* Establish a signal handler */
303
sigemptyset(&sigchld_action.sa_mask);
304
ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
307
exitstatus = EXIT_FAILURE;
310
ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
313
exitstatus = EXIT_FAILURE;
317
/* The options we understand. */
318
struct argp_option options[] = {
319
{ .name = "global-options", .key = 'g',
320
.arg = "OPTION[,OPTION[,...]]",
321
.doc = "Options passed to all plugins" },
322
{ .name = "global-envs", .key = 'e',
324
.doc = "Environment variable passed to all plugins" },
325
{ .name = "options-for", .key = 'o',
326
.arg = "PLUGIN:OPTION[,OPTION[,...]]",
327
.doc = "Options passed only to specified plugin" },
328
{ .name = "envs-for", .key = 'f',
329
.arg = "PLUGIN:ENV=value",
330
.doc = "Environment variable passed to specified plugin" },
331
{ .name = "disable", .key = 'd',
333
.doc = "Disable a specific plugin", .group = 1 },
334
{ .name = "plugin-dir", .key = 128,
336
.doc = "Specify a different plugin directory", .group = 2 },
337
{ .name = "userid", .key = 129,
338
.arg = "ID", .flags = 0,
339
.doc = "User ID the plugins will run as", .group = 2 },
340
{ .name = "groupid", .key = 130,
341
.arg = "ID", .flags = 0,
342
.doc = "Group ID the plugins will run as", .group = 2 },
343
{ .name = "debug", .key = 131,
344
.doc = "Debug mode", .group = 3 },
348
error_t parse_opt (int key, char *arg, struct argp_state *state) {
349
/* Get the INPUT argument from `argp_parse', which we know is a
350
pointer to our plugin list pointer. */
351
plugin **plugins = state->input;
356
while((p = strsep(&arg, ",")) != NULL){
360
if(not add_argument(getplugin(NULL, plugins), p)){
361
perror("add_argument");
362
return ARGP_ERR_UNKNOWN;
372
char *envdef = strdup(arg);
376
if(not add_environment(getplugin(NULL, plugins), envdef)){
377
perror("add_environment");
383
char *p_name = strsep(&arg, ":");
384
if(p_name[0] == '\0'){
387
char *opt = strsep(&arg, ":");
393
while((p = strsep(&opt, ",")) != NULL){
397
if(not add_argument(getplugin(p_name, plugins), p)){
398
perror("add_argument");
399
return ARGP_ERR_UNKNOWN;
410
char *envdef = strchr(arg, ':');
414
char *p_name = strndup(arg, (size_t) (envdef-arg));
419
if(not add_environment(getplugin(p_name, plugins), envdef)){
420
perror("add_environment");
426
plugin *p = getplugin(arg, plugins);
428
return ARGP_ERR_UNKNOWN;
437
uid = (uid_t)strtol(arg, NULL, 10);
440
gid = (gid_t)strtol(arg, NULL, 10);
446
fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
451
return ARGP_ERR_UNKNOWN;
456
plugin *plugin_list = NULL;
458
struct argp argp = { .options = options, .parser = parse_opt,
459
.args_doc = "[+PLUS_SEPARATED_OPTIONS]",
460
.doc = "Mandos plugin runner -- Run plugins" };
462
ret = argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
463
if (ret == ARGP_ERR_UNKNOWN){
464
fprintf(stderr, "Unknown error while parsing arguments\n");
465
exitstatus = EXIT_FAILURE;
469
conffp = fopen(argfile, "r");
471
char *org_line = NULL;
472
char *p, *arg, *new_arg, *line;
475
const char whitespace_delims[] = " \r\t\f\v\n";
476
const char comment_delim[] = "#";
479
sret = getline(&org_line, &size, conffp);
485
arg = strsep(&line, comment_delim);
486
while((p = strsep(&arg, whitespace_delims)) != NULL){
491
custom_argv = add_to_argv(custom_argv, &custom_argc, new_arg);
492
if (custom_argv == NULL){
493
perror("add_to_argv");
494
exitstatus = EXIT_FAILURE;
501
/* Check for harmful errors and go to fallback. Other errors might
502
not affect opening plugins */
503
if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
505
exitstatus = EXIT_FAILURE;
510
if(custom_argv != NULL){
511
custom_argv[0] = argv[0];
512
ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, &plugin_list);
513
if (ret == ARGP_ERR_UNKNOWN){
514
fprintf(stderr, "Unknown error while parsing arguments\n");
515
exitstatus = EXIT_FAILURE;
521
for(plugin *p = plugin_list; p != NULL; p=p->next){
522
fprintf(stderr, "Plugin: %s has %d arguments\n",
523
p->name ? p->name : "Global", p->argc - 1);
524
for(char **a = p->argv; *a != NULL; a++){
525
fprintf(stderr, "\tArg: %s\n", *a);
527
fprintf(stderr, "...and %u environment variables\n", p->envc);
528
for(char **a = p->environ; *a != NULL; a++){
529
fprintf(stderr, "\t%s\n", *a);
544
dir = opendir(plugindir);
546
perror("Could not open plugin dir");
547
exitstatus = EXIT_FAILURE;
551
/* Set the FD_CLOEXEC flag on the directory, if possible */
553
int dir_fd = dirfd(dir);
555
ret = set_cloexec_flag(dir_fd);
557
perror("set_cloexec_flag");
558
exitstatus = EXIT_FAILURE;
567
dirst = readdir(dir);
569
// All directory entries have been processed
573
exitstatus = EXIT_FAILURE;
579
d_name_len = strlen(dirst->d_name);
581
// Ignore dotfiles, backup files and other junk
583
bool bad_name = false;
585
const char const *bad_prefixes[] = { ".", "#", NULL };
587
const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
589
".dpkg-divert", NULL };
590
for(const char **pre = bad_prefixes; *pre != NULL; pre++){
591
size_t pre_len = strlen(*pre);
592
if((d_name_len >= pre_len)
593
and strncmp((dirst->d_name), *pre, pre_len) == 0){
595
fprintf(stderr, "Ignoring plugin dir entry \"%s\""
596
" with bad prefix %s\n", dirst->d_name, *pre);
607
for(const char **suf = bad_suffixes; *suf != NULL; suf++){
608
size_t suf_len = strlen(*suf);
609
if((d_name_len >= suf_len)
610
and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
613
fprintf(stderr, "Ignoring plugin dir entry \"%s\""
614
" with bad suffix %s\n", dirst->d_name, *suf);
627
ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
633
ret = stat(filename, &st);
640
if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
642
fprintf(stderr, "Ignoring plugin dir entry \"%s\""
643
" with bad type or mode\n", filename);
648
plugin *p = getplugin(dirst->d_name, &plugin_list);
656
fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
663
/* Add global arguments to argument list for this plugin */
664
plugin *g = getplugin(NULL, &plugin_list);
666
for(char **a = g->argv + 1; *a != NULL; a++){
667
if(not add_argument(p, *a)){
668
perror("add_argument");
671
/* Add global environment variables */
672
for(char **e = g->environ; *e != NULL; e++){
673
if(not add_environment(p, *e)){
674
perror("add_environment");
679
/* If this plugin has any environment variables, we will call
680
using execve and need to duplicate the environment from this
682
if(p->environ[0] != NULL){
683
for(char **e = environ; *e != NULL; e++){
684
char *copy = strdup(*e);
689
if(not add_environment(p, copy)){
690
perror("add_environment");
699
exitstatus = EXIT_FAILURE;
702
ret = set_cloexec_flag(pipefd[0]);
704
perror("set_cloexec_flag");
705
exitstatus = EXIT_FAILURE;
708
ret = set_cloexec_flag(pipefd[1]);
710
perror("set_cloexec_flag");
711
exitstatus = EXIT_FAILURE;
714
/* Block SIGCHLD until process is safely in process list */
715
ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
717
perror("sigprocmask");
718
exitstatus = EXIT_FAILURE;
721
// Starting a new process to be watched
725
exitstatus = EXIT_FAILURE;
729
/* this is the child process */
730
ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
735
ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
737
perror("sigprocmask");
741
ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
748
/* If dir has no file descriptor, we could not set FD_CLOEXEC
749
above and must now close it manually here. */
752
if(p->environ[0] == NULL){
753
if(execv(filename, p->argv) < 0){
758
if(execve(filename, p->argv, p->environ) < 0){
767
close(pipefd[1]); /* close unused write end of pipe */
768
process *new_process = malloc(sizeof(process));
769
if (new_process == NULL){
771
ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
773
perror("sigprocmask");
775
exitstatus = EXIT_FAILURE;
779
*new_process = (struct process){ .pid = pid,
781
.next = process_list };
783
process_list = new_process;
784
/* Unblock SIGCHLD so signal handler can be run if this process
785
has already completed */
786
ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
788
perror("sigprocmask");
789
exitstatus = EXIT_FAILURE;
793
FD_SET(new_process->fd, &rfds_all);
795
if (maxfd < new_process->fd){
796
maxfd = new_process->fd;
801
free_plugin_list(plugin_list);
807
if (process_list == NULL){
808
fprintf(stderr, "No plugin processes started. Incorrect plugin"
813
fd_set rfds = rfds_all;
814
int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
815
if (select_ret == -1){
817
exitstatus = EXIT_FAILURE;
820
/* OK, now either a process completed, or something can be read
822
for(process *proc = process_list; proc ; proc = proc->next){
823
/* Is this process completely done? */
824
if(proc->eof and proc->completed){
825
/* Only accept the plugin output if it exited cleanly */
826
if(not WIFEXITED(proc->status)
827
or WEXITSTATUS(proc->status) != 0){
828
/* Bad exit by plugin */
830
if(WIFEXITED(proc->status)){
831
fprintf(stderr, "Plugin %u exited with status %d\n",
832
(unsigned int) (proc->pid),
833
WEXITSTATUS(proc->status));
834
} else if(WIFSIGNALED(proc->status)) {
835
fprintf(stderr, "Plugin %u killed by signal %d\n",
836
(unsigned int) (proc->pid),
837
WTERMSIG(proc->status));
838
} else if(WCOREDUMP(proc->status)){
839
fprintf(stderr, "Plugin %d dumped core\n",
840
(unsigned int) (proc->pid));
843
/* Remove the plugin */
844
FD_CLR(proc->fd, &rfds_all);
845
/* Block signal while modifying process_list */
846
ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
848
perror("sigprocmask");
849
exitstatus = EXIT_FAILURE;
852
/* Delete this process entry from the list */
853
if(process_list == proc){
854
/* First one - simple */
855
process_list = proc->next;
857
/* Second one or later */
858
for(process *p = process_list; p != NULL; p = p->next){
860
p->next = proc->next;
865
/* We are done modifying process list, so unblock signal */
866
ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
869
perror("sigprocmask");
873
/* We deleted this process from the list, so we can't go
874
proc->next. Therefore, start over from the beginning of
878
/* This process exited nicely, so print its buffer */
880
bool bret = print_out_password(proc->buffer, proc->buffer_length);
882
perror("print_out_password");
883
exitstatus = EXIT_FAILURE;
887
/* This process has not completed. Does it have any output? */
888
if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
889
/* This process had nothing to say at this time */
892
/* Before reading, make the process' data buffer large enough */
893
if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
894
proc->buffer = realloc(proc->buffer, proc->buffer_size
895
+ (size_t) BUFFER_SIZE);
896
if (proc->buffer == NULL){
898
exitstatus = EXIT_FAILURE;
901
proc->buffer_size += BUFFER_SIZE;
903
/* Read from the process */
904
ret = read(proc->fd, proc->buffer + proc->buffer_length,
907
/* Read error from this process; ignore the error */
914
proc->buffer_length += (size_t) ret;
922
if(process_list == NULL or exitstatus != EXIT_SUCCESS){
923
/* Fallback if all plugins failed, none are found or an error occured */
925
fprintf(stderr, "Going to fallback mode using getpass(3)\n");
926
char *passwordbuffer = getpass("Password: ");
927
bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
929
perror("print_out_password");
930
exitstatus = EXIT_FAILURE;
934
/* Restore old signal handler */
935
ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
938
exitstatus = EXIT_FAILURE;
941
if(custom_argv != NULL){
942
for(char **arg = custom_argv; *arg != NULL; arg++){
947
free_plugin_list(plugin_list);
953
/* Free the process list and kill the processes */
954
for(process *next; process_list != NULL; process_list = next){
955
next = process_list->next;
956
close(process_list->fd);
957
ret = kill(process_list->pid, SIGTERM);
958
if(ret == -1 and errno != ESRCH){
959
/* set-uid proccesses migth not get closed */
962
free(process_list->buffer);
966
/* Wait for any remaining child processes to terminate */