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