/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2008-09-01 16:19:32 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080901161932-ostp7tulh9aijulh
* plugin-runner.c (add_environment): Never insert existing environment
                                     variables.
  (main): Rename "--global-envs" to "--global-env" and "--envs-for" to
          "--env-for".

* plugin-runner.xml (SYNOPSIS): Rename "--global-envs" to
                                "--global-env" and "--envs-for" to
                                "--env-for".
  (OPTIONS): Added "--global-env" and "--env-for".
  (FALLBACK): Add id attribute.
  (EXIT STATUS): Add text.
  (ENVIRONMENT): New section.
  (FILES): Document configuration file.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#include <stdio.h>      /* popen, fileno */
2
 
#include <iso646.h>     /* and, or, not */
3
 
#include <sys/types.h>  /* DIR, opendir, stat, struct stat, waitpid,
4
 
                           WIFEXITED, WEXITSTATUS, wait */
5
 
#include <sys/wait.h>   /* wait */
6
 
#include <dirent.h>     /* DIR, opendir */
7
 
#include <sys/stat.h>   /* stat, struct stat */
8
 
#include <unistd.h>     /* stat, struct stat, chdir */
9
 
#include <stdlib.h>     /* EXIT_FAILURE */
10
 
#include <sys/select.h> /* fd_set, select, FD_ZERO, FD_SET, FD_ISSET */
11
 
#include <string.h>     /* strlen, strcpy, strcat */
12
 
#include <stdbool.h>    /* true */
13
 
#include <sys/wait.h>   /* waitpid, WIFEXITED, WEXITSTATUS */
14
 
#include <errno.h>      /* errno */
15
 
 
16
 
struct process;
17
 
 
18
 
typedef struct process{
 
1
/*  -*- coding: utf-8 -*- */
 
2
/*
 
3
 * Mandos plugin runner - Run Mandos plugins
 
4
 *
 
5
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
6
 * 
 
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.
 
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
 
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 
15
 * General Public License for more details.
 
16
 * 
 
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/>.
 
20
 * 
 
21
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
22
 */
 
23
 
 
24
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
 
25
                                   asprintf() */
 
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(),
 
36
                                   dirfd() */
 
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(),
 
40
                                   WEXITSTATUS() */
 
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(),
 
51
                                   close() */
 
52
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
 
53
                                   FD_CLOEXEC */
 
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,
 
60
                                   error_t */
 
61
#include <signal.h>             /* struct sigaction, sigemptyset(),
 
62
                                   sigaddset(), sigaction(),
 
63
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
 
64
                                   SIG_UNBLOCK, kill() */
 
65
#include <errno.h>              /* errno, EBADF */
 
66
 
 
67
#define BUFFER_SIZE 256
 
68
 
 
69
#define PDIR "/lib/mandos/plugins.d"
 
70
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
 
71
 
 
72
const char *argp_program_version = "plugin-runner 1.0";
 
73
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
74
 
 
75
struct plugin;
 
76
 
 
77
typedef struct plugin{
 
78
  char *name;                   /* can be NULL or any plugin name */
 
79
  char **argv;
 
80
  int argc;
 
81
  char **environ;
 
82
  int envc;
 
83
  bool disabled;
 
84
 
 
85
  /* Variables used for running processes*/
19
86
  pid_t pid;
20
87
  int fd;
21
88
  char *buffer;
22
 
  int buffer_size;
23
 
  int buffer_length;
24
 
  struct process *next;
25
 
} process;
26
 
 
27
 
#define BUFFER_SIZE 256
 
89
  size_t buffer_size;
 
90
  size_t buffer_length;
 
91
  bool eof;
 
92
  volatile bool completed;
 
93
  volatile int status;
 
94
  struct plugin *next;
 
95
} plugin;
 
96
 
 
97
static plugin *plugin_list = NULL;
 
98
 
 
99
/* Gets a existing plugin based on name,
 
100
   or if none is found, creates a new one */
 
101
static plugin *getplugin(char *name){
 
102
  /* Check for exiting plugin with that name */
 
103
  for (plugin *p = plugin_list; p != NULL; p = p->next){
 
104
    if ((p->name == name)
 
105
        or (p->name and name and (strcmp(p->name, name) == 0))){
 
106
      return p;
 
107
    }
 
108
  }
 
109
  /* Create a new plugin */
 
110
  plugin *new_plugin = malloc(sizeof(plugin));
 
111
  if (new_plugin == NULL){
 
112
    return NULL;
 
113
  }
 
114
  char *copy_name = NULL;
 
115
  if(name != NULL){
 
116
    copy_name = strdup(name);
 
117
    if(copy_name == NULL){
 
118
      return NULL;
 
119
    }
 
120
  }
 
121
 
 
122
  *new_plugin = (plugin) { .name = copy_name,
 
123
                           .argc = 1,
 
124
                           .disabled = false,
 
125
                           .next = plugin_list };
 
126
  
 
127
  new_plugin->argv = malloc(sizeof(char *) * 2);
 
128
  if (new_plugin->argv == NULL){
 
129
    free(copy_name);
 
130
    free(new_plugin);
 
131
    return NULL;
 
132
  }
 
133
  new_plugin->argv[0] = copy_name;
 
134
  new_plugin->argv[1] = NULL;
 
135
  
 
136
  new_plugin->environ = malloc(sizeof(char *));
 
137
  if(new_plugin->environ == NULL){
 
138
    free(copy_name);
 
139
    free(new_plugin->argv);
 
140
    free(new_plugin);
 
141
    return NULL;
 
142
  }
 
143
  new_plugin->environ[0] = NULL;
 
144
  
 
145
  /* Append the new plugin to the list */
 
146
  plugin_list = new_plugin;
 
147
  return new_plugin;
 
148
}
 
149
 
 
150
/* Helper function for add_argument and add_environment */
 
151
static bool add_to_char_array(const char *new, char ***array,
 
152
                              int *len){
 
153
  /* Resize the pointed-to array to hold one more pointer */
 
154
  *array = realloc(*array, sizeof(char *)
 
155
                   * (size_t) ((*len) + 2));
 
156
  /* Malloc check */
 
157
  if(*array == NULL){
 
158
    return false;
 
159
  }
 
160
  /* Make a copy of the new string */
 
161
  char *copy = strdup(new);
 
162
  if(copy == NULL){
 
163
    return false;
 
164
  }
 
165
  /* Insert the copy */
 
166
  (*array)[*len] = copy;
 
167
  (*len)++;
 
168
  /* Add a new terminating NULL pointer to the last element */
 
169
  (*array)[*len] = NULL;
 
170
  return true;
 
171
}
 
172
 
 
173
/* Add to a plugin's argument vector */
 
174
static bool add_argument(plugin *p, const char *arg){
 
175
  if(p == NULL){
 
176
    return false;
 
177
  }
 
178
  return add_to_char_array(arg, &(p->argv), &(p->argc));
 
179
}
 
180
 
 
181
/* Add to a plugin's environment */
 
182
static bool add_environment(plugin *p, const char *def){
 
183
  if(p == NULL){
 
184
    return false;
 
185
  }
 
186
  /* namelen = length of name of environment variable */
 
187
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
 
188
  /* Search for this environment variable */
 
189
  for(char **e = p->environ; *e != NULL; e++){
 
190
    if(strncmp(*e, def, namelen+1) == 0){
 
191
      /* Refuse to add an existing variable */
 
192
      return true;
 
193
    }
 
194
  }
 
195
  return add_to_char_array(def, &(p->environ), &(p->envc));
 
196
}
 
197
 
 
198
/*
 
199
 * Based on the example in the GNU LibC manual chapter 13.13 "File
 
200
 * Descriptor Flags".
 
201
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
 
202
 */
 
203
static int set_cloexec_flag(int fd)
 
204
{
 
205
  int ret = fcntl(fd, F_GETFD, 0);
 
206
  /* If reading the flags failed, return error indication now. */
 
207
  if(ret < 0){
 
208
    return ret;
 
209
  }
 
210
  /* Store modified flag word in the descriptor. */
 
211
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
 
212
}
 
213
 
 
214
 
 
215
/* Mark processes as completed when they exit, and save their exit
 
216
   status. */
 
217
void handle_sigchld(__attribute__((unused)) int sig){
 
218
  while(true){
 
219
    plugin *proc = plugin_list;
 
220
    int status;
 
221
    pid_t pid = waitpid(-1, &status, WNOHANG);
 
222
    if(pid == 0){
 
223
      /* Only still running child processes */
 
224
      break;
 
225
    }
 
226
    if(pid == -1){
 
227
      if (errno != ECHILD){
 
228
        perror("waitpid");
 
229
      }
 
230
      /* No child processes */
 
231
      break;
 
232
    }
 
233
 
 
234
    /* A child exited, find it in process_list */
 
235
    while(proc != NULL and proc->pid != pid){
 
236
      proc = proc->next;
 
237
    }
 
238
    if(proc == NULL){
 
239
      /* Process not found in process list */
 
240
      continue;
 
241
    }
 
242
    proc->status = status;
 
243
    proc->completed = true;
 
244
  }
 
245
}
 
246
 
 
247
/* Prints out a password to stdout */
 
248
bool print_out_password(const char *buffer, size_t length){
 
249
  ssize_t ret;
 
250
  if(length>0 and buffer[length-1] == '\n'){
 
251
    length--;
 
252
  }
 
253
  for(size_t written = 0; written < length; written += (size_t)ret){
 
254
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
 
255
                                   length - written));
 
256
    if(ret < 0){
 
257
      return false;
 
258
    }
 
259
  }
 
260
  return true;
 
261
}
 
262
 
 
263
/* Removes and free a plugin from the plugin list */
 
264
static void free_plugin(plugin *plugin_node){
 
265
  
 
266
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
 
267
    free(*arg);
 
268
  }
 
269
  free(plugin_node->argv);
 
270
  for(char **env = plugin_node->environ; *env != NULL; env++){
 
271
    free(*env);
 
272
  }
 
273
  free(plugin_node->environ);
 
274
  free(plugin_node->buffer);
 
275
 
 
276
  /* Removes the plugin from the singly-linked list */
 
277
  if(plugin_node == plugin_list){
 
278
    /* First one - simple */
 
279
    plugin_list = plugin_list->next;
 
280
  } else {
 
281
    /* Second one or later */
 
282
    for(plugin *p = plugin_list; p != NULL; p = p->next){
 
283
      if(p->next == plugin_node){
 
284
        p->next = plugin_node->next;
 
285
        break;
 
286
      }
 
287
    }
 
288
  }
 
289
  
 
290
  free(plugin_node);
 
291
}
 
292
 
 
293
static void free_plugin_list(void){
 
294
  while(plugin_list != NULL){
 
295
    free_plugin(plugin_list);
 
296
  }
 
297
}
28
298
 
29
299
int main(int argc, char *argv[]){
30
 
  char plugindir[] = "plugins.d";
31
 
  size_t d_name_len, plugindir_len = sizeof(plugindir)-1;
32
 
  DIR *dir;
 
300
  char *plugindir = NULL;
 
301
  char *argfile = NULL;
 
302
  FILE *conffp;
 
303
  size_t d_name_len;
 
304
  DIR *dir = NULL;
33
305
  struct dirent *dirst;
34
306
  struct stat st;
35
 
  fd_set rfds_orig;
 
307
  fd_set rfds_all;
36
308
  int ret, maxfd = 0;
37
 
  process *process_list = NULL;
38
 
  
39
 
  dir = opendir(plugindir);
40
 
 
 
309
  uid_t uid = 65534;
 
310
  gid_t gid = 65534;
 
311
  bool debug = false;
 
312
  int exitstatus = EXIT_SUCCESS;
 
313
  struct sigaction old_sigchld_action;
 
314
  struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
 
315
                                      .sa_flags = SA_NOCLDSTOP };
 
316
  char **custom_argv = NULL;
 
317
  int custom_argc = 0;
 
318
  
 
319
  /* Establish a signal handler */
 
320
  sigemptyset(&sigchld_action.sa_mask);
 
321
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
 
322
  if(ret == -1){
 
323
    perror("sigaddset");
 
324
    exitstatus = EXIT_FAILURE;
 
325
    goto fallback;
 
326
  }
 
327
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
 
328
  if(ret == -1){
 
329
    perror("sigaction");
 
330
    exitstatus = EXIT_FAILURE;
 
331
    goto fallback;
 
332
  }
 
333
  
 
334
  /* The options we understand. */
 
335
  struct argp_option options[] = {
 
336
    { .name = "global-options", .key = 'g',
 
337
      .arg = "OPTION[,OPTION[,...]]",
 
338
      .doc = "Options passed to all plugins" },
 
339
    { .name = "global-env", .key = 'e',
 
340
      .arg = "VAR=value",
 
341
      .doc = "Environment variable passed to all plugins" },
 
342
    { .name = "options-for", .key = 'o',
 
343
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
 
344
      .doc = "Options passed only to specified plugin" },
 
345
    { .name = "env-for", .key = 'f',
 
346
      .arg = "PLUGIN:ENV=value",
 
347
      .doc = "Environment variable passed to specified plugin" },
 
348
    { .name = "disable", .key = 'd',
 
349
      .arg = "PLUGIN",
 
350
      .doc = "Disable a specific plugin", .group = 1 },
 
351
    { .name = "plugin-dir", .key = 128,
 
352
      .arg = "DIRECTORY",
 
353
      .doc = "Specify a different plugin directory", .group = 2 },
 
354
    { .name = "config-file", .key = 129,
 
355
      .arg = "FILE",
 
356
      .doc = "Specify a different configuration file", .group = 2 },
 
357
    { .name = "userid", .key = 130,
 
358
      .arg = "ID", .flags = 0,
 
359
      .doc = "User ID the plugins will run as", .group = 3 },
 
360
    { .name = "groupid", .key = 131,
 
361
      .arg = "ID", .flags = 0,
 
362
      .doc = "Group ID the plugins will run as", .group = 3 },
 
363
    { .name = "debug", .key = 132,
 
364
      .doc = "Debug mode", .group = 4 },
 
365
    { .name = NULL }
 
366
  };
 
367
  
 
368
  error_t parse_opt (int key, char *arg, __attribute__((unused))
 
369
                     struct argp_state *state) {
 
370
    /* Get the INPUT argument from `argp_parse', which we know is a
 
371
       pointer to our plugin list pointer. */
 
372
    switch (key) {
 
373
    case 'g':                   /* --global-options */
 
374
      if (arg != NULL){
 
375
        char *p;
 
376
        while((p = strsep(&arg, ",")) != NULL){
 
377
          if(p[0] == '\0'){
 
378
            continue;
 
379
          }
 
380
          if(not add_argument(getplugin(NULL), p)){
 
381
            perror("add_argument");
 
382
            return ARGP_ERR_UNKNOWN;
 
383
          }
 
384
        }
 
385
      }
 
386
      break;
 
387
    case 'e':                   /* --global-env */
 
388
      if(arg == NULL){
 
389
        break;
 
390
      }
 
391
      {
 
392
        char *envdef = strdup(arg);
 
393
        if(envdef == NULL){
 
394
          break;
 
395
        }
 
396
        if(not add_environment(getplugin(NULL), envdef)){
 
397
          perror("add_environment");
 
398
        }
 
399
      }
 
400
      break;
 
401
    case 'o':                   /* --options-for */
 
402
      if (arg != NULL){
 
403
        char *p_name = strsep(&arg, ":");
 
404
        if(p_name[0] == '\0'){
 
405
          break;
 
406
        }
 
407
        char *opt = strsep(&arg, ":");
 
408
        if(opt[0] == '\0'){
 
409
          break;
 
410
        }
 
411
        if(opt != NULL){
 
412
          char *p;
 
413
          while((p = strsep(&opt, ",")) != NULL){
 
414
            if(p[0] == '\0'){
 
415
              continue;
 
416
            }
 
417
            if(not add_argument(getplugin(p_name), p)){
 
418
              perror("add_argument");
 
419
              return ARGP_ERR_UNKNOWN;
 
420
            }
 
421
          }
 
422
        }
 
423
      }
 
424
      break;
 
425
    case 'f':                   /* --env-for */
 
426
      if(arg == NULL){
 
427
        break;
 
428
      }
 
429
      {
 
430
        char *envdef = strchr(arg, ':');
 
431
        if(envdef == NULL){
 
432
          break;
 
433
        }
 
434
        char *p_name = strndup(arg, (size_t) (envdef-arg));
 
435
        if(p_name == NULL){
 
436
          break;
 
437
        }
 
438
        envdef++;
 
439
        if(not add_environment(getplugin(p_name), envdef)){
 
440
          perror("add_environment");
 
441
        }
 
442
      }
 
443
      break;
 
444
    case 'd':                   /* --disable */
 
445
      if (arg != NULL){
 
446
        plugin *p = getplugin(arg);
 
447
        if(p == NULL){
 
448
          return ARGP_ERR_UNKNOWN;
 
449
        }
 
450
        p->disabled = true;
 
451
      }
 
452
      break;
 
453
    case 128:                   /* --plugin-dir */
 
454
      plugindir = strdup(arg);
 
455
      if(plugindir == NULL){
 
456
        perror("strdup");
 
457
      }      
 
458
      break;
 
459
    case 129:                   /* --config-file */
 
460
      argfile = strdup(arg);
 
461
      if(argfile == NULL){
 
462
        perror("strdup");
 
463
      }
 
464
      break;      
 
465
    case 130:                   /* --userid */
 
466
      uid = (uid_t)strtol(arg, NULL, 10);
 
467
      break;
 
468
    case 131:                   /* --groupid */
 
469
      gid = (gid_t)strtol(arg, NULL, 10);
 
470
      break;
 
471
    case 132:                   /* --debug */
 
472
      debug = true;
 
473
      break;
 
474
    case ARGP_KEY_ARG:
 
475
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
476
      break;
 
477
    case ARGP_KEY_END:
 
478
      break;
 
479
    default:
 
480
      return ARGP_ERR_UNKNOWN;
 
481
    }
 
482
    return 0;
 
483
  }
 
484
  
 
485
  struct argp argp = { .options = options, .parser = parse_opt,
 
486
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
 
487
                       .doc = "Mandos plugin runner -- Run plugins" };
 
488
  
 
489
  ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
 
490
  if (ret == ARGP_ERR_UNKNOWN){
 
491
    fprintf(stderr, "Unknown error while parsing arguments\n");
 
492
    exitstatus = EXIT_FAILURE;
 
493
    goto fallback;
 
494
  }
 
495
 
 
496
  /* Opens the configfile if aviable */
 
497
  if (argfile == NULL){
 
498
    conffp = fopen(AFILE, "r");
 
499
  } else {
 
500
    conffp = fopen(argfile, "r");
 
501
  }  
 
502
  if(conffp != NULL){
 
503
    char *org_line = NULL;
 
504
    char *p, *arg, *new_arg, *line;
 
505
    size_t size = 0;
 
506
    ssize_t sret;
 
507
    const char whitespace_delims[] = " \r\t\f\v\n";
 
508
    const char comment_delim[] = "#";
 
509
 
 
510
    custom_argc = 1;
 
511
    custom_argv = malloc(sizeof(char*) * 2);
 
512
    if(custom_argv == NULL){
 
513
      perror("malloc");
 
514
      exitstatus = EXIT_FAILURE;
 
515
      goto fallback;
 
516
    }
 
517
    custom_argv[0] = argv[0];
 
518
    custom_argv[1] = NULL;
 
519
 
 
520
    /* for each line in the config file, strip whitespace and ignore
 
521
       commented text */
 
522
    while(true){
 
523
      sret = getline(&org_line, &size, conffp);
 
524
      if(sret == -1){
 
525
        break;
 
526
      }
 
527
 
 
528
      line = org_line;
 
529
      arg = strsep(&line, comment_delim);
 
530
      while((p = strsep(&arg, whitespace_delims)) != NULL){
 
531
        if(p[0] == '\0'){
 
532
          continue;
 
533
        }
 
534
        new_arg = strdup(p);
 
535
        if(new_arg == NULL){
 
536
          perror("strdup");
 
537
          exitstatus = EXIT_FAILURE;
 
538
          free(org_line);
 
539
          goto fallback;
 
540
        }
 
541
        
 
542
        custom_argc += 1;
 
543
        custom_argv = realloc(custom_argv, sizeof(char *)
 
544
                              * ((unsigned int) custom_argc + 1));
 
545
        if(custom_argv == NULL){
 
546
          perror("realloc");
 
547
          exitstatus = EXIT_FAILURE;
 
548
          free(org_line);
 
549
          goto fallback;
 
550
        }
 
551
        custom_argv[custom_argc-1] = new_arg;
 
552
        custom_argv[custom_argc] = NULL;        
 
553
      }
 
554
    }
 
555
    free(org_line);
 
556
  } else{
 
557
    /* Check for harmful errors and go to fallback. Other errors might
 
558
       not affect opening plugins */
 
559
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
560
      perror("fopen");
 
561
      exitstatus = EXIT_FAILURE;
 
562
      goto fallback;
 
563
    }
 
564
  }
 
565
  /* If there was any arguments from configuration file,
 
566
     pass them to parser as command arguments */
 
567
  if(custom_argv != NULL){
 
568
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, NULL);
 
569
    if (ret == ARGP_ERR_UNKNOWN){
 
570
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
571
      exitstatus = EXIT_FAILURE;
 
572
      goto fallback;
 
573
    }
 
574
  }
 
575
  
 
576
  if(debug){
 
577
    for(plugin *p = plugin_list; p != NULL; p=p->next){
 
578
      fprintf(stderr, "Plugin: %s has %d arguments\n",
 
579
              p->name ? p->name : "Global", p->argc - 1);
 
580
      for(char **a = p->argv; *a != NULL; a++){
 
581
        fprintf(stderr, "\tArg: %s\n", *a);
 
582
      }
 
583
      fprintf(stderr, "...and %u environment variables\n", p->envc);
 
584
      for(char **a = p->environ; *a != NULL; a++){
 
585
        fprintf(stderr, "\t%s\n", *a);
 
586
      }
 
587
    }
 
588
  }
 
589
 
 
590
  /* Strip permissions down to nobody */
 
591
  ret = setuid(uid);
 
592
  if (ret == -1){
 
593
    perror("setuid");
 
594
  }  
 
595
  setgid(gid);
 
596
  if (ret == -1){
 
597
    perror("setgid");
 
598
  }
 
599
 
 
600
  if (plugindir == NULL){
 
601
    dir = opendir(PDIR);
 
602
  } else {
 
603
    dir = opendir(plugindir);
 
604
  }
 
605
  
41
606
  if(dir == NULL){
42
 
    fprintf(stderr, "Can not open directory\n");
43
 
    return EXIT_FAILURE;
44
 
  }
45
 
  
46
 
  FD_ZERO(&rfds_orig);
47
 
  
 
607
    perror("Could not open plugin dir");
 
608
    exitstatus = EXIT_FAILURE;
 
609
    goto fallback;
 
610
  }
 
611
  
 
612
  /* Set the FD_CLOEXEC flag on the directory, if possible */
 
613
  {
 
614
    int dir_fd = dirfd(dir);
 
615
    if(dir_fd >= 0){
 
616
      ret = set_cloexec_flag(dir_fd);
 
617
      if(ret < 0){
 
618
        perror("set_cloexec_flag");
 
619
        exitstatus = EXIT_FAILURE;
 
620
        goto fallback;
 
621
      }
 
622
    }
 
623
  }
 
624
  
 
625
  FD_ZERO(&rfds_all);
 
626
 
 
627
  /* Read and execute any executable in the plugin directory*/
48
628
  while(true){
49
629
    dirst = readdir(dir);
50
630
    
51
631
    // All directory entries have been processed
52
632
    if(dirst == NULL){
 
633
      if (errno == EBADF){
 
634
        perror("readdir");
 
635
        exitstatus = EXIT_FAILURE;
 
636
        goto fallback;
 
637
      }
53
638
      break;
54
639
    }
55
640
    
56
641
    d_name_len = strlen(dirst->d_name);
57
642
    
58
 
    // Ignore dotfiles and backup files
59
 
    if (dirst->d_name[0] == '.'
60
 
        or dirst->d_name[d_name_len - 1] == '~'){
61
 
      continue;
62
 
    }
63
 
    
64
 
    char *filename = malloc(d_name_len + plugindir_len + 1);
65
 
    strcpy(filename, plugindir);
66
 
    strcat(filename, "/");
67
 
    strcat(filename, dirst->d_name);    
68
 
    
69
 
    stat(filename, &st);
70
 
 
71
 
    if (S_ISREG(st.st_mode) and (access(filename, X_OK) == 0)){
72
 
      // Starting a new process to be watched
73
 
      process *new_process = malloc(sizeof(process));
74
 
      int pipefd[2];
75
 
      pipe(pipefd);
76
 
      new_process->pid = fork();
77
 
      if(new_process->pid == 0){
78
 
        /* this is the child process */
 
643
    // Ignore dotfiles, backup files and other junk
 
644
    {
 
645
      bool bad_name = false;
 
646
      
 
647
      const char const *bad_prefixes[] = { ".", "#", NULL };
 
648
      
 
649
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
 
650
                                           ".dpkg-old",
 
651
                                           ".dpkg-divert", NULL };
 
652
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
 
653
        size_t pre_len = strlen(*pre);
 
654
        if((d_name_len >= pre_len)
 
655
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
 
656
          if(debug){
 
657
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
658
                    " with bad prefix %s\n", dirst->d_name, *pre);
 
659
          }
 
660
          bad_name = true;
 
661
          break;
 
662
        }
 
663
      }
 
664
      if(bad_name){
 
665
        continue;
 
666
      }
 
667
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
 
668
        size_t suf_len = strlen(*suf);
 
669
        if((d_name_len >= suf_len)
 
670
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
 
671
                == 0)){
 
672
          if(debug){
 
673
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
674
                    " with bad suffix %s\n", dirst->d_name, *suf);
 
675
          }
 
676
          bad_name = true;
 
677
          break;
 
678
        }
 
679
      }
 
680
      
 
681
      if(bad_name){
 
682
        continue;
 
683
      }
 
684
    }
 
685
 
 
686
    char *filename;
 
687
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
688
    if(ret < 0){
 
689
      perror("asprintf");
 
690
      continue;
 
691
    }
 
692
    
 
693
    ret = stat(filename, &st);
 
694
    if (ret == -1){
 
695
      perror("stat");
 
696
      free(filename);
 
697
      continue;
 
698
    }
 
699
 
 
700
    /* Ignore non-executable files */
 
701
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
 
702
      if(debug){
 
703
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
704
                " with bad type or mode\n", filename);
 
705
      }
 
706
      free(filename);
 
707
      continue;
 
708
    }
 
709
    
 
710
    plugin *p = getplugin(dirst->d_name);
 
711
    if(p == NULL){
 
712
      perror("getplugin");
 
713
      free(filename);
 
714
      continue;
 
715
    }
 
716
    if(p->disabled){
 
717
      if(debug){
 
718
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
 
719
                dirst->d_name);
 
720
      }
 
721
      free(filename);
 
722
      continue;
 
723
    }
 
724
    {
 
725
      /* Add global arguments to argument list for this plugin */
 
726
      plugin *g = getplugin(NULL);
 
727
      if(g != NULL){
 
728
        for(char **a = g->argv + 1; *a != NULL; a++){
 
729
          if(not add_argument(p, *a)){
 
730
            perror("add_argument");
 
731
          }
 
732
        }
 
733
        /* Add global environment variables */
 
734
        for(char **e = g->environ; *e != NULL; e++){
 
735
          if(not add_environment(p, *e)){
 
736
            perror("add_environment");
 
737
          }
 
738
        }
 
739
      }
 
740
    }
 
741
    /* If this plugin has any environment variables, we will call
 
742
       using execve and need to duplicate the environment from this
 
743
       process, too. */
 
744
    if(p->environ[0] != NULL){
 
745
      for(char **e = environ; *e != NULL; e++){
 
746
        char *copy = strdup(*e);
 
747
        if(copy == NULL){
 
748
          perror("strdup");
 
749
          continue;
 
750
        }
 
751
        if(not add_environment(p, copy)){
 
752
          perror("add_environment");
 
753
        }
 
754
      }
 
755
    }
 
756
    
 
757
    int pipefd[2];
 
758
    ret = pipe(pipefd);
 
759
    if (ret == -1){
 
760
      perror("pipe");
 
761
      exitstatus = EXIT_FAILURE;
 
762
      goto fallback;
 
763
    }
 
764
    /* Ask OS to automatic close the pipe on exec */
 
765
    ret = set_cloexec_flag(pipefd[0]);
 
766
    if(ret < 0){
 
767
      perror("set_cloexec_flag");
 
768
      exitstatus = EXIT_FAILURE;
 
769
      goto fallback;
 
770
    }
 
771
    ret = set_cloexec_flag(pipefd[1]);
 
772
    if(ret < 0){
 
773
      perror("set_cloexec_flag");
 
774
      exitstatus = EXIT_FAILURE;
 
775
      goto fallback;
 
776
    }
 
777
    /* Block SIGCHLD until process is safely in process list */
 
778
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
779
    if(ret < 0){
 
780
      perror("sigprocmask");
 
781
      exitstatus = EXIT_FAILURE;
 
782
      goto fallback;
 
783
    }
 
784
    // Starting a new process to be watched
 
785
    pid_t pid = fork();
 
786
    if(pid == -1){
 
787
      perror("fork");
 
788
      exitstatus = EXIT_FAILURE;
 
789
      goto fallback;
 
790
    }
 
791
    if(pid == 0){
 
792
      /* this is the child process */
 
793
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
 
794
      if(ret < 0){
 
795
        perror("sigaction");
 
796
        _exit(EXIT_FAILURE);
 
797
      }
 
798
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
799
      if(ret < 0){
 
800
        perror("sigprocmask");
 
801
        _exit(EXIT_FAILURE);
 
802
      }
 
803
 
 
804
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
 
805
      if(ret == -1){
 
806
        perror("dup2");
 
807
        _exit(EXIT_FAILURE);
 
808
      }
 
809
      
 
810
      if(dirfd(dir) < 0){
 
811
        /* If dir has no file descriptor, we could not set FD_CLOEXEC
 
812
           above and must now close it manually here. */
79
813
        closedir(dir);
80
 
        close(pipefd[0]);       /* close unused read end of pipe */
81
 
        dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
82
 
        /* create a new modified argument list */
83
 
        char **new_argv = malloc(sizeof(char *) * argc + 1);
84
 
        new_argv[0] = filename;
85
 
        for(int i = 1; i < argc; i++){
86
 
          new_argv[i] = argv[i];
87
 
        }
88
 
        new_argv[argc] = NULL;
89
 
        if(execv(filename, new_argv) < 0){
90
 
          perror(argv[0]);
91
 
          close(pipefd[1]);
92
 
          exit(EXIT_FAILURE);
93
 
        }
94
 
        /* no return */
95
 
      }
96
 
      close(pipefd[1]);         /* close unused write end of pipe */
97
 
      new_process->fd = pipefd[0];
98
 
      new_process->buffer = malloc(BUFFER_SIZE);
99
 
      if (new_process->buffer == NULL){
100
 
        perror(argv[0]);
101
 
        goto end;
102
 
      }
103
 
      new_process->buffer_size = BUFFER_SIZE;
104
 
      new_process->buffer_length = 0;
105
 
      FD_SET(new_process->fd, &rfds_orig);
106
 
      
107
 
      if (maxfd < new_process->fd){
108
 
        maxfd = new_process->fd;
109
 
      }
110
 
      
111
 
      //List handling
112
 
      new_process->next = process_list;
113
 
      process_list = new_process;
114
 
    }
 
814
      }
 
815
      if(p->environ[0] == NULL){
 
816
        if(execv(filename, p->argv) < 0){
 
817
          perror("execv");
 
818
          _exit(EXIT_FAILURE);
 
819
        }
 
820
      } else {
 
821
        if(execve(filename, p->argv, p->environ) < 0){
 
822
          perror("execve");
 
823
          _exit(EXIT_FAILURE);
 
824
        }
 
825
      }
 
826
      /* no return */
 
827
    }
 
828
    /* Parent process */
 
829
    close(pipefd[1]);           /* Close unused write end of pipe */
 
830
    free(filename);
 
831
    plugin *new_plugin = getplugin(dirst->d_name);
 
832
    if (new_plugin == NULL){
 
833
      perror("getplugin");
 
834
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
835
      if(ret < 0){
 
836
        perror("sigprocmask");
 
837
      }
 
838
      exitstatus = EXIT_FAILURE;
 
839
      goto fallback;
 
840
    }
 
841
    
 
842
    new_plugin->pid = pid;
 
843
    new_plugin->fd = pipefd[0];
 
844
    
 
845
    /* Unblock SIGCHLD so signal handler can be run if this process
 
846
       has already completed */
 
847
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
848
    if(ret < 0){
 
849
      perror("sigprocmask");
 
850
      exitstatus = EXIT_FAILURE;
 
851
      goto fallback;
 
852
    }
 
853
    
 
854
    FD_SET(new_plugin->fd, &rfds_all);
 
855
    
 
856
    if (maxfd < new_plugin->fd){
 
857
      maxfd = new_plugin->fd;
 
858
    }
 
859
    
115
860
  }
116
861
  
117
862
  closedir(dir);
118
 
  
119
 
  if (process_list != NULL){
120
 
    while(true){
121
 
      fd_set rfds = rfds_orig;
122
 
      int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
123
 
      if (select_ret == -1){
124
 
        perror(argv[0]);
125
 
        goto end;
126
 
      }else{    
127
 
        for(process *process_itr = process_list; process_itr != NULL;
128
 
            process_itr = process_itr->next){
129
 
          if(FD_ISSET(process_itr->fd, &rfds)){
130
 
            if(process_itr->buffer_length + BUFFER_SIZE
131
 
               > process_itr->buffer_size){
132
 
                process_itr->buffer = realloc(process_itr->buffer,
133
 
                                              process_itr->buffer_size
134
 
                                              + BUFFER_SIZE);
135
 
                if (process_itr->buffer == NULL){
136
 
                  perror(argv[0]);
137
 
                  goto end;
138
 
                }
139
 
                process_itr->buffer_size += BUFFER_SIZE;
140
 
            }
141
 
            ret = read(process_itr->fd, process_itr->buffer
142
 
                       + process_itr->buffer_length, BUFFER_SIZE);
143
 
            process_itr->buffer_length+=ret;
144
 
            if(ret == 0){
145
 
              /* got EOF */
146
 
              /* wait for process exit */
147
 
              int status;
148
 
              waitpid(process_itr->pid, &status, 0);
149
 
              if(WIFEXITED(status) and WEXITSTATUS(status) == 0){
150
 
                write(STDOUT_FILENO, process_itr->buffer,
151
 
                      process_itr->buffer_length);
152
 
                goto end;
153
 
              } else {
154
 
                FD_CLR(process_itr->fd, &rfds_orig);
155
 
              }
156
 
            }
157
 
          }
158
 
        }
159
 
      }
160
 
    }
161
 
  }
162
 
  
163
 
 end:
164
 
  for(process *process_itr = process_list; process_itr != NULL;
165
 
      process_itr = process_itr->next){
166
 
    close(process_itr->fd);
167
 
    kill(process_itr->pid, SIGTERM);
168
 
    free(process_itr->buffer);
169
 
  }
170
 
  
171
 
  while(true){
172
 
    int status;
173
 
    ret = wait(&status);
174
 
    if (ret == -1){
175
 
      if(errno != ECHILD){
176
 
        perror("wait");
177
 
      }
 
863
  dir = NULL;
 
864
 
 
865
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
866
    if(p->pid != 0){
178
867
      break;
179
868
    }
180
 
  }  
181
 
  return EXIT_SUCCESS;
 
869
    if(p->next == NULL){
 
870
      fprintf(stderr, "No plugin processes started. Incorrect plugin"
 
871
              " directory?\n");
 
872
      free_plugin_list();
 
873
    }
 
874
  }
 
875
 
 
876
  /* Main loop while running plugins exist */
 
877
  while(plugin_list){
 
878
    fd_set rfds = rfds_all;
 
879
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
 
880
    if (select_ret == -1){
 
881
      perror("select");
 
882
      exitstatus = EXIT_FAILURE;
 
883
      goto fallback;
 
884
    }
 
885
    /* OK, now either a process completed, or something can be read
 
886
       from one of them */
 
887
    for(plugin *proc = plugin_list; proc != NULL; proc = proc->next){
 
888
      /* Is this process completely done? */
 
889
      if(proc->eof and proc->completed){
 
890
        /* Only accept the plugin output if it exited cleanly */
 
891
        if(not WIFEXITED(proc->status)
 
892
           or WEXITSTATUS(proc->status) != 0){
 
893
          /* Bad exit by plugin */
 
894
 
 
895
          if(debug){
 
896
            if(WIFEXITED(proc->status)){
 
897
              fprintf(stderr, "Plugin %u exited with status %d\n",
 
898
                      (unsigned int) (proc->pid),
 
899
                      WEXITSTATUS(proc->status));
 
900
            } else if(WIFSIGNALED(proc->status)) {
 
901
              fprintf(stderr, "Plugin %u killed by signal %d\n",
 
902
                      (unsigned int) (proc->pid),
 
903
                      WTERMSIG(proc->status));
 
904
            } else if(WCOREDUMP(proc->status)){
 
905
              fprintf(stderr, "Plugin %d dumped core\n",
 
906
                      (unsigned int) (proc->pid));
 
907
            }
 
908
          }
 
909
          
 
910
          /* Remove the plugin */
 
911
          FD_CLR(proc->fd, &rfds_all);
 
912
 
 
913
          /* Block signal while modifying process_list */
 
914
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
915
          if(ret < 0){
 
916
            perror("sigprocmask");
 
917
            exitstatus = EXIT_FAILURE;
 
918
            goto fallback;
 
919
          }
 
920
          free_plugin(proc);
 
921
          /* We are done modifying process list, so unblock signal */
 
922
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
 
923
                             NULL);
 
924
          if(ret < 0){
 
925
            perror("sigprocmask");
 
926
            exitstatus = EXIT_FAILURE;
 
927
            goto fallback;
 
928
          }
 
929
          
 
930
          if(plugin_list == NULL){
 
931
            break;
 
932
          }
 
933
          continue;
 
934
        }
 
935
        
 
936
        /* This process exited nicely, so print its buffer */
 
937
 
 
938
        bool bret = print_out_password(proc->buffer,
 
939
                                       proc->buffer_length);
 
940
        if(not bret){
 
941
          perror("print_out_password");
 
942
          exitstatus = EXIT_FAILURE;
 
943
        }
 
944
        goto fallback;
 
945
      }
 
946
      
 
947
      /* This process has not completed.  Does it have any output? */
 
948
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
 
949
        /* This process had nothing to say at this time */
 
950
        continue;
 
951
      }
 
952
      /* Before reading, make the process' data buffer large enough */
 
953
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
 
954
        proc->buffer = realloc(proc->buffer, proc->buffer_size
 
955
                               + (size_t) BUFFER_SIZE);
 
956
        if (proc->buffer == NULL){
 
957
          perror("malloc");
 
958
          exitstatus = EXIT_FAILURE;
 
959
          goto fallback;
 
960
        }
 
961
        proc->buffer_size += BUFFER_SIZE;
 
962
      }
 
963
      /* Read from the process */
 
964
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
 
965
                 BUFFER_SIZE);
 
966
      if(ret < 0){
 
967
        /* Read error from this process; ignore the error */
 
968
        continue;
 
969
      }
 
970
      if(ret == 0){
 
971
        /* got EOF */
 
972
        proc->eof = true;
 
973
      } else {
 
974
        proc->buffer_length += (size_t) ret;
 
975
      }
 
976
    }
 
977
  }
 
978
 
 
979
 
 
980
 fallback:
 
981
  
 
982
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
983
    /* Fallback if all plugins failed, none are found or an error
 
984
       occured */
 
985
    bool bret;
 
986
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
 
987
    char *passwordbuffer = getpass("Password: ");
 
988
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
 
989
    if(not bret){
 
990
      perror("print_out_password");
 
991
      exitstatus = EXIT_FAILURE;
 
992
    }
 
993
  }
 
994
  
 
995
  /* Restore old signal handler */
 
996
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
 
997
  if(ret == -1){
 
998
    perror("sigaction");
 
999
    exitstatus = EXIT_FAILURE;
 
1000
  }
 
1001
 
 
1002
  if(custom_argv != NULL){
 
1003
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
 
1004
      free(*arg);
 
1005
    }
 
1006
    free(custom_argv);
 
1007
  }
 
1008
  
 
1009
  if(dir != NULL){
 
1010
    closedir(dir);
 
1011
  }
 
1012
  
 
1013
  /* Free the process list and kill the processes */
 
1014
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
1015
    if(p->pid != 0){
 
1016
      close(p->fd);
 
1017
      ret = kill(p->pid, SIGTERM);
 
1018
      if(ret == -1 and errno != ESRCH){
 
1019
        /* Set-uid proccesses might not get closed */
 
1020
        perror("kill");
 
1021
      }
 
1022
    }
 
1023
  }
 
1024
  
 
1025
  /* Wait for any remaining child processes to terminate */
 
1026
  do{
 
1027
    ret = wait(NULL);
 
1028
  } while(ret >= 0);
 
1029
  if(errno != ECHILD){
 
1030
    perror("wait");
 
1031
  }
 
1032
 
 
1033
  free_plugin_list();
 
1034
  
 
1035
  free(plugindir);
 
1036
  free(argfile);
 
1037
  
 
1038
  return exitstatus;
182
1039
}