/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

merge

Show diffs side-by-side

added added

removed removed

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