/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
new approve/deny functionallity in mandos-monitor

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*  -*- coding: utf-8 -*- */
 
1
/*  -*- coding: utf-8; mode: c; mode: orgtbl -*- */
2
2
/*
3
3
 * Mandos plugin runner - Run Mandos plugins
4
4
 *
5
 
 * Copyright © 2008 Teddy Hogeborn
6
 
 * Copyright © 2008 Björn Påhlsson
 
5
 * Copyright © 2008,2009 Teddy Hogeborn
 
6
 * Copyright © 2008,2009 Björn Påhlsson
7
7
 * 
8
8
 * This program is free software: you can redistribute it and/or
9
9
 * modify it under the terms of the GNU General Public License as
23
23
 */
24
24
 
25
25
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
26
 
                                   asprintf() */
 
26
                                   asprintf(), O_CLOEXEC */
27
27
#include <stddef.h>             /* size_t, NULL */
28
 
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
29
 
                                   EXIT_SUCCESS, realloc() */
 
28
#include <stdlib.h>             /* malloc(), exit(), EXIT_SUCCESS,
 
29
                                   realloc() */
30
30
#include <stdbool.h>            /* bool, true, false */
31
31
#include <stdio.h>              /* perror, fileno(), fprintf(),
32
32
                                   stderr, STDOUT_FILENO */
33
 
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
 
33
#include <sys/types.h>          /* DIR, fdopendir(), stat(), struct
34
34
                                   stat, waitpid(), WIFEXITED(),
35
35
                                   WEXITSTATUS(), wait(), pid_t,
36
36
                                   uid_t, gid_t, getuid(), getgid(),
38
38
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
39
39
                                   FD_SET(), FD_ISSET(), FD_CLR */
40
40
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
41
 
                                   WEXITSTATUS() */
 
41
                                   WEXITSTATUS(), WTERMSIG(),
 
42
                                   WCOREDUMP() */
42
43
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
43
44
#include <iso646.h>             /* and, or, not */
44
 
#include <dirent.h>             /* DIR, struct dirent, opendir(),
 
45
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
45
46
                                   readdir(), closedir(), dirfd() */
46
47
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
47
48
                                   fcntl(), setuid(), setgid(),
52
53
                                   close() */
53
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
54
55
                                   FD_CLOEXEC */
55
 
#include <string.h>             /* strsep, strlen(), asprintf() */
 
56
#include <string.h>             /* strsep, strlen(), asprintf(),
 
57
                                   strsignal(), strcmp(), strncmp() */
56
58
#include <errno.h>              /* errno */
57
59
#include <argp.h>               /* struct argp_option, struct
58
60
                                   argp_state, struct argp,
62
64
#include <signal.h>             /* struct sigaction, sigemptyset(),
63
65
                                   sigaddset(), sigaction(),
64
66
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
65
 
                                   SIG_UNBLOCK, kill() */
 
67
                                   SIG_UNBLOCK, kill(), sig_atomic_t
 
68
                                */
66
69
#include <errno.h>              /* errno, EBADF */
 
70
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
 
71
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_IOERR,
 
72
                                   EX_CONFIG, EX_UNAVAILABLE, EX_OK */
67
73
 
68
74
#define BUFFER_SIZE 256
69
75
 
80
86
  char **environ;
81
87
  int envc;
82
88
  bool disabled;
83
 
 
 
89
  
84
90
  /* Variables used for running processes*/
85
91
  pid_t pid;
86
92
  int fd;
88
94
  size_t buffer_size;
89
95
  size_t buffer_length;
90
96
  bool eof;
91
 
  volatile bool completed;
92
 
  volatile int status;
 
97
  volatile sig_atomic_t completed;
 
98
  int status;
93
99
  struct plugin *next;
94
100
} plugin;
95
101
 
98
104
/* Gets an existing plugin based on name,
99
105
   or if none is found, creates a new one */
100
106
static plugin *getplugin(char *name){
101
 
  /* Check for exiting plugin with that name */
102
 
  for (plugin *p = plugin_list; p != NULL; p = p->next){
103
 
    if ((p->name == name)
104
 
        or (p->name and name and (strcmp(p->name, name) == 0))){
 
107
  /* Check for existing plugin with that name */
 
108
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
109
    if((p->name == name)
 
110
       or (p->name and name and (strcmp(p->name, name) == 0))){
105
111
      return p;
106
112
    }
107
113
  }
108
114
  /* Create a new plugin */
109
 
  plugin *new_plugin = malloc(sizeof(plugin));
110
 
  if (new_plugin == NULL){
 
115
  plugin *new_plugin = NULL;
 
116
  do {
 
117
    new_plugin = malloc(sizeof(plugin));
 
118
  } while(new_plugin == NULL and errno == EINTR);
 
119
  if(new_plugin == NULL){
111
120
    return NULL;
112
121
  }
113
122
  char *copy_name = NULL;
114
123
  if(name != NULL){
115
 
    copy_name = strdup(name);
 
124
    do {
 
125
      copy_name = strdup(name);
 
126
    } while(copy_name == NULL and errno == EINTR);
116
127
    if(copy_name == NULL){
 
128
      int e = errno;
 
129
      free(new_plugin);
 
130
      errno = e;
117
131
      return NULL;
118
132
    }
119
133
  }
120
134
  
121
 
  *new_plugin = (plugin) { .name = copy_name,
122
 
                           .argc = 1,
123
 
                           .disabled = false,
124
 
                           .next = plugin_list };
 
135
  *new_plugin = (plugin){ .name = copy_name,
 
136
                          .argc = 1,
 
137
                          .disabled = false,
 
138
                          .next = plugin_list };
125
139
  
126
 
  new_plugin->argv = malloc(sizeof(char *) * 2);
127
 
  if (new_plugin->argv == NULL){
 
140
  do {
 
141
    new_plugin->argv = malloc(sizeof(char *) * 2);
 
142
  } while(new_plugin->argv == NULL and errno == EINTR);
 
143
  if(new_plugin->argv == NULL){
 
144
    int e = errno;
128
145
    free(copy_name);
129
146
    free(new_plugin);
 
147
    errno = e;
130
148
    return NULL;
131
149
  }
132
150
  new_plugin->argv[0] = copy_name;
133
151
  new_plugin->argv[1] = NULL;
134
152
  
135
 
  new_plugin->environ = malloc(sizeof(char *));
 
153
  do {
 
154
    new_plugin->environ = malloc(sizeof(char *));
 
155
  } while(new_plugin->environ == NULL and errno == EINTR);
136
156
  if(new_plugin->environ == NULL){
 
157
    int e = errno;
137
158
    free(copy_name);
138
159
    free(new_plugin->argv);
139
160
    free(new_plugin);
 
161
    errno = e;
140
162
    return NULL;
141
163
  }
142
164
  new_plugin->environ[0] = NULL;
150
172
static bool add_to_char_array(const char *new, char ***array,
151
173
                              int *len){
152
174
  /* Resize the pointed-to array to hold one more pointer */
153
 
  *array = realloc(*array, sizeof(char *)
154
 
                   * (size_t) ((*len) + 2));
 
175
  do {
 
176
    *array = realloc(*array, sizeof(char *)
 
177
                     * (size_t) ((*len) + 2));
 
178
  } while(*array == NULL and errno == EINTR);
155
179
  /* Malloc check */
156
180
  if(*array == NULL){
157
181
    return false;
158
182
  }
159
183
  /* Make a copy of the new string */
160
 
  char *copy = strdup(new);
 
184
  char *copy;
 
185
  do {
 
186
    copy = strdup(new);
 
187
  } while(copy == NULL and errno == EINTR);
161
188
  if(copy == NULL){
162
189
    return false;
163
190
  }
189
216
    if(strncmp(*e, def, namelen + 1) == 0){
190
217
      /* It already exists */
191
218
      if(replace){
192
 
        char *new = realloc(*e, strlen(def) + 1);
 
219
        char *new;
 
220
        do {
 
221
          new = realloc(*e, strlen(def) + 1);
 
222
        } while(new == NULL and errno == EINTR);
193
223
        if(new == NULL){
194
224
          return false;
195
225
        }
205
235
/*
206
236
 * Based on the example in the GNU LibC manual chapter 13.13 "File
207
237
 * Descriptor Flags".
208
 
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
 
238
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
209
239
 */
210
240
static int set_cloexec_flag(int fd){
211
 
  int ret = fcntl(fd, F_GETFD, 0);
 
241
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
212
242
  /* If reading the flags failed, return error indication now. */
213
243
  if(ret < 0){
214
244
    return ret;
215
245
  }
216
246
  /* Store modified flag word in the descriptor. */
217
 
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
 
247
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
 
248
                                       ret | FD_CLOEXEC));
218
249
}
219
250
 
220
251
 
221
252
/* Mark processes as completed when they exit, and save their exit
222
253
   status. */
223
254
static void handle_sigchld(__attribute__((unused)) int sig){
 
255
  int old_errno = errno;
224
256
  while(true){
225
257
    plugin *proc = plugin_list;
226
258
    int status;
230
262
      break;
231
263
    }
232
264
    if(pid == -1){
233
 
      if (errno != ECHILD){
234
 
        perror("waitpid");
 
265
      if(errno == ECHILD){
 
266
        /* No child processes */
 
267
        break;
235
268
      }
236
 
      /* No child processes */
237
 
      break;
 
269
      perror("waitpid");
238
270
    }
239
271
    
240
272
    /* A child exited, find it in process_list */
246
278
      continue;
247
279
    }
248
280
    proc->status = status;
249
 
    proc->completed = true;
 
281
    proc->completed = 1;
250
282
  }
 
283
  errno = old_errno;
251
284
}
252
285
 
253
286
/* Prints out a password to stdout */
275
308
  }
276
309
  free(plugin_node->environ);
277
310
  free(plugin_node->buffer);
278
 
 
 
311
  
279
312
  /* Removes the plugin from the singly-linked list */
280
313
  if(plugin_node == plugin_list){
281
314
    /* First one - simple */
309
342
  struct stat st;
310
343
  fd_set rfds_all;
311
344
  int ret, maxfd = 0;
 
345
  ssize_t sret;
312
346
  uid_t uid = 65534;
313
347
  gid_t gid = 65534;
314
348
  bool debug = false;
324
358
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
325
359
  if(ret == -1){
326
360
    perror("sigaddset");
327
 
    exitstatus = EXIT_FAILURE;
 
361
    exitstatus = EX_OSERR;
328
362
    goto fallback;
329
363
  }
330
364
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
331
365
  if(ret == -1){
332
366
    perror("sigaction");
333
 
    exitstatus = EXIT_FAILURE;
 
367
    exitstatus = EX_OSERR;
334
368
    goto fallback;
335
369
  }
336
370
  
368
402
      .doc = "Group ID the plugins will run as", .group = 3 },
369
403
    { .name = "debug", .key = 132,
370
404
      .doc = "Debug mode", .group = 4 },
 
405
    /*
 
406
     * These reproduce what we would get without ARGP_NO_HELP
 
407
     */
 
408
    { .name = "help", .key = '?',
 
409
      .doc = "Give this help list", .group = -1 },
 
410
    { .name = "usage", .key = -3,
 
411
      .doc = "Give a short usage message", .group = -1 },
 
412
    { .name = "version", .key = 'V',
 
413
      .doc = "Print program version", .group = -1 },
371
414
    { .name = NULL }
372
415
  };
373
416
  
374
 
  error_t parse_opt (int key, char *arg, __attribute__((unused))
375
 
                     struct argp_state *state) {
376
 
    switch (key) {
 
417
  error_t parse_opt(int key, char *arg, struct argp_state *state){
 
418
    errno = 0;
 
419
    switch(key){
 
420
      char *tmp;
 
421
      intmax_t tmpmax;
377
422
    case 'g':                   /* --global-options */
378
 
      if (arg != NULL){
379
 
        char *p;
380
 
        while((p = strsep(&arg, ",")) != NULL){
381
 
          if(p[0] == '\0'){
382
 
            continue;
383
 
          }
384
 
          if(not add_argument(getplugin(NULL), p)){
385
 
            perror("add_argument");
386
 
            return ARGP_ERR_UNKNOWN;
 
423
      {
 
424
        char *plugin_option;
 
425
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
426
          if(not add_argument(getplugin(NULL), plugin_option)){
 
427
            break;
387
428
          }
388
429
        }
389
430
      }
390
431
      break;
391
432
    case 'G':                   /* --global-env */
392
 
      if(arg == NULL){
393
 
        break;
394
 
      }
395
 
      if(not add_environment(getplugin(NULL), arg, true)){
396
 
        perror("add_environment");
397
 
      }
 
433
      add_environment(getplugin(NULL), arg, true);
398
434
      break;
399
435
    case 'o':                   /* --options-for */
400
 
      if (arg != NULL){
401
 
        char *p_name = strsep(&arg, ":");
402
 
        if(p_name[0] == '\0' or arg == NULL){
403
 
          break;
404
 
        }
405
 
        char *opt = strsep(&arg, ":");
406
 
        if(opt[0] == '\0' or opt == NULL){
407
 
          break;
408
 
        }
409
 
        char *p;
410
 
        while((p = strsep(&opt, ",")) != NULL){
411
 
          if(p[0] == '\0'){
412
 
            continue;
413
 
          }
414
 
          if(not add_argument(getplugin(p_name), p)){
415
 
            perror("add_argument");
416
 
            return ARGP_ERR_UNKNOWN;
 
436
      {
 
437
        char *option_list = strchr(arg, ':');
 
438
        if(option_list == NULL){
 
439
          argp_error(state, "No colon in \"%s\"", arg);
 
440
          errno = EINVAL;
 
441
          break;
 
442
        }
 
443
        *option_list = '\0';
 
444
        option_list++;
 
445
        if(arg[0] == '\0'){
 
446
          argp_error(state, "Empty plugin name");
 
447
          errno = EINVAL;
 
448
          break;
 
449
        }
 
450
        char *option;
 
451
        while((option = strsep(&option_list, ",")) != NULL){
 
452
          if(not add_argument(getplugin(arg), option)){
 
453
            break;
417
454
          }
418
455
        }
419
456
      }
420
457
      break;
421
458
    case 'E':                   /* --env-for */
422
 
      if(arg == NULL){
423
 
        break;
424
 
      }
425
459
      {
426
460
        char *envdef = strchr(arg, ':');
427
461
        if(envdef == NULL){
 
462
          argp_error(state, "No colon in \"%s\"", arg);
 
463
          errno = EINVAL;
428
464
          break;
429
465
        }
430
466
        *envdef = '\0';
431
 
        if(not add_environment(getplugin(arg), envdef+1, true)){
432
 
          perror("add_environment");
 
467
        envdef++;
 
468
        if(arg[0] == '\0'){
 
469
          argp_error(state, "Empty plugin name");
 
470
          errno = EINVAL;
 
471
          break;
433
472
        }
 
473
        add_environment(getplugin(arg), envdef, true);
434
474
      }
435
475
      break;
436
476
    case 'd':                   /* --disable */
437
 
      if (arg != NULL){
 
477
      {
438
478
        plugin *p = getplugin(arg);
439
 
        if(p == NULL){
440
 
          return ARGP_ERR_UNKNOWN;
 
479
        if(p != NULL){
 
480
          p->disabled = true;
441
481
        }
442
 
        p->disabled = true;
443
482
      }
444
483
      break;
445
484
    case 'e':                   /* --enable */
446
 
      if (arg != NULL){
 
485
      {
447
486
        plugin *p = getplugin(arg);
448
 
        if(p == NULL){
449
 
          return ARGP_ERR_UNKNOWN;
 
487
        if(p != NULL){
 
488
          p->disabled = false;
450
489
        }
451
 
        p->disabled = false;
452
490
      }
453
491
      break;
454
492
    case 128:                   /* --plugin-dir */
455
493
      free(plugindir);
456
494
      plugindir = strdup(arg);
457
 
      if(plugindir == NULL){
458
 
        perror("strdup");
459
 
      }      
460
495
      break;
461
496
    case 129:                   /* --config-file */
462
497
      /* This is already done by parse_opt_config_file() */
463
498
      break;
464
499
    case 130:                   /* --userid */
465
 
      uid = (uid_t)strtol(arg, NULL, 10);
 
500
      tmpmax = strtoimax(arg, &tmp, 10);
 
501
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
502
         or tmpmax != (uid_t)tmpmax){
 
503
        argp_error(state, "Bad user ID number: \"%s\", using %"
 
504
                   PRIdMAX, arg, (intmax_t)uid);
 
505
        break;
 
506
      }
 
507
      uid = (uid_t)tmpmax;
466
508
      break;
467
509
    case 131:                   /* --groupid */
468
 
      gid = (gid_t)strtol(arg, NULL, 10);
 
510
      tmpmax = strtoimax(arg, &tmp, 10);
 
511
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
512
         or tmpmax != (gid_t)tmpmax){
 
513
        argp_error(state, "Bad group ID number: \"%s\", using %"
 
514
                   PRIdMAX, arg, (intmax_t)gid);
 
515
        break;
 
516
      }
 
517
      gid = (gid_t)tmpmax;
469
518
      break;
470
519
    case 132:                   /* --debug */
471
520
      debug = true;
472
521
      break;
 
522
      /*
 
523
       * These reproduce what we would get without ARGP_NO_HELP
 
524
       */
 
525
    case '?':                   /* --help */
 
526
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
 
527
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
 
528
    case -3:                    /* --usage */
 
529
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
 
530
      argp_state_help(state, state->out_stream,
 
531
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
 
532
    case 'V':                   /* --version */
 
533
      fprintf(state->out_stream, "%s\n", argp_program_version);
 
534
      exit(EXIT_SUCCESS);
 
535
      break;
 
536
/*
 
537
 * When adding more options before this line, remember to also add a
 
538
 * "case" to the "parse_opt_config_file" function below.
 
539
 */
473
540
    case ARGP_KEY_ARG:
474
541
      /* Cryptsetup always passes an argument, which is an empty
475
542
         string if "none" was specified in /etc/crypttab.  So if
476
543
         argument was empty, we ignore it silently. */
477
 
      if(arg[0] != '\0'){
478
 
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
544
      if(arg[0] == '\0'){
 
545
        break;
479
546
      }
480
 
      break;
481
 
    case ARGP_KEY_END:
482
 
      break;
483
547
    default:
484
548
      return ARGP_ERR_UNKNOWN;
485
549
    }
486
 
    return 0;
 
550
    return errno;               /* Set to 0 at start */
487
551
  }
488
552
  
489
553
  /* This option parser is the same as parse_opt() above, except it
490
554
     ignores everything but the --config-file option. */
491
 
  error_t parse_opt_config_file (int key, char *arg,
492
 
                                 __attribute__((unused))
493
 
                                 struct argp_state *state) {
494
 
    switch (key) {
 
555
  error_t parse_opt_config_file(int key, char *arg,
 
556
                                __attribute__((unused))
 
557
                                struct argp_state *state){
 
558
    errno = 0;
 
559
    switch(key){
495
560
    case 'g':                   /* --global-options */
496
561
    case 'G':                   /* --global-env */
497
562
    case 'o':                   /* --options-for */
503
568
    case 129:                   /* --config-file */
504
569
      free(argfile);
505
570
      argfile = strdup(arg);
506
 
      if(argfile == NULL){
507
 
        perror("strdup");
508
 
      }
509
 
      break;      
 
571
      break;
510
572
    case 130:                   /* --userid */
511
573
    case 131:                   /* --groupid */
512
574
    case 132:                   /* --debug */
 
575
    case '?':                   /* --help */
 
576
    case -3:                    /* --usage */
 
577
    case 'V':                   /* --version */
513
578
    case ARGP_KEY_ARG:
514
 
    case ARGP_KEY_END:
515
579
      break;
516
580
    default:
517
581
      return ARGP_ERR_UNKNOWN;
518
582
    }
519
 
    return 0;
 
583
    return errno;
520
584
  }
521
585
  
522
586
  struct argp argp = { .options = options,
524
588
                       .args_doc = "",
525
589
                       .doc = "Mandos plugin runner -- Run plugins" };
526
590
  
527
 
  /* Parse using the parse_opt_config_file in order to get the custom
 
591
  /* Parse using parse_opt_config_file() in order to get the custom
528
592
     config file location, if any. */
529
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
530
 
  if (ret == ARGP_ERR_UNKNOWN){
531
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
532
 
    exitstatus = EXIT_FAILURE;
 
593
  ret = argp_parse(&argp, argc, argv,
 
594
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
595
                   NULL, NULL);
 
596
  switch(ret){
 
597
  case 0:
 
598
    break;
 
599
  case ENOMEM:
 
600
  default:
 
601
    errno = ret;
 
602
    perror("argp_parse");
 
603
    exitstatus = EX_OSERR;
 
604
    goto fallback;
 
605
  case EINVAL:
 
606
    exitstatus = EX_USAGE;
533
607
    goto fallback;
534
608
  }
535
609
  
537
611
  argp.parser = parse_opt;
538
612
  
539
613
  /* Open the configfile if available */
540
 
  if (argfile == NULL){
 
614
  if(argfile == NULL){
541
615
    conffp = fopen(AFILE, "r");
542
616
  } else {
543
617
    conffp = fopen(argfile, "r");
544
 
  }  
 
618
  }
545
619
  if(conffp != NULL){
546
620
    char *org_line = NULL;
547
621
    char *p, *arg, *new_arg, *line;
548
622
    size_t size = 0;
549
 
    ssize_t sret;
550
623
    const char whitespace_delims[] = " \r\t\f\v\n";
551
624
    const char comment_delim[] = "#";
552
 
 
 
625
    
553
626
    custom_argc = 1;
554
627
    custom_argv = malloc(sizeof(char*) * 2);
555
628
    if(custom_argv == NULL){
556
629
      perror("malloc");
557
 
      exitstatus = EXIT_FAILURE;
 
630
      exitstatus = EX_OSERR;
558
631
      goto fallback;
559
632
    }
560
633
    custom_argv[0] = argv[0];
561
634
    custom_argv[1] = NULL;
562
 
 
 
635
    
563
636
    /* for each line in the config file, strip whitespace and ignore
564
637
       commented text */
565
638
    while(true){
567
640
      if(sret == -1){
568
641
        break;
569
642
      }
570
 
 
 
643
      
571
644
      line = org_line;
572
645
      arg = strsep(&line, comment_delim);
573
646
      while((p = strsep(&arg, whitespace_delims)) != NULL){
577
650
        new_arg = strdup(p);
578
651
        if(new_arg == NULL){
579
652
          perror("strdup");
580
 
          exitstatus = EXIT_FAILURE;
 
653
          exitstatus = EX_OSERR;
581
654
          free(org_line);
582
655
          goto fallback;
583
656
        }
587
660
                              * ((unsigned int) custom_argc + 1));
588
661
        if(custom_argv == NULL){
589
662
          perror("realloc");
590
 
          exitstatus = EXIT_FAILURE;
 
663
          exitstatus = EX_OSERR;
591
664
          free(org_line);
592
665
          goto fallback;
593
666
        }
594
667
        custom_argv[custom_argc-1] = new_arg;
595
 
        custom_argv[custom_argc] = NULL;        
 
668
        custom_argv[custom_argc] = NULL;
596
669
      }
597
670
    }
 
671
    do {
 
672
      ret = fclose(conffp);
 
673
    } while(ret == EOF and errno == EINTR);
 
674
    if(ret == EOF){
 
675
      perror("fclose");
 
676
      exitstatus = EX_IOERR;
 
677
      goto fallback;
 
678
    }
598
679
    free(org_line);
599
680
  } else {
600
681
    /* Check for harmful errors and go to fallback. Other errors might
601
682
       not affect opening plugins */
602
 
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
683
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
603
684
      perror("fopen");
604
 
      exitstatus = EXIT_FAILURE;
 
685
      exitstatus = EX_OSERR;
605
686
      goto fallback;
606
687
    }
607
688
  }
608
 
  /* If there was any arguments from configuration file,
609
 
     pass them to parser as command arguments */
 
689
  /* If there were any arguments from the configuration file, pass
 
690
     them to parser as command line arguments */
610
691
  if(custom_argv != NULL){
611
 
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
612
 
                      0, NULL);
613
 
    if (ret == ARGP_ERR_UNKNOWN){
614
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
615
 
      exitstatus = EXIT_FAILURE;
 
692
    ret = argp_parse(&argp, custom_argc, custom_argv,
 
693
                     ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
694
                     NULL, NULL);
 
695
    switch(ret){
 
696
    case 0:
 
697
      break;
 
698
    case ENOMEM:
 
699
    default:
 
700
      errno = ret;
 
701
      perror("argp_parse");
 
702
      exitstatus = EX_OSERR;
 
703
      goto fallback;
 
704
    case EINVAL:
 
705
      exitstatus = EX_CONFIG;
616
706
      goto fallback;
617
707
    }
618
708
  }
619
709
  
620
710
  /* Parse actual command line arguments, to let them override the
621
711
     config file */
622
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
623
 
  if (ret == ARGP_ERR_UNKNOWN){
624
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
625
 
    exitstatus = EXIT_FAILURE;
 
712
  ret = argp_parse(&argp, argc, argv,
 
713
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
714
                   NULL, NULL);
 
715
  switch(ret){
 
716
  case 0:
 
717
    break;
 
718
  case ENOMEM:
 
719
  default:
 
720
    errno = ret;
 
721
    perror("argp_parse");
 
722
    exitstatus = EX_OSERR;
 
723
    goto fallback;
 
724
  case EINVAL:
 
725
    exitstatus = EX_USAGE;
626
726
    goto fallback;
627
727
  }
628
728
  
633
733
      for(char **a = p->argv; *a != NULL; a++){
634
734
        fprintf(stderr, "\tArg: %s\n", *a);
635
735
      }
636
 
      fprintf(stderr, "...and %u environment variables\n", p->envc);
 
736
      fprintf(stderr, "...and %d environment variables\n", p->envc);
637
737
      for(char **a = p->environ; *a != NULL; a++){
638
738
        fprintf(stderr, "\t%s\n", *a);
639
739
      }
641
741
  }
642
742
  
643
743
  /* Strip permissions down to nobody */
 
744
  setgid(gid);
 
745
  if(ret == -1){
 
746
    perror("setgid");
 
747
  }
644
748
  ret = setuid(uid);
645
 
  if (ret == -1){
 
749
  if(ret == -1){
646
750
    perror("setuid");
647
 
  }  
648
 
  setgid(gid);
649
 
  if (ret == -1){
650
 
    perror("setgid");
651
 
  }
652
 
  
653
 
  if (plugindir == NULL){
654
 
    dir = opendir(PDIR);
655
 
  } else {
656
 
    dir = opendir(plugindir);
657
 
  }
658
 
  
659
 
  if(dir == NULL){
660
 
    perror("Could not open plugin dir");
661
 
    exitstatus = EXIT_FAILURE;
662
 
    goto fallback;
663
 
  }
664
 
  
665
 
  /* Set the FD_CLOEXEC flag on the directory, if possible */
 
751
  }
 
752
  
 
753
  /* Open plugin directory with close_on_exec flag */
666
754
  {
667
 
    int dir_fd = dirfd(dir);
668
 
    if(dir_fd >= 0){
669
 
      ret = set_cloexec_flag(dir_fd);
670
 
      if(ret < 0){
671
 
        perror("set_cloexec_flag");
672
 
        exitstatus = EXIT_FAILURE;
673
 
        goto fallback;
674
 
      }
 
755
    int dir_fd = -1;
 
756
    if(plugindir == NULL){
 
757
      dir_fd = open(PDIR, O_RDONLY |
 
758
#ifdef O_CLOEXEC
 
759
                    O_CLOEXEC
 
760
#else  /* not O_CLOEXEC */
 
761
                    0
 
762
#endif  /* not O_CLOEXEC */
 
763
                    );
 
764
    } else {
 
765
      dir_fd = open(plugindir, O_RDONLY |
 
766
#ifdef O_CLOEXEC
 
767
                    O_CLOEXEC
 
768
#else  /* not O_CLOEXEC */
 
769
                    0
 
770
#endif  /* not O_CLOEXEC */
 
771
                    );
 
772
    }
 
773
    if(dir_fd == -1){
 
774
      perror("Could not open plugin dir");
 
775
      exitstatus = EX_UNAVAILABLE;
 
776
      goto fallback;
 
777
    }
 
778
    
 
779
#ifndef O_CLOEXEC
 
780
  /* Set the FD_CLOEXEC flag on the directory */
 
781
    ret = set_cloexec_flag(dir_fd);
 
782
    if(ret < 0){
 
783
      perror("set_cloexec_flag");
 
784
      TEMP_FAILURE_RETRY(close(dir_fd));
 
785
      exitstatus = EX_OSERR;
 
786
      goto fallback;
 
787
    }
 
788
#endif  /* O_CLOEXEC */
 
789
    
 
790
    dir = fdopendir(dir_fd);
 
791
    if(dir == NULL){
 
792
      perror("Could not open plugin dir");
 
793
      TEMP_FAILURE_RETRY(close(dir_fd));
 
794
      exitstatus = EX_OSERR;
 
795
      goto fallback;
675
796
    }
676
797
  }
677
798
  
679
800
  
680
801
  /* Read and execute any executable in the plugin directory*/
681
802
  while(true){
682
 
    dirst = readdir(dir);
 
803
    do {
 
804
      dirst = readdir(dir);
 
805
    } while(dirst == NULL and errno == EINTR);
683
806
    
684
807
    /* All directory entries have been processed */
685
808
    if(dirst == NULL){
686
 
      if (errno == EBADF){
 
809
      if(errno == EBADF){
687
810
        perror("readdir");
688
 
        exitstatus = EXIT_FAILURE;
 
811
        exitstatus = EX_IOERR;
689
812
        goto fallback;
690
813
      }
691
814
      break;
721
844
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
722
845
        size_t suf_len = strlen(*suf);
723
846
        if((d_name_len >= suf_len)
724
 
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
 
847
           and (strcmp((dirst->d_name) + d_name_len-suf_len, *suf)
725
848
                == 0)){
726
849
          if(debug){
727
850
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
736
859
        continue;
737
860
      }
738
861
    }
739
 
 
 
862
    
740
863
    char *filename;
741
864
    if(plugindir == NULL){
742
 
      ret = asprintf(&filename, PDIR "/%s", dirst->d_name);
 
865
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
 
866
                                             dirst->d_name));
743
867
    } else {
744
 
      ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
868
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s",
 
869
                                             plugindir,
 
870
                                             dirst->d_name));
745
871
    }
746
872
    if(ret < 0){
747
873
      perror("asprintf");
748
874
      continue;
749
875
    }
750
876
    
751
 
    ret = stat(filename, &st);
752
 
    if (ret == -1){
 
877
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
 
878
    if(ret == -1){
753
879
      perror("stat");
754
880
      free(filename);
755
881
      continue;
756
882
    }
757
 
 
 
883
    
758
884
    /* Ignore non-executable files */
759
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
 
885
    if(not S_ISREG(st.st_mode)
 
886
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
760
887
      if(debug){
761
888
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
762
889
                " with bad type or mode\n", filename);
808
935
    }
809
936
    
810
937
    int pipefd[2];
811
 
    ret = pipe(pipefd);
812
 
    if (ret == -1){
 
938
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
 
939
    if(ret == -1){
813
940
      perror("pipe");
814
 
      exitstatus = EXIT_FAILURE;
 
941
      exitstatus = EX_OSERR;
815
942
      goto fallback;
816
943
    }
817
944
    /* Ask OS to automatic close the pipe on exec */
818
945
    ret = set_cloexec_flag(pipefd[0]);
819
946
    if(ret < 0){
820
947
      perror("set_cloexec_flag");
821
 
      exitstatus = EXIT_FAILURE;
 
948
      exitstatus = EX_OSERR;
822
949
      goto fallback;
823
950
    }
824
951
    ret = set_cloexec_flag(pipefd[1]);
825
952
    if(ret < 0){
826
953
      perror("set_cloexec_flag");
827
 
      exitstatus = EXIT_FAILURE;
 
954
      exitstatus = EX_OSERR;
828
955
      goto fallback;
829
956
    }
830
957
    /* Block SIGCHLD until process is safely in process list */
831
 
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
958
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
 
959
                                              &sigchld_action.sa_mask,
 
960
                                              NULL));
832
961
    if(ret < 0){
833
962
      perror("sigprocmask");
834
 
      exitstatus = EXIT_FAILURE;
 
963
      exitstatus = EX_OSERR;
835
964
      goto fallback;
836
965
    }
837
966
    /* Starting a new process to be watched */
838
 
    pid_t pid = fork();
 
967
    pid_t pid;
 
968
    do {
 
969
      pid = fork();
 
970
    } while(pid == -1 and errno == EINTR);
839
971
    if(pid == -1){
840
972
      perror("fork");
841
 
      exitstatus = EXIT_FAILURE;
 
973
      exitstatus = EX_OSERR;
842
974
      goto fallback;
843
975
    }
844
976
    if(pid == 0){
846
978
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
847
979
      if(ret < 0){
848
980
        perror("sigaction");
849
 
        _exit(EXIT_FAILURE);
 
981
        _exit(EX_OSERR);
850
982
      }
851
983
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
852
984
      if(ret < 0){
853
985
        perror("sigprocmask");
854
 
        _exit(EXIT_FAILURE);
 
986
        _exit(EX_OSERR);
855
987
      }
856
988
      
857
989
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
858
990
      if(ret == -1){
859
991
        perror("dup2");
860
 
        _exit(EXIT_FAILURE);
 
992
        _exit(EX_OSERR);
861
993
      }
862
994
      
863
995
      if(dirfd(dir) < 0){
868
1000
      if(p->environ[0] == NULL){
869
1001
        if(execv(filename, p->argv) < 0){
870
1002
          perror("execv");
871
 
          _exit(EXIT_FAILURE);
 
1003
          _exit(EX_OSERR);
872
1004
        }
873
1005
      } else {
874
1006
        if(execve(filename, p->argv, p->environ) < 0){
875
1007
          perror("execve");
876
 
          _exit(EXIT_FAILURE);
 
1008
          _exit(EX_OSERR);
877
1009
        }
878
1010
      }
879
1011
      /* no return */
880
1012
    }
881
1013
    /* Parent process */
882
 
    close(pipefd[1]);           /* Close unused write end of pipe */
 
1014
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
 
1015
                                             pipe */
883
1016
    free(filename);
884
1017
    plugin *new_plugin = getplugin(dirst->d_name);
885
 
    if (new_plugin == NULL){
 
1018
    if(new_plugin == NULL){
886
1019
      perror("getplugin");
887
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1020
      ret = (int)(TEMP_FAILURE_RETRY
 
1021
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
 
1022
                               NULL)));
888
1023
      if(ret < 0){
889
1024
        perror("sigprocmask");
890
1025
      }
891
 
      exitstatus = EXIT_FAILURE;
 
1026
      exitstatus = EX_OSERR;
892
1027
      goto fallback;
893
1028
    }
894
1029
    
897
1032
    
898
1033
    /* Unblock SIGCHLD so signal handler can be run if this process
899
1034
       has already completed */
900
 
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1035
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
 
1036
                                              &sigchld_action.sa_mask,
 
1037
                                              NULL));
901
1038
    if(ret < 0){
902
1039
      perror("sigprocmask");
903
 
      exitstatus = EXIT_FAILURE;
 
1040
      exitstatus = EX_OSERR;
904
1041
      goto fallback;
905
1042
    }
906
1043
    
907
 
    FD_SET(new_plugin->fd, &rfds_all);
 
1044
    FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from
 
1045
                                          -Wconversion */
908
1046
    
909
 
    if (maxfd < new_plugin->fd){
 
1047
    if(maxfd < new_plugin->fd){
910
1048
      maxfd = new_plugin->fd;
911
1049
    }
912
1050
  }
913
1051
  
914
 
  closedir(dir);
 
1052
  TEMP_FAILURE_RETRY(closedir(dir));
915
1053
  dir = NULL;
 
1054
  free_plugin(getplugin(NULL));
916
1055
  
917
1056
  for(plugin *p = plugin_list; p != NULL; p = p->next){
918
1057
    if(p->pid != 0){
929
1068
  while(plugin_list){
930
1069
    fd_set rfds = rfds_all;
931
1070
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
932
 
    if (select_ret == -1){
 
1071
    if(select_ret == -1 and errno != EINTR){
933
1072
      perror("select");
934
 
      exitstatus = EXIT_FAILURE;
 
1073
      exitstatus = EX_OSERR;
935
1074
      goto fallback;
936
1075
    }
937
1076
    /* OK, now either a process completed, or something can be read
938
1077
       from one of them */
939
1078
    for(plugin *proc = plugin_list; proc != NULL;){
940
1079
      /* Is this process completely done? */
941
 
      if(proc->eof and proc->completed){
 
1080
      if(proc->completed and proc->eof){
942
1081
        /* Only accept the plugin output if it exited cleanly */
943
1082
        if(not WIFEXITED(proc->status)
944
1083
           or WEXITSTATUS(proc->status) != 0){
945
1084
          /* Bad exit by plugin */
946
 
 
 
1085
          
947
1086
          if(debug){
948
1087
            if(WIFEXITED(proc->status)){
949
 
              fprintf(stderr, "Plugin %u exited with status %d\n",
950
 
                      (unsigned int) (proc->pid),
 
1088
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] exited with"
 
1089
                      " status %d\n", proc->name,
 
1090
                      (intmax_t) (proc->pid),
951
1091
                      WEXITSTATUS(proc->status));
952
 
            } else if(WIFSIGNALED(proc->status)) {
953
 
              fprintf(stderr, "Plugin %u killed by signal %d\n",
954
 
                      (unsigned int) (proc->pid),
955
 
                      WTERMSIG(proc->status));
 
1092
            } else if(WIFSIGNALED(proc->status)){
 
1093
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] killed by"
 
1094
                      " signal %d: %s\n", proc->name,
 
1095
                      (intmax_t) (proc->pid),
 
1096
                      WTERMSIG(proc->status),
 
1097
                      strsignal(WTERMSIG(proc->status)));
956
1098
            } else if(WCOREDUMP(proc->status)){
957
 
              fprintf(stderr, "Plugin %d dumped core\n",
958
 
                      (unsigned int) (proc->pid));
 
1099
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
1100
                      " core\n", proc->name, (intmax_t) (proc->pid));
959
1101
            }
960
1102
          }
961
1103
          
962
1104
          /* Remove the plugin */
963
 
          FD_CLR(proc->fd, &rfds_all);
964
 
 
 
1105
          FD_CLR(proc->fd, &rfds_all); /* Spurious warning from
 
1106
                                          -Wconversion */
 
1107
          
965
1108
          /* Block signal while modifying process_list */
966
 
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
1109
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
 
1110
                                        (SIG_BLOCK,
 
1111
                                         &sigchld_action.sa_mask,
 
1112
                                         NULL));
967
1113
          if(ret < 0){
968
1114
            perror("sigprocmask");
969
 
            exitstatus = EXIT_FAILURE;
 
1115
            exitstatus = EX_OSERR;
970
1116
            goto fallback;
971
1117
          }
972
1118
          
975
1121
          proc = next_plugin;
976
1122
          
977
1123
          /* We are done modifying process list, so unblock signal */
978
 
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
979
 
                             NULL);
 
1124
          ret = (int)(TEMP_FAILURE_RETRY
 
1125
                      (sigprocmask(SIG_UNBLOCK,
 
1126
                                   &sigchld_action.sa_mask, NULL)));
980
1127
          if(ret < 0){
981
1128
            perror("sigprocmask");
982
 
            exitstatus = EXIT_FAILURE;
 
1129
            exitstatus = EX_OSERR;
983
1130
            goto fallback;
984
1131
          }
985
1132
          
996
1143
                                       proc->buffer_length);
997
1144
        if(not bret){
998
1145
          perror("print_out_password");
999
 
          exitstatus = EXIT_FAILURE;
 
1146
          exitstatus = EX_IOERR;
1000
1147
        }
1001
1148
        goto fallback;
1002
1149
      }
1003
1150
      
1004
1151
      /* This process has not completed.  Does it have any output? */
1005
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
 
1152
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious
 
1153
                                                         warning from
 
1154
                                                         -Wconversion */
1006
1155
        /* This process had nothing to say at this time */
1007
1156
        proc = proc->next;
1008
1157
        continue;
1011
1160
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1012
1161
        proc->buffer = realloc(proc->buffer, proc->buffer_size
1013
1162
                               + (size_t) BUFFER_SIZE);
1014
 
        if (proc->buffer == NULL){
 
1163
        if(proc->buffer == NULL){
1015
1164
          perror("malloc");
1016
 
          exitstatus = EXIT_FAILURE;
 
1165
          exitstatus = EX_OSERR;
1017
1166
          goto fallback;
1018
1167
        }
1019
1168
        proc->buffer_size += BUFFER_SIZE;
1020
1169
      }
1021
1170
      /* Read from the process */
1022
 
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
1023
 
                 BUFFER_SIZE);
1024
 
      if(ret < 0){
 
1171
      sret = TEMP_FAILURE_RETRY(read(proc->fd,
 
1172
                                     proc->buffer
 
1173
                                     + proc->buffer_length,
 
1174
                                     BUFFER_SIZE));
 
1175
      if(sret < 0){
1025
1176
        /* Read error from this process; ignore the error */
1026
1177
        proc = proc->next;
1027
1178
        continue;
1028
1179
      }
1029
 
      if(ret == 0){
 
1180
      if(sret == 0){
1030
1181
        /* got EOF */
1031
1182
        proc->eof = true;
1032
1183
      } else {
1033
 
        proc->buffer_length += (size_t) ret;
 
1184
        proc->buffer_length += (size_t) sret;
1034
1185
      }
1035
1186
    }
1036
1187
  }
1037
 
 
1038
 
 
 
1188
  
 
1189
  
1039
1190
 fallback:
1040
1191
  
1041
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
1192
  if(plugin_list == NULL or (exitstatus != EXIT_SUCCESS
 
1193
                             and exitstatus != EX_OK)){
1042
1194
    /* Fallback if all plugins failed, none are found or an error
1043
1195
       occured */
1044
1196
    bool bret;
1053
1205
    bret = print_out_password(passwordbuffer, len);
1054
1206
    if(not bret){
1055
1207
      perror("print_out_password");
1056
 
      exitstatus = EXIT_FAILURE;
 
1208
      exitstatus = EX_IOERR;
1057
1209
    }
1058
1210
  }
1059
1211
  
1061
1213
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1062
1214
  if(ret == -1){
1063
1215
    perror("sigaction");
1064
 
    exitstatus = EXIT_FAILURE;
 
1216
    exitstatus = EX_OSERR;
1065
1217
  }
1066
1218
  
1067
1219
  if(custom_argv != NULL){
1088
1240
  }
1089
1241
  
1090
1242
  /* Wait for any remaining child processes to terminate */
1091
 
  do{
 
1243
  do {
1092
1244
    ret = wait(NULL);
1093
1245
  } while(ret >= 0);
1094
1246
  if(errno != ECHILD){