/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

merge

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