/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: 2009-01-18 00:18:50 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090118001850-pvg8xjwmbyt23fom
* debian/rules (install-indep): Removed "--no-start" from
                                dh_installinit.

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