/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-25 07:52:35 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080825075235-gq338t4ywhqhire8
* mandos-clients.conf.xml (DESCRIPTION): Do not imply that this is the
                                         only configuration file of
                                         mandos(8).
  (OPTIONS): Note that unknown options are ignored.  When describing
             "checker", be more specific about exit codes, and refer
             to PATH.  When describing "secret", refer to
             mandos-keygen(8), and note the relationship with
             "secfile".  Added synopsis to "secfile", and note
             relationship with "secret".  Added synopsis and more text
             to "host".
  (EXAMPLE): Remove Radix-64 checksum from "secret" option value.
  (SEE ALSO): New section, refer to mandos(8), mandos-keygen(8), and
              mandos.conf(5).

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
 
258
                           parsing */
 
259
    argv[1] = NULL;
 
260
  }
 
261
  *argc += 1;
 
262
  argv = realloc(argv, sizeof(char *)
 
263
                  * ((unsigned int) *argc + 1));
 
264
  if(argv == NULL){
 
265
    return NULL;
 
266
  }
 
267
  argv[*argc-1] = arg;
 
268
  argv[*argc] = NULL;
 
269
  return argv;
293
270
}
294
271
 
295
 
static void free_plugin_list(void){
296
 
  while(plugin_list != NULL){
297
 
    free_plugin(plugin_list);
 
272
static void free_plugin_list(plugin *plugin_list){
 
273
  for(plugin *next; plugin_list != NULL; plugin_list = next){
 
274
    next = plugin_list->next;
 
275
    for(char **arg = plugin_list->argv; *arg != NULL; arg++){
 
276
      free(*arg);
 
277
    }
 
278
    free(plugin_list->argv);
 
279
    for(char **env = plugin_list->environ; *env != NULL; env++){
 
280
      free(*env);
 
281
    }
 
282
    free(plugin_list->environ);
 
283
    free(plugin_list);
298
284
  }
299
285
}
300
286
 
301
287
int main(int argc, char *argv[]){
302
 
  char *plugindir = NULL;
303
 
  char *argfile = NULL;
 
288
  const char *plugindir = "/lib/mandos/plugins.d";
 
289
  const char *argfile = ARGFILE;
304
290
  FILE *conffp;
305
291
  size_t d_name_len;
306
292
  DIR *dir = NULL;
338
324
    { .name = "global-options", .key = 'g',
339
325
      .arg = "OPTION[,OPTION[,...]]",
340
326
      .doc = "Options passed to all plugins" },
341
 
    { .name = "global-env", .key = 'G',
 
327
    { .name = "global-envs", .key = 'e',
342
328
      .arg = "VAR=value",
343
329
      .doc = "Environment variable passed to all plugins" },
344
330
    { .name = "options-for", .key = 'o',
345
331
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
346
332
      .doc = "Options passed only to specified plugin" },
347
 
    { .name = "env-for", .key = 'E',
 
333
    { .name = "envs-for", .key = 'f',
348
334
      .arg = "PLUGIN:ENV=value",
349
335
      .doc = "Environment variable passed to specified plugin" },
350
336
    { .name = "disable", .key = 'd',
351
337
      .arg = "PLUGIN",
352
338
      .doc = "Disable a specific plugin", .group = 1 },
353
 
    { .name = "enable", .key = 'e',
354
 
      .arg = "PLUGIN",
355
 
      .doc = "Enable a specific plugin", .group = 1 },
356
339
    { .name = "plugin-dir", .key = 128,
357
340
      .arg = "DIRECTORY",
358
341
      .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 },
 
342
    { .name = "userid", .key = 129,
 
343
      .arg = "ID", .flags = 0,
 
344
      .doc = "User ID the plugins will run as", .group = 2 },
 
345
    { .name = "groupid", .key = 130,
 
346
      .arg = "ID", .flags = 0,
 
347
      .doc = "Group ID the plugins will run as", .group = 2 },
 
348
    { .name = "debug", .key = 131,
 
349
      .doc = "Debug mode", .group = 3 },
370
350
    { .name = NULL }
371
351
  };
372
352
  
373
 
  error_t parse_opt (int key, char *arg, __attribute__((unused))
374
 
                     struct argp_state *state) {
 
353
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
 
354
    /* Get the INPUT argument from `argp_parse', which we know is a
 
355
       pointer to our plugin list pointer. */
 
356
    plugin **plugins = state->input;
375
357
    switch (key) {
376
 
    case 'g':                   /* --global-options */
 
358
    case 'g':
377
359
      if (arg != NULL){
378
360
        char *p;
379
361
        while((p = strsep(&arg, ",")) != NULL){
380
362
          if(p[0] == '\0'){
381
363
            continue;
382
364
          }
383
 
          if(not add_argument(getplugin(NULL), p)){
 
365
          if(not add_argument(getplugin(NULL, plugins), p)){
384
366
            perror("add_argument");
385
367
            return ARGP_ERR_UNKNOWN;
386
368
          }
387
369
        }
388
370
      }
389
371
      break;
390
 
    case 'G':                   /* --global-env */
 
372
    case 'e':
391
373
      if(arg == NULL){
392
374
        break;
393
375
      }
394
 
      if(not add_environment(getplugin(NULL), arg, true)){
395
 
        perror("add_environment");
 
376
      {
 
377
        char *envdef = strdup(arg);
 
378
        if(envdef == NULL){
 
379
          break;
 
380
        }
 
381
        if(not add_environment(getplugin(NULL, plugins), envdef)){
 
382
          perror("add_environment");
 
383
        }
396
384
      }
397
385
      break;
398
 
    case 'o':                   /* --options-for */
 
386
    case 'o':
399
387
      if (arg != NULL){
400
388
        char *p_name = strsep(&arg, ":");
401
 
        if(p_name[0] == '\0' or arg == NULL){
 
389
        if(p_name[0] == '\0'){
402
390
          break;
403
391
        }
404
392
        char *opt = strsep(&arg, ":");
405
 
        if(opt[0] == '\0' or opt == NULL){
 
393
        if(opt[0] == '\0'){
406
394
          break;
407
395
        }
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;
 
396
        if(opt != NULL){
 
397
          char *p;
 
398
          while((p = strsep(&opt, ",")) != NULL){
 
399
            if(p[0] == '\0'){
 
400
              continue;
 
401
            }
 
402
            if(not add_argument(getplugin(p_name, plugins), p)){
 
403
              perror("add_argument");
 
404
              return ARGP_ERR_UNKNOWN;
 
405
            }
416
406
          }
417
407
        }
418
408
      }
419
409
      break;
420
 
    case 'E':                   /* --env-for */
 
410
    case 'f':
421
411
      if(arg == NULL){
422
412
        break;
423
413
      }
426
416
        if(envdef == NULL){
427
417
          break;
428
418
        }
429
 
        *envdef = '\0';
430
 
        if(not add_environment(getplugin(arg), envdef+1, true)){
 
419
        char *p_name = strndup(arg, (size_t) (envdef-arg));
 
420
        if(p_name == NULL){
 
421
          break;
 
422
        }
 
423
        envdef++;
 
424
        if(not add_environment(getplugin(p_name, plugins), envdef)){
431
425
          perror("add_environment");
432
426
        }
433
427
      }
434
428
      break;
435
 
    case 'd':                   /* --disable */
 
429
    case 'd':
436
430
      if (arg != NULL){
437
 
        plugin *p = getplugin(arg);
 
431
        plugin *p = getplugin(arg, plugins);
438
432
        if(p == NULL){
439
433
          return ARGP_ERR_UNKNOWN;
440
434
        }
441
435
        p->disabled = true;
442
436
      }
443
437
      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 */
 
438
    case 128:
 
439
      plugindir = arg;
 
440
      break;
 
441
    case 129:
464
442
      uid = (uid_t)strtol(arg, NULL, 10);
465
443
      break;
466
 
    case 131:                   /* --groupid */
 
444
    case 130:
467
445
      gid = (gid_t)strtol(arg, NULL, 10);
468
446
      break;
469
 
    case 132:                   /* --debug */
 
447
    case 131:
470
448
      debug = true;
471
449
      break;
472
450
    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 = "",
 
451
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
452
      break;
 
453
    case ARGP_KEY_END:
 
454
      break;
 
455
    default:
 
456
      return ARGP_ERR_UNKNOWN;
 
457
    }
 
458
    return 0;
 
459
  }
 
460
  
 
461
  plugin *plugin_list = NULL;
 
462
  
 
463
  struct argp argp = { .options = options, .parser = parse_opt,
 
464
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
524
465
                       .doc = "Mandos plugin runner -- Run plugins" };
525
466
  
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);
 
467
  ret = argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
529
468
  if (ret == ARGP_ERR_UNKNOWN){
530
469
    fprintf(stderr, "Unknown error while parsing arguments\n");
531
470
    exitstatus = EXIT_FAILURE;
532
471
    goto fallback;
533
472
  }
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
 
  }  
 
473
 
 
474
  conffp = fopen(argfile, "r");
544
475
  if(conffp != NULL){
545
476
    char *org_line = NULL;
546
477
    char *p, *arg, *new_arg, *line;
549
480
    const char whitespace_delims[] = " \r\t\f\v\n";
550
481
    const char comment_delim[] = "#";
551
482
 
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
483
    while(true){
565
484
      sret = getline(&org_line, &size, conffp);
566
485
      if(sret == -1){
574
493
          continue;
575
494
        }
576
495
        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;        
 
496
        custom_argv = add_to_argv(custom_argv, &custom_argc, new_arg);
 
497
        if (custom_argv == NULL){
 
498
          perror("add_to_argv");
 
499
          exitstatus = EXIT_FAILURE;
 
500
          goto fallback;
 
501
        }
595
502
      }
596
503
    }
597
504
    free(org_line);
598
 
  } else {
 
505
  } else{
599
506
    /* Check for harmful errors and go to fallback. Other errors might
600
507
       not affect opening plugins */
601
508
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
604
511
      goto fallback;
605
512
    }
606
513
  }
607
 
  /* If there was any arguments from configuration file,
608
 
     pass them to parser as command arguments */
 
514
 
609
515
  if(custom_argv != NULL){
610
 
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
611
 
                      0, NULL);
 
516
    custom_argv[0] = argv[0];
 
517
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0,
 
518
                      &plugin_list);
612
519
    if (ret == ARGP_ERR_UNKNOWN){
613
520
      fprintf(stderr, "Unknown error while parsing arguments\n");
614
521
      exitstatus = EXIT_FAILURE;
616
523
    }
617
524
  }
618
525
  
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
526
  if(debug){
629
527
    for(plugin *p = plugin_list; p != NULL; p=p->next){
630
528
      fprintf(stderr, "Plugin: %s has %d arguments\n",
639
537
    }
640
538
  }
641
539
  
642
 
  /* Strip permissions down to nobody */
643
540
  ret = setuid(uid);
644
541
  if (ret == -1){
645
542
    perror("setuid");
646
 
  }  
 
543
  }
 
544
  
647
545
  setgid(gid);
648
546
  if (ret == -1){
649
547
    perror("setgid");
650
548
  }
651
549
  
652
 
  if (plugindir == NULL){
653
 
    dir = opendir(PDIR);
654
 
  } else {
655
 
    dir = opendir(plugindir);
656
 
  }
657
 
  
 
550
  dir = opendir(plugindir);
658
551
  if(dir == NULL){
659
552
    perror("Could not open plugin dir");
660
553
    exitstatus = EXIT_FAILURE;
676
569
  
677
570
  FD_ZERO(&rfds_all);
678
571
  
679
 
  /* Read and execute any executable in the plugin directory*/
680
572
  while(true){
681
573
    dirst = readdir(dir);
682
574
    
683
 
    /* All directory entries have been processed */
 
575
    // All directory entries have been processed
684
576
    if(dirst == NULL){
685
577
      if (errno == EBADF){
686
578
        perror("readdir");
692
584
    
693
585
    d_name_len = strlen(dirst->d_name);
694
586
    
695
 
    /* Ignore dotfiles, backup files and other junk */
 
587
    // Ignore dotfiles, backup files and other junk
696
588
    {
697
589
      bool bad_name = false;
698
590
      
713
605
          break;
714
606
        }
715
607
      }
 
608
      
716
609
      if(bad_name){
717
610
        continue;
718
611
      }
 
612
      
719
613
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
720
614
        size_t suf_len = strlen(*suf);
721
615
        if((d_name_len >= suf_len)
736
630
    }
737
631
 
738
632
    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
 
    }
 
633
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
744
634
    if(ret < 0){
745
635
      perror("asprintf");
746
636
      continue;
752
642
      free(filename);
753
643
      continue;
754
644
    }
755
 
 
756
 
    /* Ignore non-executable files */
 
645
    
757
646
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
758
647
      if(debug){
759
648
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
762
651
      free(filename);
763
652
      continue;
764
653
    }
765
 
    
766
 
    plugin *p = getplugin(dirst->d_name);
 
654
    plugin *p = getplugin(dirst->d_name, &plugin_list);
767
655
    if(p == NULL){
768
656
      perror("getplugin");
769
657
      free(filename);
779
667
    }
780
668
    {
781
669
      /* Add global arguments to argument list for this plugin */
782
 
      plugin *g = getplugin(NULL);
 
670
      plugin *g = getplugin(NULL, &plugin_list);
783
671
      if(g != NULL){
784
672
        for(char **a = g->argv + 1; *a != NULL; a++){
785
673
          if(not add_argument(p, *a)){
788
676
        }
789
677
        /* Add global environment variables */
790
678
        for(char **e = g->environ; *e != NULL; e++){
791
 
          if(not add_environment(p, *e, false)){
 
679
          if(not add_environment(p, *e)){
792
680
            perror("add_environment");
793
681
          }
794
682
        }
799
687
       process, too. */
800
688
    if(p->environ[0] != NULL){
801
689
      for(char **e = environ; *e != NULL; e++){
802
 
        if(not add_environment(p, *e, false)){
 
690
        char *copy = strdup(*e);
 
691
        if(copy == NULL){
 
692
          perror("strdup");
 
693
          continue;
 
694
        }
 
695
        if(not add_environment(p, copy)){
803
696
          perror("add_environment");
804
697
        }
805
698
      }
812
705
      exitstatus = EXIT_FAILURE;
813
706
      goto fallback;
814
707
    }
815
 
    /* Ask OS to automatic close the pipe on exec */
816
708
    ret = set_cloexec_flag(pipefd[0]);
817
709
    if(ret < 0){
818
710
      perror("set_cloexec_flag");
832
724
      exitstatus = EXIT_FAILURE;
833
725
      goto fallback;
834
726
    }
835
 
    /* Starting a new process to be watched */
 
727
    // Starting a new process to be watched
836
728
    pid_t pid = fork();
837
729
    if(pid == -1){
838
730
      perror("fork");
876
768
      }
877
769
      /* no return */
878
770
    }
879
 
    /* Parent process */
880
 
    close(pipefd[1]);           /* Close unused write end of pipe */
 
771
    /* parent process */
881
772
    free(filename);
882
 
    plugin *new_plugin = getplugin(dirst->d_name);
883
 
    if (new_plugin == NULL){
884
 
      perror("getplugin");
 
773
    close(pipefd[1]);           /* close unused write end of pipe */
 
774
    process *new_process = malloc(sizeof(process));
 
775
    if (new_process == NULL){
 
776
      perror("malloc");
885
777
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
886
778
      if(ret < 0){
887
 
        perror("sigprocmask");
 
779
        perror("sigprocmask");
888
780
      }
889
781
      exitstatus = EXIT_FAILURE;
890
782
      goto fallback;
891
783
    }
892
784
    
893
 
    new_plugin->pid = pid;
894
 
    new_plugin->fd = pipefd[0];
895
 
    
 
785
    *new_process = (struct process){ .pid = pid,
 
786
                                     .fd = pipefd[0],
 
787
                                     .next = process_list };
 
788
    // List handling
 
789
    process_list = new_process;
896
790
    /* Unblock SIGCHLD so signal handler can be run if this process
897
791
       has already completed */
898
792
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
902
796
      goto fallback;
903
797
    }
904
798
    
905
 
    FD_SET(new_plugin->fd, &rfds_all);
 
799
    FD_SET(new_process->fd, &rfds_all);
906
800
    
907
 
    if (maxfd < new_plugin->fd){
908
 
      maxfd = new_plugin->fd;
 
801
    if (maxfd < new_process->fd){
 
802
      maxfd = new_process->fd;
909
803
    }
910
804
    
911
805
  }
912
806
  
 
807
  free_plugin_list(plugin_list);
 
808
  plugin_list = NULL;
 
809
  
913
810
  closedir(dir);
914
811
  dir = 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
 
    }
 
812
    
 
813
  if (process_list == NULL){
 
814
    fprintf(stderr, "No plugin processes started. Incorrect plugin"
 
815
            " directory?\n");
 
816
    process_list = NULL;
925
817
  }
926
 
 
927
 
  /* Main loop while running plugins exist */
928
 
  while(plugin_list){
 
818
  while(process_list){
929
819
    fd_set rfds = rfds_all;
930
820
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
931
821
    if (select_ret == -1){
935
825
    }
936
826
    /* OK, now either a process completed, or something can be read
937
827
       from one of them */
938
 
    for(plugin *proc = plugin_list; proc != NULL;){
 
828
    for(process *proc = process_list; proc ; proc = proc->next){
939
829
      /* Is this process completely done? */
940
830
      if(proc->eof and proc->completed){
941
831
        /* Only accept the plugin output if it exited cleanly */
942
832
        if(not WIFEXITED(proc->status)
943
833
           or WEXITSTATUS(proc->status) != 0){
944
834
          /* Bad exit by plugin */
945
 
 
946
835
          if(debug){
947
836
            if(WIFEXITED(proc->status)){
948
837
              fprintf(stderr, "Plugin %u exited with status %d\n",
957
846
                      (unsigned int) (proc->pid));
958
847
            }
959
848
          }
960
 
          
961
849
          /* Remove the plugin */
962
850
          FD_CLR(proc->fd, &rfds_all);
963
 
 
964
851
          /* Block signal while modifying process_list */
965
852
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
966
853
          if(ret < 0){
968
855
            exitstatus = EXIT_FAILURE;
969
856
            goto fallback;
970
857
          }
971
 
          
 
858
          /* Delete this process entry from the list */
 
859
          if(process_list == proc){
 
860
            /* First one - simple */
 
861
            process_list = proc->next;
 
862
          } else {
 
863
            /* Second one or later */
 
864
            for(process *p = process_list; p != NULL; p = p->next){
 
865
              if(p->next == proc){
 
866
                p->next = proc->next;
 
867
                break;
 
868
              }
 
869
            }
 
870
          }
972
871
          /* We are done modifying process list, so unblock signal */
973
872
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
974
873
                             NULL);
975
874
          if(ret < 0){
976
875
            perror("sigprocmask");
977
 
            exitstatus = EXIT_FAILURE;
978
 
            goto fallback;
979
 
          }
980
 
          
981
 
          if(plugin_list == NULL){
982
 
            break;
983
 
          }
984
 
          
985
 
          plugin *next_plugin = proc->next;
986
 
          free_plugin(proc);
987
 
          proc = next_plugin;
988
 
          continue;
 
876
          }
 
877
          free(proc->buffer);
 
878
          free(proc);
 
879
          /* We deleted this process from the list, so we can't go
 
880
             proc->next.  Therefore, start over from the beginning of
 
881
             the process list */
 
882
          break;
989
883
        }
990
 
        
991
884
        /* This process exited nicely, so print its buffer */
992
885
 
993
886
        bool bret = print_out_password(proc->buffer,
998
891
        }
999
892
        goto fallback;
1000
893
      }
1001
 
      
1002
894
      /* This process has not completed.  Does it have any output? */
1003
895
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
1004
896
        /* This process had nothing to say at this time */
1005
 
        proc = proc->next;
1006
897
        continue;
1007
898
      }
1008
899
      /* Before reading, make the process' data buffer large enough */
1021
912
                 BUFFER_SIZE);
1022
913
      if(ret < 0){
1023
914
        /* Read error from this process; ignore the error */
1024
 
        proc = proc->next;
1025
915
        continue;
1026
916
      }
1027
917
      if(ret == 0){
1036
926
 
1037
927
 fallback:
1038
928
  
1039
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
929
  if(process_list == NULL or exitstatus != EXIT_SUCCESS){
1040
930
    /* Fallback if all plugins failed, none are found or an error
1041
931
       occured */
1042
932
    bool bret;
1043
933
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
1044
934
    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);
 
935
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
1052
936
    if(not bret){
1053
937
      perror("print_out_password");
1054
938
      exitstatus = EXIT_FAILURE;
1063
947
  }
1064
948
 
1065
949
  if(custom_argv != NULL){
1066
 
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
 
950
    for(char **arg = custom_argv; *arg != NULL; arg++){
1067
951
      free(*arg);
1068
952
    }
1069
953
    free(custom_argv);
1070
954
  }
 
955
  free_plugin_list(plugin_list);
1071
956
  
1072
957
  if(dir != NULL){
1073
958
    closedir(dir);
1074
959
  }
1075
960
  
1076
961
  /* Free the process list and 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
 
      }
 
962
  for(process *next; process_list != NULL; process_list = next){
 
963
    next = process_list->next;
 
964
    close(process_list->fd);
 
965
    ret = kill(process_list->pid, SIGTERM);
 
966
    if(ret == -1 and errno != ESRCH){
 
967
      /* set-uid proccesses migth not get closed */
 
968
      perror("kill");
1085
969
    }
 
970
    free(process_list->buffer);
 
971
    free(process_list);
1086
972
  }
1087
973
  
1088
974
  /* Wait for any remaining child processes to terminate */
1092
978
  if(errno != ECHILD){
1093
979
    perror("wait");
1094
980
  }
1095
 
 
1096
 
  free_plugin_list();
1097
 
  
1098
 
  free(plugindir);
1099
 
  free(argfile);
1100
981
  
1101
982
  return exitstatus;
1102
983
}