/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2014-03-23 20:48:58 UTC
  • Revision ID: teddy@recompile.se-20140323204858-l1x3aiick21oog4y
Improve error message when working around Debian bug #633582.

* plugins-runner.c (main): Improve error message when failing to work
                           around Debian bug #633582.  Also simplify
                           code to always use execve().

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
/*
3
3
 * Mandos plugin runner - Run Mandos plugins
4
4
 *
5
 
 * Copyright © 2008,2009 Teddy Hogeborn
6
 
 * Copyright © 2008,2009 Björn Påhlsson
 
5
 * Copyright © 2008-2013 Teddy Hogeborn
 
6
 * Copyright © 2008-2013 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
19
19
 * along with this program.  If not, see
20
20
 * <http://www.gnu.org/licenses/>.
21
21
 * 
22
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
22
 * Contact the authors at <mandos@recompile.se>.
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
 
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
31
#include <stdio.h>              /* 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(),
42
42
                                   WCOREDUMP() */
43
43
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
44
44
#include <iso646.h>             /* and, or, not */
45
 
#include <dirent.h>             /* DIR, struct dirent, opendir(),
 
45
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
46
46
                                   readdir(), closedir(), dirfd() */
47
47
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
48
48
                                   fcntl(), setuid(), setgid(),
49
49
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
50
50
                                   access(), pipe(), fork(), close()
51
51
                                   dup2(), STDOUT_FILENO, _exit(),
52
 
                                   execv(), write(), read(),
 
52
                                   execve(), write(), read(),
53
53
                                   close() */
54
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
55
55
                                   FD_CLOEXEC */
56
56
#include <string.h>             /* strsep, strlen(), asprintf(),
57
 
                                   strsignal() */
 
57
                                   strsignal(), strcmp(), strncmp() */
58
58
#include <errno.h>              /* errno */
59
59
#include <argp.h>               /* struct argp_option, struct
60
60
                                   argp_state, struct argp,
68
68
                                */
69
69
#include <errno.h>              /* errno, EBADF */
70
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 */
 
73
#include <errno.h>              /* errno */
 
74
#include <error.h>              /* error() */
71
75
 
72
76
#define BUFFER_SIZE 256
73
77
 
75
79
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
76
80
 
77
81
const char *argp_program_version = "plugin-runner " VERSION;
78
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
82
const char *argp_program_bug_address = "<mandos@recompile.se>";
79
83
 
80
84
typedef struct plugin{
81
85
  char *name;                   /* can be NULL or any plugin name */
101
105
 
102
106
/* Gets an existing plugin based on name,
103
107
   or if none is found, creates a new one */
 
108
__attribute__((warn_unused_result))
104
109
static plugin *getplugin(char *name){
105
 
  /* Check for exiting plugin with that name */
 
110
  /* Check for existing plugin with that name */
106
111
  for(plugin *p = plugin_list; p != NULL; p = p->next){
107
112
    if((p->name == name)
108
113
       or (p->name and name and (strcmp(p->name, name) == 0))){
123
128
      copy_name = strdup(name);
124
129
    } while(copy_name == NULL and errno == EINTR);
125
130
    if(copy_name == NULL){
 
131
      int e = errno;
126
132
      free(new_plugin);
 
133
      errno = e;
127
134
      return NULL;
128
135
    }
129
136
  }
137
144
    new_plugin->argv = malloc(sizeof(char *) * 2);
138
145
  } while(new_plugin->argv == NULL and errno == EINTR);
139
146
  if(new_plugin->argv == NULL){
 
147
    int e = errno;
140
148
    free(copy_name);
141
149
    free(new_plugin);
 
150
    errno = e;
142
151
    return NULL;
143
152
  }
144
153
  new_plugin->argv[0] = copy_name;
148
157
    new_plugin->environ = malloc(sizeof(char *));
149
158
  } while(new_plugin->environ == NULL and errno == EINTR);
150
159
  if(new_plugin->environ == NULL){
 
160
    int e = errno;
151
161
    free(copy_name);
152
162
    free(new_plugin->argv);
153
163
    free(new_plugin);
 
164
    errno = e;
154
165
    return NULL;
155
166
  }
156
167
  new_plugin->environ[0] = NULL;
161
172
}
162
173
 
163
174
/* Helper function for add_argument and add_environment */
 
175
__attribute__((nonnull, warn_unused_result))
164
176
static bool add_to_char_array(const char *new, char ***array,
165
177
                              int *len){
166
178
  /* Resize the pointed-to array to hold one more pointer */
 
179
  char **new_array = NULL;
167
180
  do {
168
 
    *array = realloc(*array, sizeof(char *)
169
 
                     * (size_t) ((*len) + 2));
170
 
  } while(*array == NULL and errno == EINTR);
 
181
    new_array = realloc(*array, sizeof(char *)
 
182
                        * (size_t) ((*len) + 2));
 
183
  } while(new_array == NULL and errno == EINTR);
171
184
  /* Malloc check */
172
 
  if(*array == NULL){
 
185
  if(new_array == NULL){
173
186
    return false;
174
187
  }
 
188
  *array = new_array;
175
189
  /* Make a copy of the new string */
176
190
  char *copy;
177
191
  do {
189
203
}
190
204
 
191
205
/* Add to a plugin's argument vector */
 
206
__attribute__((nonnull(2), warn_unused_result))
192
207
static bool add_argument(plugin *p, const char *arg){
193
208
  if(p == NULL){
194
209
    return false;
197
212
}
198
213
 
199
214
/* Add to a plugin's environment */
 
215
__attribute__((nonnull(2), warn_unused_result))
200
216
static bool add_environment(plugin *p, const char *def, bool replace){
201
217
  if(p == NULL){
202
218
    return false;
204
220
  /* namelen = length of name of environment variable */
205
221
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
206
222
  /* Search for this environment variable */
207
 
  for(char **e = p->environ; *e != NULL; e++){
208
 
    if(strncmp(*e, def, namelen + 1) == 0){
 
223
  for(char **envdef = p->environ; *envdef != NULL; envdef++){
 
224
    if(strncmp(*envdef, def, namelen + 1) == 0){
209
225
      /* It already exists */
210
226
      if(replace){
211
 
        char *new;
 
227
        char *new_envdef;
212
228
        do {
213
 
          new = realloc(*e, strlen(def) + 1);
214
 
        } while(new == NULL and errno == EINTR);
215
 
        if(new == NULL){
 
229
          new_envdef = realloc(*envdef, strlen(def) + 1);
 
230
        } while(new_envdef == NULL and errno == EINTR);
 
231
        if(new_envdef == NULL){
216
232
          return false;
217
233
        }
218
 
        *e = new;
219
 
        strcpy(*e, def);
 
234
        *envdef = new_envdef;
 
235
        strcpy(*envdef, def);
220
236
      }
221
237
      return true;
222
238
    }
229
245
 * Descriptor Flags".
230
246
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
231
247
 */
 
248
__attribute__((warn_unused_result))
232
249
static int set_cloexec_flag(int fd){
233
250
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
234
251
  /* If reading the flags failed, return error indication now. */
258
275
        /* No child processes */
259
276
        break;
260
277
      }
261
 
      perror("waitpid");
 
278
      error(0, errno, "waitpid");
262
279
    }
263
280
    
264
281
    /* A child exited, find it in process_list */
276
293
}
277
294
 
278
295
/* Prints out a password to stdout */
 
296
__attribute__((nonnull, warn_unused_result))
279
297
static bool print_out_password(const char *buffer, size_t length){
280
298
  ssize_t ret;
281
299
  for(size_t written = 0; written < length; written += (size_t)ret){
289
307
}
290
308
 
291
309
/* Removes and free a plugin from the plugin list */
 
310
__attribute__((nonnull))
292
311
static void free_plugin(plugin *plugin_node){
293
312
  
294
313
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
349
368
  sigemptyset(&sigchld_action.sa_mask);
350
369
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
351
370
  if(ret == -1){
352
 
    perror("sigaddset");
353
 
    exitstatus = EXIT_FAILURE;
 
371
    error(0, errno, "sigaddset");
 
372
    exitstatus = EX_OSERR;
354
373
    goto fallback;
355
374
  }
356
375
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
357
376
  if(ret == -1){
358
 
    perror("sigaction");
359
 
    exitstatus = EXIT_FAILURE;
 
377
    error(0, errno, "sigaction");
 
378
    exitstatus = EX_OSERR;
360
379
    goto fallback;
361
380
  }
362
381
  
394
413
      .doc = "Group ID the plugins will run as", .group = 3 },
395
414
    { .name = "debug", .key = 132,
396
415
      .doc = "Debug mode", .group = 4 },
 
416
    /*
 
417
     * These reproduce what we would get without ARGP_NO_HELP
 
418
     */
 
419
    { .name = "help", .key = '?',
 
420
      .doc = "Give this help list", .group = -1 },
 
421
    { .name = "usage", .key = -3,
 
422
      .doc = "Give a short usage message", .group = -1 },
 
423
    { .name = "version", .key = 'V',
 
424
      .doc = "Print program version", .group = -1 },
397
425
    { .name = NULL }
398
426
  };
399
427
  
400
 
  error_t parse_opt(int key, char *arg, __attribute__((unused))
401
 
                    struct argp_state *state){
 
428
  __attribute__((nonnull(3)))
 
429
  error_t parse_opt(int key, char *arg, struct argp_state *state){
 
430
    errno = 0;
402
431
    switch(key){
403
432
      char *tmp;
404
 
      intmax_t tmpmax;
 
433
      intmax_t tmp_id;
405
434
    case 'g':                   /* --global-options */
406
 
      if(arg != NULL){
 
435
      {
407
436
        char *plugin_option;
408
437
        while((plugin_option = strsep(&arg, ",")) != NULL){
409
 
          if(plugin_option[0] == '\0'){
410
 
            continue;
411
 
          }
412
438
          if(not add_argument(getplugin(NULL), plugin_option)){
413
 
            perror("add_argument");
414
 
            return ARGP_ERR_UNKNOWN;
 
439
            break;
415
440
          }
416
441
        }
 
442
        errno = 0;
417
443
      }
418
444
      break;
419
445
    case 'G':                   /* --global-env */
420
 
      if(arg == NULL){
421
 
        break;
422
 
      }
423
 
      if(not add_environment(getplugin(NULL), arg, true)){
424
 
        perror("add_environment");
 
446
      if(add_environment(getplugin(NULL), arg, true)){
 
447
        errno = 0;
425
448
      }
426
449
      break;
427
450
    case 'o':                   /* --options-for */
428
 
      if(arg != NULL){
429
 
        char *plugin_name = strsep(&arg, ":");
430
 
        if(plugin_name[0] == '\0'){
431
 
          break;
432
 
        }
433
 
        char *plugin_option;
434
 
        while((plugin_option = strsep(&arg, ",")) != NULL){
435
 
          if(not add_argument(getplugin(plugin_name), plugin_option)){
436
 
            perror("add_argument");
437
 
            return ARGP_ERR_UNKNOWN;
 
451
      {
 
452
        char *option_list = strchr(arg, ':');
 
453
        if(option_list == NULL){
 
454
          argp_error(state, "No colon in \"%s\"", arg);
 
455
          errno = EINVAL;
 
456
          break;
 
457
        }
 
458
        *option_list = '\0';
 
459
        option_list++;
 
460
        if(arg[0] == '\0'){
 
461
          argp_error(state, "Empty plugin name");
 
462
          errno = EINVAL;
 
463
          break;
 
464
        }
 
465
        char *option;
 
466
        while((option = strsep(&option_list, ",")) != NULL){
 
467
          if(not add_argument(getplugin(arg), option)){
 
468
            break;
438
469
          }
439
470
        }
 
471
        errno = 0;
440
472
      }
441
473
      break;
442
474
    case 'E':                   /* --env-for */
443
 
      if(arg == NULL){
444
 
        break;
445
 
      }
446
475
      {
447
476
        char *envdef = strchr(arg, ':');
448
477
        if(envdef == NULL){
 
478
          argp_error(state, "No colon in \"%s\"", arg);
 
479
          errno = EINVAL;
449
480
          break;
450
481
        }
451
482
        *envdef = '\0';
452
 
        if(not add_environment(getplugin(arg), envdef+1, true)){
453
 
          perror("add_environment");
 
483
        envdef++;
 
484
        if(arg[0] == '\0'){
 
485
          argp_error(state, "Empty plugin name");
 
486
          errno = EINVAL;
 
487
          break;
 
488
        }
 
489
        if(add_environment(getplugin(arg), envdef, true)){
 
490
          errno = 0;
454
491
        }
455
492
      }
456
493
      break;
457
494
    case 'd':                   /* --disable */
458
 
      if(arg != NULL){
 
495
      {
459
496
        plugin *p = getplugin(arg);
460
 
        if(p == NULL){
461
 
          return ARGP_ERR_UNKNOWN;
 
497
        if(p != NULL){
 
498
          p->disabled = true;
 
499
          errno = 0;
462
500
        }
463
 
        p->disabled = true;
464
501
      }
465
502
      break;
466
503
    case 'e':                   /* --enable */
467
 
      if(arg != NULL){
 
504
      {
468
505
        plugin *p = getplugin(arg);
469
 
        if(p == NULL){
470
 
          return ARGP_ERR_UNKNOWN;
 
506
        if(p != NULL){
 
507
          p->disabled = false;
 
508
          errno = 0;
471
509
        }
472
 
        p->disabled = false;
473
510
      }
474
511
      break;
475
512
    case 128:                   /* --plugin-dir */
476
513
      free(plugindir);
477
514
      plugindir = strdup(arg);
478
 
      if(plugindir == NULL){
479
 
        perror("strdup");
 
515
      if(plugindir != NULL){
 
516
        errno = 0;
480
517
      }
481
518
      break;
482
519
    case 129:                   /* --config-file */
483
520
      /* This is already done by parse_opt_config_file() */
484
521
      break;
485
522
    case 130:                   /* --userid */
486
 
      errno = 0;
487
 
      tmpmax = strtoimax(arg, &tmp, 10);
 
523
      tmp_id = strtoimax(arg, &tmp, 10);
488
524
      if(errno != 0 or tmp == arg or *tmp != '\0'
489
 
         or tmpmax != (uid_t)tmpmax){
490
 
        fprintf(stderr, "Bad user ID number: \"%s\", using %"
491
 
                PRIdMAX "\n", arg, (intmax_t)uid);
492
 
      } else {
493
 
        uid = (uid_t)tmpmax;
 
525
         or tmp_id != (uid_t)tmp_id){
 
526
        argp_error(state, "Bad user ID number: \"%s\", using %"
 
527
                   PRIdMAX, arg, (intmax_t)uid);
 
528
        break;
494
529
      }
 
530
      uid = (uid_t)tmp_id;
 
531
      errno = 0;
495
532
      break;
496
533
    case 131:                   /* --groupid */
497
 
      errno = 0;
498
 
      tmpmax = strtoimax(arg, &tmp, 10);
 
534
      tmp_id = strtoimax(arg, &tmp, 10);
499
535
      if(errno != 0 or tmp == arg or *tmp != '\0'
500
 
         or tmpmax != (gid_t)tmpmax){
501
 
        fprintf(stderr, "Bad group ID number: \"%s\", using %"
502
 
                PRIdMAX "\n", arg, (intmax_t)gid);
503
 
      } else {
504
 
        gid = (gid_t)tmpmax;
 
536
         or tmp_id != (gid_t)tmp_id){
 
537
        argp_error(state, "Bad group ID number: \"%s\", using %"
 
538
                   PRIdMAX, arg, (intmax_t)gid);
 
539
        break;
505
540
      }
 
541
      gid = (gid_t)tmp_id;
 
542
      errno = 0;
506
543
      break;
507
544
    case 132:                   /* --debug */
508
545
      debug = true;
509
546
      break;
 
547
      /*
 
548
       * These reproduce what we would get without ARGP_NO_HELP
 
549
       */
 
550
    case '?':                   /* --help */
 
551
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
 
552
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
 
553
    case -3:                    /* --usage */
 
554
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
 
555
      argp_state_help(state, state->out_stream,
 
556
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
 
557
    case 'V':                   /* --version */
 
558
      fprintf(state->out_stream, "%s\n", argp_program_version);
 
559
      exit(EXIT_SUCCESS);
 
560
      break;
510
561
/*
511
562
 * When adding more options before this line, remember to also add a
512
563
 * "case" to the "parse_opt_config_file" function below.
515
566
      /* Cryptsetup always passes an argument, which is an empty
516
567
         string if "none" was specified in /etc/crypttab.  So if
517
568
         argument was empty, we ignore it silently. */
518
 
      if(arg[0] != '\0'){
519
 
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
569
      if(arg[0] == '\0'){
 
570
        break;
520
571
      }
521
 
      break;
522
 
    case ARGP_KEY_END:
523
 
      break;
524
572
    default:
525
573
      return ARGP_ERR_UNKNOWN;
526
574
    }
527
 
    return 0;
 
575
    return errno;               /* Set to 0 at start */
528
576
  }
529
577
  
530
578
  /* This option parser is the same as parse_opt() above, except it
532
580
  error_t parse_opt_config_file(int key, char *arg,
533
581
                                __attribute__((unused))
534
582
                                struct argp_state *state){
 
583
    errno = 0;
535
584
    switch(key){
536
585
    case 'g':                   /* --global-options */
537
586
    case 'G':                   /* --global-env */
544
593
    case 129:                   /* --config-file */
545
594
      free(argfile);
546
595
      argfile = strdup(arg);
547
 
      if(argfile == NULL){
548
 
        perror("strdup");
 
596
      if(argfile != NULL){
 
597
        errno = 0;
549
598
      }
550
599
      break;
551
600
    case 130:                   /* --userid */
552
601
    case 131:                   /* --groupid */
553
602
    case 132:                   /* --debug */
 
603
    case '?':                   /* --help */
 
604
    case -3:                    /* --usage */
 
605
    case 'V':                   /* --version */
554
606
    case ARGP_KEY_ARG:
555
 
    case ARGP_KEY_END:
556
607
      break;
557
608
    default:
558
609
      return ARGP_ERR_UNKNOWN;
559
610
    }
560
 
    return 0;
 
611
    return errno;
561
612
  }
562
613
  
563
614
  struct argp argp = { .options = options,
567
618
  
568
619
  /* Parse using parse_opt_config_file() in order to get the custom
569
620
     config file location, if any. */
570
 
  ret = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
571
 
  if(ret == ARGP_ERR_UNKNOWN){
572
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
573
 
    exitstatus = EXIT_FAILURE;
 
621
  ret = argp_parse(&argp, argc, argv,
 
622
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
623
                   NULL, NULL);
 
624
  switch(ret){
 
625
  case 0:
 
626
    break;
 
627
  case ENOMEM:
 
628
  default:
 
629
    errno = ret;
 
630
    error(0, errno, "argp_parse");
 
631
    exitstatus = EX_OSERR;
 
632
    goto fallback;
 
633
  case EINVAL:
 
634
    exitstatus = EX_USAGE;
574
635
    goto fallback;
575
636
  }
576
637
  
593
654
    custom_argc = 1;
594
655
    custom_argv = malloc(sizeof(char*) * 2);
595
656
    if(custom_argv == NULL){
596
 
      perror("malloc");
597
 
      exitstatus = EXIT_FAILURE;
 
657
      error(0, errno, "malloc");
 
658
      exitstatus = EX_OSERR;
598
659
      goto fallback;
599
660
    }
600
661
    custom_argv[0] = argv[0];
616
677
        }
617
678
        new_arg = strdup(p);
618
679
        if(new_arg == NULL){
619
 
          perror("strdup");
620
 
          exitstatus = EXIT_FAILURE;
 
680
          error(0, errno, "strdup");
 
681
          exitstatus = EX_OSERR;
621
682
          free(org_line);
622
683
          goto fallback;
623
684
        }
624
685
        
625
686
        custom_argc += 1;
626
 
        custom_argv = realloc(custom_argv, sizeof(char *)
627
 
                              * ((unsigned int) custom_argc + 1));
628
 
        if(custom_argv == NULL){
629
 
          perror("realloc");
630
 
          exitstatus = EXIT_FAILURE;
631
 
          free(org_line);
632
 
          goto fallback;
 
687
        {
 
688
          char **new_argv = realloc(custom_argv, sizeof(char *)
 
689
                                    * ((unsigned int)
 
690
                                       custom_argc + 1));
 
691
          if(new_argv == NULL){
 
692
            error(0, errno, "realloc");
 
693
            exitstatus = EX_OSERR;
 
694
            free(new_arg);
 
695
            free(org_line);
 
696
            goto fallback;
 
697
          } else {
 
698
            custom_argv = new_argv;
 
699
          }
633
700
        }
634
701
        custom_argv[custom_argc-1] = new_arg;
635
702
        custom_argv[custom_argc] = NULL;
639
706
      ret = fclose(conffp);
640
707
    } while(ret == EOF and errno == EINTR);
641
708
    if(ret == EOF){
642
 
      perror("fclose");
643
 
      exitstatus = EXIT_FAILURE;
 
709
      error(0, errno, "fclose");
 
710
      exitstatus = EX_IOERR;
644
711
      goto fallback;
645
712
    }
646
713
    free(org_line);
648
715
    /* Check for harmful errors and go to fallback. Other errors might
649
716
       not affect opening plugins */
650
717
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
651
 
      perror("fopen");
652
 
      exitstatus = EXIT_FAILURE;
 
718
      error(0, errno, "fopen");
 
719
      exitstatus = EX_OSERR;
653
720
      goto fallback;
654
721
    }
655
722
  }
656
 
  /* If there was any arguments from configuration file,
657
 
     pass them to parser as command arguments */
 
723
  /* If there were any arguments from the configuration file, pass
 
724
     them to parser as command line arguments */
658
725
  if(custom_argv != NULL){
659
 
    ret = argp_parse(&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
660
 
                     0, NULL);
661
 
    if(ret == ARGP_ERR_UNKNOWN){
662
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
663
 
      exitstatus = EXIT_FAILURE;
 
726
    ret = argp_parse(&argp, custom_argc, custom_argv,
 
727
                     ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
728
                     NULL, NULL);
 
729
    switch(ret){
 
730
    case 0:
 
731
      break;
 
732
    case ENOMEM:
 
733
    default:
 
734
      errno = ret;
 
735
      error(0, errno, "argp_parse");
 
736
      exitstatus = EX_OSERR;
 
737
      goto fallback;
 
738
    case EINVAL:
 
739
      exitstatus = EX_CONFIG;
664
740
      goto fallback;
665
741
    }
666
742
  }
667
743
  
668
744
  /* Parse actual command line arguments, to let them override the
669
745
     config file */
670
 
  ret = argp_parse(&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
671
 
  if(ret == ARGP_ERR_UNKNOWN){
672
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
673
 
    exitstatus = EXIT_FAILURE;
 
746
  ret = argp_parse(&argp, argc, argv,
 
747
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
 
748
                   NULL, NULL);
 
749
  switch(ret){
 
750
  case 0:
 
751
    break;
 
752
  case ENOMEM:
 
753
  default:
 
754
    errno = ret;
 
755
    error(0, errno, "argp_parse");
 
756
    exitstatus = EX_OSERR;
 
757
    goto fallback;
 
758
  case EINVAL:
 
759
    exitstatus = EX_USAGE;
674
760
    goto fallback;
675
761
  }
676
762
  
688
774
    }
689
775
  }
690
776
  
691
 
  /* Strip permissions down to nobody */
692
 
  setgid(gid);
 
777
  if(getuid() == 0){
 
778
    /* Work around Debian bug #633582:
 
779
       <http://bugs.debian.org/633582> */
 
780
    int plugindir_fd = open(/* plugindir or */ PDIR, O_RDONLY);
 
781
    if(plugindir_fd == -1){
 
782
      error(0, errno, "open(\"" PDIR "\")");
 
783
    } else {
 
784
      ret = (int)TEMP_FAILURE_RETRY(fstat(plugindir_fd, &st));
 
785
      if(ret == -1){
 
786
        error(0, errno, "fstat");
 
787
      } else {
 
788
        if(S_ISDIR(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
789
          ret = fchown(plugindir_fd, uid, gid);
 
790
          if(ret == -1){
 
791
            error(0, errno, "fchown");
 
792
          }
 
793
        }
 
794
      }
 
795
      TEMP_FAILURE_RETRY(close(plugindir_fd));
 
796
    }
 
797
  }
 
798
  
 
799
  /* Lower permissions */
 
800
  ret = setgid(gid);
693
801
  if(ret == -1){
694
 
    perror("setgid");
 
802
    error(0, errno, "setgid");
695
803
  }
696
804
  ret = setuid(uid);
697
805
  if(ret == -1){
698
 
    perror("setuid");
699
 
  }
700
 
  
701
 
  if(plugindir == NULL){
702
 
    dir = opendir(PDIR);
703
 
  } else {
704
 
    dir = opendir(plugindir);
705
 
  }
706
 
  
707
 
  if(dir == NULL){
708
 
    perror("Could not open plugin dir");
709
 
    exitstatus = EXIT_FAILURE;
710
 
    goto fallback;
711
 
  }
712
 
  
713
 
  /* Set the FD_CLOEXEC flag on the directory, if possible */
 
806
    error(0, errno, "setuid");
 
807
  }
 
808
  
 
809
  /* Open plugin directory with close_on_exec flag */
714
810
  {
715
 
    int dir_fd = dirfd(dir);
716
 
    if(dir_fd >= 0){
717
 
      ret = set_cloexec_flag(dir_fd);
718
 
      if(ret < 0){
719
 
        perror("set_cloexec_flag");
720
 
        exitstatus = EXIT_FAILURE;
721
 
        goto fallback;
722
 
      }
 
811
    int dir_fd = -1;
 
812
    if(plugindir == NULL){
 
813
      dir_fd = open(PDIR, O_RDONLY |
 
814
#ifdef O_CLOEXEC
 
815
                    O_CLOEXEC
 
816
#else  /* not O_CLOEXEC */
 
817
                    0
 
818
#endif  /* not O_CLOEXEC */
 
819
                    );
 
820
    } else {
 
821
      dir_fd = open(plugindir, O_RDONLY |
 
822
#ifdef O_CLOEXEC
 
823
                    O_CLOEXEC
 
824
#else  /* not O_CLOEXEC */
 
825
                    0
 
826
#endif  /* not O_CLOEXEC */
 
827
                    );
 
828
    }
 
829
    if(dir_fd == -1){
 
830
      error(0, errno, "Could not open plugin dir");
 
831
      exitstatus = EX_UNAVAILABLE;
 
832
      goto fallback;
 
833
    }
 
834
    
 
835
#ifndef O_CLOEXEC
 
836
  /* Set the FD_CLOEXEC flag on the directory */
 
837
    ret = set_cloexec_flag(dir_fd);
 
838
    if(ret < 0){
 
839
      error(0, errno, "set_cloexec_flag");
 
840
      TEMP_FAILURE_RETRY(close(dir_fd));
 
841
      exitstatus = EX_OSERR;
 
842
      goto fallback;
 
843
    }
 
844
#endif  /* O_CLOEXEC */
 
845
    
 
846
    dir = fdopendir(dir_fd);
 
847
    if(dir == NULL){
 
848
      error(0, errno, "Could not open plugin dir");
 
849
      TEMP_FAILURE_RETRY(close(dir_fd));
 
850
      exitstatus = EX_OSERR;
 
851
      goto fallback;
723
852
    }
724
853
  }
725
854
  
734
863
    /* All directory entries have been processed */
735
864
    if(dirst == NULL){
736
865
      if(errno == EBADF){
737
 
        perror("readdir");
738
 
        exitstatus = EXIT_FAILURE;
 
866
        error(0, errno, "readdir");
 
867
        exitstatus = EX_IOERR;
739
868
        goto fallback;
740
869
      }
741
870
      break;
747
876
    {
748
877
      bool bad_name = false;
749
878
      
750
 
      const char const *bad_prefixes[] = { ".", "#", NULL };
 
879
      const char * const bad_prefixes[] = { ".", "#", NULL };
751
880
      
752
 
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
 
881
      const char * const bad_suffixes[] = { "~", "#", ".dpkg-new",
753
882
                                           ".dpkg-old",
754
883
                                           ".dpkg-bak",
755
884
                                           ".dpkg-divert", NULL };
756
 
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
 
885
#ifdef __GNUC__
 
886
#pragma GCC diagnostic push
 
887
#pragma GCC diagnostic ignored "-Wcast-qual"
 
888
#endif
 
889
      for(const char **pre = (const char **)bad_prefixes;
 
890
          *pre != NULL; pre++){
 
891
#ifdef __GNUC__
 
892
#pragma GCC diagnostic pop
 
893
#endif
757
894
        size_t pre_len = strlen(*pre);
758
895
        if((d_name_len >= pre_len)
759
896
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
768
905
      if(bad_name){
769
906
        continue;
770
907
      }
771
 
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
 
908
#ifdef __GNUC__
 
909
#pragma GCC diagnostic push
 
910
#pragma GCC diagnostic ignored "-Wcast-qual"
 
911
#endif
 
912
      for(const char **suf = (const char **)bad_suffixes;
 
913
          *suf != NULL; suf++){
 
914
#ifdef __GNUC__
 
915
#pragma GCC diagnostic pop
 
916
#endif
772
917
        size_t suf_len = strlen(*suf);
773
918
        if((d_name_len >= suf_len)
774
 
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
 
919
           and (strcmp((dirst->d_name) + d_name_len-suf_len, *suf)
775
920
                == 0)){
776
921
          if(debug){
777
922
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
797
942
                                             dirst->d_name));
798
943
    }
799
944
    if(ret < 0){
800
 
      perror("asprintf");
 
945
      error(0, errno, "asprintf");
801
946
      continue;
802
947
    }
803
948
    
804
949
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
805
950
    if(ret == -1){
806
 
      perror("stat");
 
951
      error(0, errno, "stat");
807
952
      free(filename);
808
953
      continue;
809
954
    }
821
966
    
822
967
    plugin *p = getplugin(dirst->d_name);
823
968
    if(p == NULL){
824
 
      perror("getplugin");
 
969
      error(0, errno, "getplugin");
825
970
      free(filename);
826
971
      continue;
827
972
    }
839
984
      if(g != NULL){
840
985
        for(char **a = g->argv + 1; *a != NULL; a++){
841
986
          if(not add_argument(p, *a)){
842
 
            perror("add_argument");
 
987
            error(0, errno, "add_argument");
843
988
          }
844
989
        }
845
990
        /* Add global environment variables */
846
991
        for(char **e = g->environ; *e != NULL; e++){
847
992
          if(not add_environment(p, *e, false)){
848
 
            perror("add_environment");
 
993
            error(0, errno, "add_environment");
849
994
          }
850
995
        }
851
996
      }
856
1001
    if(p->environ[0] != NULL){
857
1002
      for(char **e = environ; *e != NULL; e++){
858
1003
        if(not add_environment(p, *e, false)){
859
 
          perror("add_environment");
 
1004
          error(0, errno, "add_environment");
860
1005
        }
861
1006
      }
862
1007
    }
864
1009
    int pipefd[2];
865
1010
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
866
1011
    if(ret == -1){
867
 
      perror("pipe");
868
 
      exitstatus = EXIT_FAILURE;
 
1012
      error(0, errno, "pipe");
 
1013
      exitstatus = EX_OSERR;
869
1014
      goto fallback;
870
1015
    }
871
1016
    /* Ask OS to automatic close the pipe on exec */
872
1017
    ret = set_cloexec_flag(pipefd[0]);
873
1018
    if(ret < 0){
874
 
      perror("set_cloexec_flag");
875
 
      exitstatus = EXIT_FAILURE;
 
1019
      error(0, errno, "set_cloexec_flag");
 
1020
      exitstatus = EX_OSERR;
876
1021
      goto fallback;
877
1022
    }
878
1023
    ret = set_cloexec_flag(pipefd[1]);
879
1024
    if(ret < 0){
880
 
      perror("set_cloexec_flag");
881
 
      exitstatus = EXIT_FAILURE;
 
1025
      error(0, errno, "set_cloexec_flag");
 
1026
      exitstatus = EX_OSERR;
882
1027
      goto fallback;
883
1028
    }
884
1029
    /* Block SIGCHLD until process is safely in process list */
886
1031
                                              &sigchld_action.sa_mask,
887
1032
                                              NULL));
888
1033
    if(ret < 0){
889
 
      perror("sigprocmask");
890
 
      exitstatus = EXIT_FAILURE;
 
1034
      error(0, errno, "sigprocmask");
 
1035
      exitstatus = EX_OSERR;
891
1036
      goto fallback;
892
1037
    }
893
1038
    /* Starting a new process to be watched */
896
1041
      pid = fork();
897
1042
    } while(pid == -1 and errno == EINTR);
898
1043
    if(pid == -1){
899
 
      perror("fork");
900
 
      exitstatus = EXIT_FAILURE;
 
1044
      error(0, errno, "fork");
 
1045
      exitstatus = EX_OSERR;
901
1046
      goto fallback;
902
1047
    }
903
1048
    if(pid == 0){
904
1049
      /* this is the child process */
905
1050
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
906
1051
      if(ret < 0){
907
 
        perror("sigaction");
908
 
        _exit(EXIT_FAILURE);
 
1052
        error(0, errno, "sigaction");
 
1053
        _exit(EX_OSERR);
909
1054
      }
910
1055
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
911
1056
      if(ret < 0){
912
 
        perror("sigprocmask");
913
 
        _exit(EXIT_FAILURE);
 
1057
        error(0, errno, "sigprocmask");
 
1058
        _exit(EX_OSERR);
914
1059
      }
915
1060
      
916
1061
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
917
1062
      if(ret == -1){
918
 
        perror("dup2");
919
 
        _exit(EXIT_FAILURE);
 
1063
        error(0, errno, "dup2");
 
1064
        _exit(EX_OSERR);
920
1065
      }
921
1066
      
922
1067
      if(dirfd(dir) < 0){
924
1069
           above and must now close it manually here. */
925
1070
        closedir(dir);
926
1071
      }
927
 
      if(p->environ[0] == NULL){
928
 
        if(execv(filename, p->argv) < 0){
929
 
          perror("execv");
930
 
          _exit(EXIT_FAILURE);
931
 
        }
932
 
      } else {
933
 
        if(execve(filename, p->argv, p->environ) < 0){
934
 
          perror("execve");
935
 
          _exit(EXIT_FAILURE);
936
 
        }
 
1072
      if(execve(filename, p->argv,
 
1073
                (p->environ[0] != NULL) ? p->environ : environ) < 0){
 
1074
        error(0, errno, "execve for %s", filename);
 
1075
        _exit(EX_OSERR);
937
1076
      }
938
1077
      /* no return */
939
1078
    }
943
1082
    free(filename);
944
1083
    plugin *new_plugin = getplugin(dirst->d_name);
945
1084
    if(new_plugin == NULL){
946
 
      perror("getplugin");
 
1085
      error(0, errno, "getplugin");
947
1086
      ret = (int)(TEMP_FAILURE_RETRY
948
1087
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
949
1088
                               NULL)));
950
1089
      if(ret < 0){
951
 
        perror("sigprocmask");
 
1090
        error(0, errno, "sigprocmask");
952
1091
      }
953
 
      exitstatus = EXIT_FAILURE;
 
1092
      exitstatus = EX_OSERR;
954
1093
      goto fallback;
955
1094
    }
956
1095
    
963
1102
                                              &sigchld_action.sa_mask,
964
1103
                                              NULL));
965
1104
    if(ret < 0){
966
 
      perror("sigprocmask");
967
 
      exitstatus = EXIT_FAILURE;
 
1105
      error(0, errno, "sigprocmask");
 
1106
      exitstatus = EX_OSERR;
968
1107
      goto fallback;
969
1108
    }
970
1109
    
971
 
    FD_SET(new_plugin->fd, &rfds_all);
 
1110
#if defined (__GNUC__) and defined (__GLIBC__)
 
1111
#if not __GLIBC_PREREQ(2, 16)
 
1112
#pragma GCC diagnostic push
 
1113
#pragma GCC diagnostic ignored "-Wsign-conversion"
 
1114
#endif
 
1115
#endif
 
1116
    FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from
 
1117
                                          -Wconversion in GNU libc
 
1118
                                          before 2.16 */
 
1119
#if defined (__GNUC__) and defined (__GLIBC__)
 
1120
#if not __GLIBC_PREREQ(2, 16)
 
1121
#pragma GCC diagnostic pop
 
1122
#endif
 
1123
#endif
972
1124
    
973
1125
    if(maxfd < new_plugin->fd){
974
1126
      maxfd = new_plugin->fd;
995
1147
    fd_set rfds = rfds_all;
996
1148
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
997
1149
    if(select_ret == -1 and errno != EINTR){
998
 
      perror("select");
999
 
      exitstatus = EXIT_FAILURE;
 
1150
      error(0, errno, "select");
 
1151
      exitstatus = EX_OSERR;
1000
1152
      goto fallback;
1001
1153
    }
1002
1154
    /* OK, now either a process completed, or something can be read
1028
1180
          }
1029
1181
          
1030
1182
          /* Remove the plugin */
1031
 
          FD_CLR(proc->fd, &rfds_all);
 
1183
#if defined (__GNUC__) and defined (__GLIBC__)
 
1184
#if not __GLIBC_PREREQ(2, 16)
 
1185
#pragma GCC diagnostic push
 
1186
#pragma GCC diagnostic ignored "-Wsign-conversion"
 
1187
#endif
 
1188
#endif
 
1189
          FD_CLR(proc->fd, &rfds_all); /* Spurious warning from
 
1190
                                          -Wconversion in GNU libc
 
1191
                                          before 2.16 */
 
1192
#if defined (__GNUC__) and defined (__GLIBC__)
 
1193
#if not __GLIBC_PREREQ(2, 16)
 
1194
#pragma GCC diagnostic pop
 
1195
#endif
 
1196
#endif
1032
1197
          
1033
1198
          /* Block signal while modifying process_list */
1034
1199
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
1036
1201
                                         &sigchld_action.sa_mask,
1037
1202
                                         NULL));
1038
1203
          if(ret < 0){
1039
 
            perror("sigprocmask");
1040
 
            exitstatus = EXIT_FAILURE;
 
1204
            error(0, errno, "sigprocmask");
 
1205
            exitstatus = EX_OSERR;
1041
1206
            goto fallback;
1042
1207
          }
1043
1208
          
1050
1215
                      (sigprocmask(SIG_UNBLOCK,
1051
1216
                                   &sigchld_action.sa_mask, NULL)));
1052
1217
          if(ret < 0){
1053
 
            perror("sigprocmask");
1054
 
            exitstatus = EXIT_FAILURE;
 
1218
            error(0, errno, "sigprocmask");
 
1219
            exitstatus = EX_OSERR;
1055
1220
            goto fallback;
1056
1221
          }
1057
1222
          
1067
1232
        bool bret = print_out_password(proc->buffer,
1068
1233
                                       proc->buffer_length);
1069
1234
        if(not bret){
1070
 
          perror("print_out_password");
1071
 
          exitstatus = EXIT_FAILURE;
 
1235
          error(0, errno, "print_out_password");
 
1236
          exitstatus = EX_IOERR;
1072
1237
        }
1073
1238
        goto fallback;
1074
1239
      }
1075
1240
      
1076
1241
      /* This process has not completed.  Does it have any output? */
1077
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
 
1242
#if defined (__GNUC__) and defined (__GLIBC__)
 
1243
#if not __GLIBC_PREREQ(2, 16)
 
1244
#pragma GCC diagnostic push
 
1245
#pragma GCC diagnostic ignored "-Wsign-conversion"
 
1246
#endif
 
1247
#endif
 
1248
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious
 
1249
                                                         warning from
 
1250
                                                         -Wconversion
 
1251
                                                         in GNU libc
 
1252
                                                         before
 
1253
                                                         2.16 */
 
1254
#if defined (__GNUC__) and defined (__GLIBC__)
 
1255
#if not __GLIBC_PREREQ(2, 16)
 
1256
#pragma GCC diagnostic pop
 
1257
#endif
 
1258
#endif
1078
1259
        /* This process had nothing to say at this time */
1079
1260
        proc = proc->next;
1080
1261
        continue;
1081
1262
      }
1082
1263
      /* Before reading, make the process' data buffer large enough */
1083
1264
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1084
 
        proc->buffer = realloc(proc->buffer, proc->buffer_size
1085
 
                               + (size_t) BUFFER_SIZE);
1086
 
        if(proc->buffer == NULL){
1087
 
          perror("malloc");
1088
 
          exitstatus = EXIT_FAILURE;
 
1265
        char *new_buffer = realloc(proc->buffer, proc->buffer_size
 
1266
                                   + (size_t) BUFFER_SIZE);
 
1267
        if(new_buffer == NULL){
 
1268
          error(0, errno, "malloc");
 
1269
          exitstatus = EX_OSERR;
1089
1270
          goto fallback;
1090
1271
        }
 
1272
        proc->buffer = new_buffer;
1091
1273
        proc->buffer_size += BUFFER_SIZE;
1092
1274
      }
1093
1275
      /* Read from the process */
1112
1294
  
1113
1295
 fallback:
1114
1296
  
1115
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
1297
  if(plugin_list == NULL or (exitstatus != EXIT_SUCCESS
 
1298
                             and exitstatus != EX_OK)){
1116
1299
    /* Fallback if all plugins failed, none are found or an error
1117
1300
       occured */
1118
1301
    bool bret;
1126
1309
    }
1127
1310
    bret = print_out_password(passwordbuffer, len);
1128
1311
    if(not bret){
1129
 
      perror("print_out_password");
1130
 
      exitstatus = EXIT_FAILURE;
 
1312
      error(0, errno, "print_out_password");
 
1313
      exitstatus = EX_IOERR;
1131
1314
    }
1132
1315
  }
1133
1316
  
1134
1317
  /* Restore old signal handler */
1135
1318
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1136
1319
  if(ret == -1){
1137
 
    perror("sigaction");
1138
 
    exitstatus = EXIT_FAILURE;
 
1320
    error(0, errno, "sigaction");
 
1321
    exitstatus = EX_OSERR;
1139
1322
  }
1140
1323
  
1141
1324
  if(custom_argv != NULL){
1156
1339
      ret = kill(p->pid, SIGTERM);
1157
1340
      if(ret == -1 and errno != ESRCH){
1158
1341
        /* Set-uid proccesses might not get closed */
1159
 
        perror("kill");
 
1342
        error(0, errno, "kill");
1160
1343
      }
1161
1344
    }
1162
1345
  }
1166
1349
    ret = wait(NULL);
1167
1350
  } while(ret >= 0);
1168
1351
  if(errno != ECHILD){
1169
 
    perror("wait");
 
1352
    error(0, errno, "wait");
1170
1353
  }
1171
1354
  
1172
1355
  free_plugin_list();