/mandos/release

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2008-11-01 02:26:00 UTC
  • Revision ID: teddy@fukt.bsnet.se-20081101022600-bacs9fxmsliqrah1
* initramfs-tools-hook: Also ignore plugins named "*.dpkg-bak".
* plugin-runner.c: - '' -

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