/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 03:53:42 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080825035342-wheobopjfhf0hive
* Makefile (maintainer-clean): Also remove "confdir".
  (run-client): Also create a key.
  (run-server): Also create a local config including a client.
  (keydir/secring.gpg, keydir/pubring.gpg, keydir/seckey.txt
  keydir/pubkey.txt): New targets used by "run-client".
  (confdir/mandos.conf, confdir/clients.conf): New targets used by
                                               "run-server".

* mandos-keygen (KEYLENGTH): Changed default to "2048".

* mandos-keygen.xml (OPTIONS): Changed default value for "--length".

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