/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

Earlier signal handling

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