/mandos/release

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2014-03-23 20:48:58 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 311.
  • 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:
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 © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
5
 * Copyright © 2008-2013 Teddy Hogeborn
 
6
 * Copyright © 2008-2013 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
18
19
 * along with this program.  If not, see
19
20
 * <http://www.gnu.org/licenses/>.
20
21
 * 
21
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
22
 * Contact the authors at <mandos@recompile.se>.
22
23
 */
23
24
 
24
25
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
25
 
                                   asprintf() */
 
26
                                   asprintf(), O_CLOEXEC */
26
27
#include <stddef.h>             /* size_t, NULL */
27
 
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
 
                                   EXIT_SUCCESS, realloc() */
 
28
#include <stdlib.h>             /* malloc(), exit(), EXIT_SUCCESS,
 
29
                                   realloc() */
29
30
#include <stdbool.h>            /* bool, true, false */
30
 
#include <stdio.h>              /* perror, popen(), fileno(),
31
 
                                   fprintf(), stderr, STDOUT_FILENO */
32
 
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
 
31
#include <stdio.h>              /* fileno(), fprintf(),
 
32
                                   stderr, STDOUT_FILENO */
 
33
#include <sys/types.h>          /* DIR, fdopendir(), stat(), struct
33
34
                                   stat, waitpid(), WIFEXITED(),
34
35
                                   WEXITSTATUS(), wait(), pid_t,
35
36
                                   uid_t, gid_t, getuid(), getgid(),
37
38
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
38
39
                                   FD_SET(), FD_ISSET(), FD_CLR */
39
40
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
40
 
                                   WEXITSTATUS() */
 
41
                                   WEXITSTATUS(), WTERMSIG(),
 
42
                                   WCOREDUMP() */
41
43
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
42
44
#include <iso646.h>             /* and, or, not */
43
 
#include <dirent.h>             /* DIR, struct dirent, opendir(),
 
45
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
44
46
                                   readdir(), closedir(), dirfd() */
45
47
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
46
48
                                   fcntl(), setuid(), setgid(),
47
49
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
48
50
                                   access(), pipe(), fork(), close()
49
 
                                   dup2, STDOUT_FILENO, _exit(),
50
 
                                   execv(), write(), read(),
 
51
                                   dup2(), STDOUT_FILENO, _exit(),
 
52
                                   execve(), write(), read(),
51
53
                                   close() */
52
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
55
                                   FD_CLOEXEC */
54
 
#include <string.h>             /* strsep, strlen(), asprintf() */
 
56
#include <string.h>             /* strsep, strlen(), asprintf(),
 
57
                                   strsignal(), strcmp(), strncmp() */
55
58
#include <errno.h>              /* errno */
56
59
#include <argp.h>               /* struct argp_option, struct
57
60
                                   argp_state, struct argp,
61
64
#include <signal.h>             /* struct sigaction, sigemptyset(),
62
65
                                   sigaddset(), sigaction(),
63
66
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
64
 
                                   SIG_UNBLOCK, kill() */
 
67
                                   SIG_UNBLOCK, kill(), sig_atomic_t
 
68
                                */
65
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 */
 
73
#include <errno.h>              /* errno */
 
74
#include <error.h>              /* error() */
66
75
 
67
76
#define BUFFER_SIZE 256
68
77
 
69
78
#define PDIR "/lib/mandos/plugins.d"
70
79
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
71
80
 
72
 
const char *argp_program_version = "plugin-runner 1.0";
73
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
74
 
 
75
 
struct plugin;
 
81
const char *argp_program_version = "plugin-runner " VERSION;
 
82
const char *argp_program_bug_address = "<mandos@recompile.se>";
76
83
 
77
84
typedef struct plugin{
78
85
  char *name;                   /* can be NULL or any plugin name */
81
88
  char **environ;
82
89
  int envc;
83
90
  bool disabled;
84
 
 
 
91
  
85
92
  /* Variables used for running processes*/
86
93
  pid_t pid;
87
94
  int fd;
89
96
  size_t buffer_size;
90
97
  size_t buffer_length;
91
98
  bool eof;
92
 
  volatile bool completed;
93
 
  volatile int status;
 
99
  volatile sig_atomic_t completed;
 
100
  int status;
94
101
  struct plugin *next;
95
102
} plugin;
96
103
 
98
105
 
99
106
/* Gets an existing plugin based on name,
100
107
   or if none is found, creates a new one */
 
108
__attribute__((warn_unused_result))
101
109
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))){
 
110
  /* Check for existing plugin with that name */
 
111
  for(plugin *p = plugin_list; p != NULL; p = p->next){
 
112
    if((p->name == name)
 
113
       or (p->name and name and (strcmp(p->name, name) == 0))){
106
114
      return p;
107
115
    }
108
116
  }
109
117
  /* Create a new plugin */
110
 
  plugin *new_plugin = malloc(sizeof(plugin));
111
 
  if (new_plugin == NULL){
 
118
  plugin *new_plugin = NULL;
 
119
  do {
 
120
    new_plugin = malloc(sizeof(plugin));
 
121
  } while(new_plugin == NULL and errno == EINTR);
 
122
  if(new_plugin == NULL){
112
123
    return NULL;
113
124
  }
114
125
  char *copy_name = NULL;
115
126
  if(name != NULL){
116
 
    copy_name = strdup(name);
 
127
    do {
 
128
      copy_name = strdup(name);
 
129
    } while(copy_name == NULL and errno == EINTR);
117
130
    if(copy_name == NULL){
 
131
      int e = errno;
 
132
      free(new_plugin);
 
133
      errno = e;
118
134
      return NULL;
119
135
    }
120
136
  }
121
137
  
122
 
  *new_plugin = (plugin) { .name = copy_name,
123
 
                           .argc = 1,
124
 
                           .disabled = false,
125
 
                           .next = plugin_list };
 
138
  *new_plugin = (plugin){ .name = copy_name,
 
139
                          .argc = 1,
 
140
                          .disabled = false,
 
141
                          .next = plugin_list };
126
142
  
127
 
  new_plugin->argv = malloc(sizeof(char *) * 2);
128
 
  if (new_plugin->argv == NULL){
 
143
  do {
 
144
    new_plugin->argv = malloc(sizeof(char *) * 2);
 
145
  } while(new_plugin->argv == NULL and errno == EINTR);
 
146
  if(new_plugin->argv == NULL){
 
147
    int e = errno;
129
148
    free(copy_name);
130
149
    free(new_plugin);
 
150
    errno = e;
131
151
    return NULL;
132
152
  }
133
153
  new_plugin->argv[0] = copy_name;
134
154
  new_plugin->argv[1] = NULL;
135
155
  
136
 
  new_plugin->environ = malloc(sizeof(char *));
 
156
  do {
 
157
    new_plugin->environ = malloc(sizeof(char *));
 
158
  } while(new_plugin->environ == NULL and errno == EINTR);
137
159
  if(new_plugin->environ == NULL){
 
160
    int e = errno;
138
161
    free(copy_name);
139
162
    free(new_plugin->argv);
140
163
    free(new_plugin);
 
164
    errno = e;
141
165
    return NULL;
142
166
  }
143
167
  new_plugin->environ[0] = NULL;
148
172
}
149
173
 
150
174
/* Helper function for add_argument and add_environment */
 
175
__attribute__((nonnull, warn_unused_result))
151
176
static bool add_to_char_array(const char *new, char ***array,
152
177
                              int *len){
153
178
  /* Resize the pointed-to array to hold one more pointer */
154
 
  *array = realloc(*array, sizeof(char *)
155
 
                   * (size_t) ((*len) + 2));
 
179
  char **new_array = NULL;
 
180
  do {
 
181
    new_array = realloc(*array, sizeof(char *)
 
182
                        * (size_t) ((*len) + 2));
 
183
  } while(new_array == NULL and errno == EINTR);
156
184
  /* Malloc check */
157
 
  if(*array == NULL){
 
185
  if(new_array == NULL){
158
186
    return false;
159
187
  }
 
188
  *array = new_array;
160
189
  /* Make a copy of the new string */
161
 
  char *copy = strdup(new);
 
190
  char *copy;
 
191
  do {
 
192
    copy = strdup(new);
 
193
  } while(copy == NULL and errno == EINTR);
162
194
  if(copy == NULL){
163
195
    return false;
164
196
  }
171
203
}
172
204
 
173
205
/* Add to a plugin's argument vector */
 
206
__attribute__((nonnull(2), warn_unused_result))
174
207
static bool add_argument(plugin *p, const char *arg){
175
208
  if(p == NULL){
176
209
    return false;
179
212
}
180
213
 
181
214
/* Add to a plugin's environment */
 
215
__attribute__((nonnull(2), warn_unused_result))
182
216
static bool add_environment(plugin *p, const char *def, bool replace){
183
217
  if(p == NULL){
184
218
    return false;
186
220
  /* namelen = length of name of environment variable */
187
221
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
188
222
  /* Search for this environment variable */
189
 
  for(char **e = p->environ; *e != NULL; e++){
190
 
    if(strncmp(*e, def, namelen + 1) == 0){
 
223
  for(char **envdef = p->environ; *envdef != NULL; envdef++){
 
224
    if(strncmp(*envdef, def, namelen + 1) == 0){
191
225
      /* It already exists */
192
226
      if(replace){
193
 
        char *new = realloc(*e, strlen(def) + 1);
194
 
        if(new == NULL){
 
227
        char *new_envdef;
 
228
        do {
 
229
          new_envdef = realloc(*envdef, strlen(def) + 1);
 
230
        } while(new_envdef == NULL and errno == EINTR);
 
231
        if(new_envdef == NULL){
195
232
          return false;
196
233
        }
197
 
        *e = new;
198
 
        strcpy(*e, def);
 
234
        *envdef = new_envdef;
 
235
        strcpy(*envdef, def);
199
236
      }
200
237
      return true;
201
238
    }
206
243
/*
207
244
 * Based on the example in the GNU LibC manual chapter 13.13 "File
208
245
 * Descriptor Flags".
209
 
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
 
246
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
210
247
 */
211
 
static int set_cloexec_flag(int fd)
212
 
{
213
 
  int ret = fcntl(fd, F_GETFD, 0);
 
248
__attribute__((warn_unused_result))
 
249
static int set_cloexec_flag(int fd){
 
250
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
214
251
  /* If reading the flags failed, return error indication now. */
215
252
  if(ret < 0){
216
253
    return ret;
217
254
  }
218
255
  /* Store modified flag word in the descriptor. */
219
 
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
 
256
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
 
257
                                       ret | FD_CLOEXEC));
220
258
}
221
259
 
222
260
 
223
261
/* Mark processes as completed when they exit, and save their exit
224
262
   status. */
225
 
void handle_sigchld(__attribute__((unused)) int sig){
 
263
static void handle_sigchld(__attribute__((unused)) int sig){
 
264
  int old_errno = errno;
226
265
  while(true){
227
266
    plugin *proc = plugin_list;
228
267
    int status;
232
271
      break;
233
272
    }
234
273
    if(pid == -1){
235
 
      if (errno != ECHILD){
236
 
        perror("waitpid");
 
274
      if(errno == ECHILD){
 
275
        /* No child processes */
 
276
        break;
237
277
      }
238
 
      /* No child processes */
239
 
      break;
 
278
      error(0, errno, "waitpid");
240
279
    }
241
280
    
242
281
    /* A child exited, find it in process_list */
248
287
      continue;
249
288
    }
250
289
    proc->status = status;
251
 
    proc->completed = true;
 
290
    proc->completed = 1;
252
291
  }
 
292
  errno = old_errno;
253
293
}
254
294
 
255
295
/* Prints out a password to stdout */
256
 
bool print_out_password(const char *buffer, size_t length){
 
296
__attribute__((nonnull, warn_unused_result))
 
297
static bool print_out_password(const char *buffer, size_t length){
257
298
  ssize_t ret;
258
299
  for(size_t written = 0; written < length; written += (size_t)ret){
259
300
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
266
307
}
267
308
 
268
309
/* Removes and free a plugin from the plugin list */
 
310
__attribute__((nonnull))
269
311
static void free_plugin(plugin *plugin_node){
270
312
  
271
313
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
277
319
  }
278
320
  free(plugin_node->environ);
279
321
  free(plugin_node->buffer);
280
 
 
 
322
  
281
323
  /* Removes the plugin from the singly-linked list */
282
324
  if(plugin_node == plugin_list){
283
325
    /* First one - simple */
311
353
  struct stat st;
312
354
  fd_set rfds_all;
313
355
  int ret, maxfd = 0;
 
356
  ssize_t sret;
314
357
  uid_t uid = 65534;
315
358
  gid_t gid = 65534;
316
359
  bool debug = false;
325
368
  sigemptyset(&sigchld_action.sa_mask);
326
369
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
327
370
  if(ret == -1){
328
 
    perror("sigaddset");
329
 
    exitstatus = EXIT_FAILURE;
 
371
    error(0, errno, "sigaddset");
 
372
    exitstatus = EX_OSERR;
330
373
    goto fallback;
331
374
  }
332
375
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
333
376
  if(ret == -1){
334
 
    perror("sigaction");
335
 
    exitstatus = EXIT_FAILURE;
 
377
    error(0, errno, "sigaction");
 
378
    exitstatus = EX_OSERR;
336
379
    goto fallback;
337
380
  }
338
381
  
370
413
      .doc = "Group ID the plugins will run as", .group = 3 },
371
414
    { .name = "debug", .key = 132,
372
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 },
373
425
    { .name = NULL }
374
426
  };
375
427
  
376
 
  error_t parse_opt (int key, char *arg, __attribute__((unused))
377
 
                     struct argp_state *state) {
378
 
    switch (key) {
 
428
  __attribute__((nonnull(3)))
 
429
  error_t parse_opt(int key, char *arg, struct argp_state *state){
 
430
    errno = 0;
 
431
    switch(key){
 
432
      char *tmp;
 
433
      intmax_t tmp_id;
379
434
    case 'g':                   /* --global-options */
380
 
      if (arg != NULL){
381
 
        char *p;
382
 
        while((p = strsep(&arg, ",")) != NULL){
383
 
          if(p[0] == '\0'){
384
 
            continue;
385
 
          }
386
 
          if(not add_argument(getplugin(NULL), p)){
387
 
            perror("add_argument");
388
 
            return ARGP_ERR_UNKNOWN;
 
435
      {
 
436
        char *plugin_option;
 
437
        while((plugin_option = strsep(&arg, ",")) != NULL){
 
438
          if(not add_argument(getplugin(NULL), plugin_option)){
 
439
            break;
389
440
          }
390
441
        }
 
442
        errno = 0;
391
443
      }
392
444
      break;
393
445
    case 'G':                   /* --global-env */
394
 
      if(arg == NULL){
395
 
        break;
396
 
      }
397
 
      if(not add_environment(getplugin(NULL), arg, true)){
398
 
        perror("add_environment");
 
446
      if(add_environment(getplugin(NULL), arg, true)){
 
447
        errno = 0;
399
448
      }
400
449
      break;
401
450
    case 'o':                   /* --options-for */
402
 
      if (arg != NULL){
403
 
        char *p_name = strsep(&arg, ":");
404
 
        if(p_name[0] == '\0' or arg == NULL){
405
 
          break;
406
 
        }
407
 
        char *opt = strsep(&arg, ":");
408
 
        if(opt[0] == '\0' or opt == NULL){
409
 
          break;
410
 
        }
411
 
        char *p;
412
 
        while((p = strsep(&opt, ",")) != NULL){
413
 
          if(p[0] == '\0'){
414
 
            continue;
415
 
          }
416
 
          if(not add_argument(getplugin(p_name), p)){
417
 
            perror("add_argument");
418
 
            return ARGP_ERR_UNKNOWN;
419
 
          }
420
 
        }
 
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;
 
469
          }
 
470
        }
 
471
        errno = 0;
421
472
      }
422
473
      break;
423
474
    case 'E':                   /* --env-for */
424
 
      if(arg == NULL){
425
 
        break;
426
 
      }
427
475
      {
428
476
        char *envdef = strchr(arg, ':');
429
477
        if(envdef == NULL){
 
478
          argp_error(state, "No colon in \"%s\"", arg);
 
479
          errno = EINVAL;
430
480
          break;
431
481
        }
432
482
        *envdef = '\0';
433
 
        if(not add_environment(getplugin(arg), envdef+1, true)){
434
 
          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;
435
491
        }
436
492
      }
437
493
      break;
438
494
    case 'd':                   /* --disable */
439
 
      if (arg != NULL){
 
495
      {
440
496
        plugin *p = getplugin(arg);
441
 
        if(p == NULL){
442
 
          return ARGP_ERR_UNKNOWN;
 
497
        if(p != NULL){
 
498
          p->disabled = true;
 
499
          errno = 0;
443
500
        }
444
 
        p->disabled = true;
445
501
      }
446
502
      break;
447
503
    case 'e':                   /* --enable */
448
 
      if (arg != NULL){
 
504
      {
449
505
        plugin *p = getplugin(arg);
450
 
        if(p == NULL){
451
 
          return ARGP_ERR_UNKNOWN;
 
506
        if(p != NULL){
 
507
          p->disabled = false;
 
508
          errno = 0;
452
509
        }
453
 
        p->disabled = false;
454
510
      }
455
511
      break;
456
512
    case 128:                   /* --plugin-dir */
457
513
      free(plugindir);
458
514
      plugindir = strdup(arg);
459
 
      if(plugindir == NULL){
460
 
        perror("strdup");
461
 
      }      
 
515
      if(plugindir != NULL){
 
516
        errno = 0;
 
517
      }
462
518
      break;
463
519
    case 129:                   /* --config-file */
464
520
      /* This is already done by parse_opt_config_file() */
465
521
      break;
466
522
    case 130:                   /* --userid */
467
 
      uid = (uid_t)strtol(arg, NULL, 10);
 
523
      tmp_id = strtoimax(arg, &tmp, 10);
 
524
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
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;
 
529
      }
 
530
      uid = (uid_t)tmp_id;
 
531
      errno = 0;
468
532
      break;
469
533
    case 131:                   /* --groupid */
470
 
      gid = (gid_t)strtol(arg, NULL, 10);
 
534
      tmp_id = strtoimax(arg, &tmp, 10);
 
535
      if(errno != 0 or tmp == arg or *tmp != '\0'
 
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;
 
540
      }
 
541
      gid = (gid_t)tmp_id;
 
542
      errno = 0;
471
543
      break;
472
544
    case 132:                   /* --debug */
473
545
      debug = true;
474
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;
 
561
/*
 
562
 * When adding more options before this line, remember to also add a
 
563
 * "case" to the "parse_opt_config_file" function below.
 
564
 */
475
565
    case ARGP_KEY_ARG:
476
566
      /* Cryptsetup always passes an argument, which is an empty
477
567
         string if "none" was specified in /etc/crypttab.  So if
478
568
         argument was empty, we ignore it silently. */
479
 
      if(arg[0] != '\0'){
480
 
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
569
      if(arg[0] == '\0'){
 
570
        break;
481
571
      }
482
 
      break;
483
 
    case ARGP_KEY_END:
484
 
      break;
485
572
    default:
486
573
      return ARGP_ERR_UNKNOWN;
487
574
    }
488
 
    return 0;
 
575
    return errno;               /* Set to 0 at start */
489
576
  }
490
577
  
491
578
  /* This option parser is the same as parse_opt() above, except it
492
579
     ignores everything but the --config-file option. */
493
 
  error_t parse_opt_config_file (int key, char *arg,
494
 
                                 __attribute__((unused))
495
 
                                 struct argp_state *state) {
496
 
    switch (key) {
 
580
  error_t parse_opt_config_file(int key, char *arg,
 
581
                                __attribute__((unused))
 
582
                                struct argp_state *state){
 
583
    errno = 0;
 
584
    switch(key){
497
585
    case 'g':                   /* --global-options */
498
586
    case 'G':                   /* --global-env */
499
587
    case 'o':                   /* --options-for */
505
593
    case 129:                   /* --config-file */
506
594
      free(argfile);
507
595
      argfile = strdup(arg);
508
 
      if(argfile == NULL){
509
 
        perror("strdup");
 
596
      if(argfile != NULL){
 
597
        errno = 0;
510
598
      }
511
 
      break;      
 
599
      break;
512
600
    case 130:                   /* --userid */
513
601
    case 131:                   /* --groupid */
514
602
    case 132:                   /* --debug */
 
603
    case '?':                   /* --help */
 
604
    case -3:                    /* --usage */
 
605
    case 'V':                   /* --version */
515
606
    case ARGP_KEY_ARG:
516
 
    case ARGP_KEY_END:
517
607
      break;
518
608
    default:
519
609
      return ARGP_ERR_UNKNOWN;
520
610
    }
521
 
    return 0;
 
611
    return errno;
522
612
  }
523
613
  
524
614
  struct argp argp = { .options = options,
526
616
                       .args_doc = "",
527
617
                       .doc = "Mandos plugin runner -- Run plugins" };
528
618
  
529
 
  /* Parse using the parse_opt_config_file in order to get the custom
 
619
  /* Parse using parse_opt_config_file() in order to get the custom
530
620
     config file location, if any. */
531
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
532
 
  if (ret == ARGP_ERR_UNKNOWN){
533
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
534
 
    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;
535
635
    goto fallback;
536
636
  }
537
637
  
539
639
  argp.parser = parse_opt;
540
640
  
541
641
  /* Open the configfile if available */
542
 
  if (argfile == NULL){
 
642
  if(argfile == NULL){
543
643
    conffp = fopen(AFILE, "r");
544
644
  } else {
545
645
    conffp = fopen(argfile, "r");
546
 
  }  
 
646
  }
547
647
  if(conffp != NULL){
548
648
    char *org_line = NULL;
549
649
    char *p, *arg, *new_arg, *line;
550
650
    size_t size = 0;
551
 
    ssize_t sret;
552
651
    const char whitespace_delims[] = " \r\t\f\v\n";
553
652
    const char comment_delim[] = "#";
554
 
 
 
653
    
555
654
    custom_argc = 1;
556
655
    custom_argv = malloc(sizeof(char*) * 2);
557
656
    if(custom_argv == NULL){
558
 
      perror("malloc");
559
 
      exitstatus = EXIT_FAILURE;
 
657
      error(0, errno, "malloc");
 
658
      exitstatus = EX_OSERR;
560
659
      goto fallback;
561
660
    }
562
661
    custom_argv[0] = argv[0];
563
662
    custom_argv[1] = NULL;
564
 
 
 
663
    
565
664
    /* for each line in the config file, strip whitespace and ignore
566
665
       commented text */
567
666
    while(true){
569
668
      if(sret == -1){
570
669
        break;
571
670
      }
572
 
 
 
671
      
573
672
      line = org_line;
574
673
      arg = strsep(&line, comment_delim);
575
674
      while((p = strsep(&arg, whitespace_delims)) != NULL){
578
677
        }
579
678
        new_arg = strdup(p);
580
679
        if(new_arg == NULL){
581
 
          perror("strdup");
582
 
          exitstatus = EXIT_FAILURE;
 
680
          error(0, errno, "strdup");
 
681
          exitstatus = EX_OSERR;
583
682
          free(org_line);
584
683
          goto fallback;
585
684
        }
586
685
        
587
686
        custom_argc += 1;
588
 
        custom_argv = realloc(custom_argv, sizeof(char *)
589
 
                              * ((unsigned int) custom_argc + 1));
590
 
        if(custom_argv == NULL){
591
 
          perror("realloc");
592
 
          exitstatus = EXIT_FAILURE;
593
 
          free(org_line);
594
 
          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
          }
595
700
        }
596
701
        custom_argv[custom_argc-1] = new_arg;
597
 
        custom_argv[custom_argc] = NULL;        
 
702
        custom_argv[custom_argc] = NULL;
598
703
      }
599
704
    }
 
705
    do {
 
706
      ret = fclose(conffp);
 
707
    } while(ret == EOF and errno == EINTR);
 
708
    if(ret == EOF){
 
709
      error(0, errno, "fclose");
 
710
      exitstatus = EX_IOERR;
 
711
      goto fallback;
 
712
    }
600
713
    free(org_line);
601
714
  } else {
602
715
    /* Check for harmful errors and go to fallback. Other errors might
603
716
       not affect opening plugins */
604
 
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
605
 
      perror("fopen");
606
 
      exitstatus = EXIT_FAILURE;
 
717
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
 
718
      error(0, errno, "fopen");
 
719
      exitstatus = EX_OSERR;
607
720
      goto fallback;
608
721
    }
609
722
  }
610
 
  /* If there was any arguments from configuration file,
611
 
     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 */
612
725
  if(custom_argv != NULL){
613
 
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
614
 
                      0, NULL);
615
 
    if (ret == ARGP_ERR_UNKNOWN){
616
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
617
 
      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;
618
740
      goto fallback;
619
741
    }
620
742
  }
621
743
  
622
744
  /* Parse actual command line arguments, to let them override the
623
745
     config file */
624
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
625
 
  if (ret == ARGP_ERR_UNKNOWN){
626
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
627
 
    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;
628
760
    goto fallback;
629
761
  }
630
762
  
635
767
      for(char **a = p->argv; *a != NULL; a++){
636
768
        fprintf(stderr, "\tArg: %s\n", *a);
637
769
      }
638
 
      fprintf(stderr, "...and %u environment variables\n", p->envc);
 
770
      fprintf(stderr, "...and %d environment variables\n", p->envc);
639
771
      for(char **a = p->environ; *a != NULL; a++){
640
772
        fprintf(stderr, "\t%s\n", *a);
641
773
      }
642
774
    }
643
775
  }
644
776
  
645
 
  /* Strip permissions down to nobody */
 
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);
 
801
  if(ret == -1){
 
802
    error(0, errno, "setgid");
 
803
  }
646
804
  ret = setuid(uid);
647
 
  if (ret == -1){
648
 
    perror("setuid");
649
 
  }  
650
 
  setgid(gid);
651
 
  if (ret == -1){
652
 
    perror("setgid");
653
 
  }
654
 
  
655
 
  if (plugindir == NULL){
656
 
    dir = opendir(PDIR);
657
 
  } else {
658
 
    dir = opendir(plugindir);
659
 
  }
660
 
  
661
 
  if(dir == NULL){
662
 
    perror("Could not open plugin dir");
663
 
    exitstatus = EXIT_FAILURE;
664
 
    goto fallback;
665
 
  }
666
 
  
667
 
  /* Set the FD_CLOEXEC flag on the directory, if possible */
 
805
  if(ret == -1){
 
806
    error(0, errno, "setuid");
 
807
  }
 
808
  
 
809
  /* Open plugin directory with close_on_exec flag */
668
810
  {
669
 
    int dir_fd = dirfd(dir);
670
 
    if(dir_fd >= 0){
671
 
      ret = set_cloexec_flag(dir_fd);
672
 
      if(ret < 0){
673
 
        perror("set_cloexec_flag");
674
 
        exitstatus = EXIT_FAILURE;
675
 
        goto fallback;
676
 
      }
 
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;
677
852
    }
678
853
  }
679
854
  
681
856
  
682
857
  /* Read and execute any executable in the plugin directory*/
683
858
  while(true){
684
 
    dirst = readdir(dir);
 
859
    do {
 
860
      dirst = readdir(dir);
 
861
    } while(dirst == NULL and errno == EINTR);
685
862
    
686
863
    /* All directory entries have been processed */
687
864
    if(dirst == NULL){
688
 
      if (errno == EBADF){
689
 
        perror("readdir");
690
 
        exitstatus = EXIT_FAILURE;
 
865
      if(errno == EBADF){
 
866
        error(0, errno, "readdir");
 
867
        exitstatus = EX_IOERR;
691
868
        goto fallback;
692
869
      }
693
870
      break;
699
876
    {
700
877
      bool bad_name = false;
701
878
      
702
 
      const char const *bad_prefixes[] = { ".", "#", NULL };
 
879
      const char * const bad_prefixes[] = { ".", "#", NULL };
703
880
      
704
 
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
 
881
      const char * const bad_suffixes[] = { "~", "#", ".dpkg-new",
705
882
                                           ".dpkg-old",
 
883
                                           ".dpkg-bak",
706
884
                                           ".dpkg-divert", NULL };
707
 
      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
708
894
        size_t pre_len = strlen(*pre);
709
895
        if((d_name_len >= pre_len)
710
896
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
719
905
      if(bad_name){
720
906
        continue;
721
907
      }
722
 
      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
723
917
        size_t suf_len = strlen(*suf);
724
918
        if((d_name_len >= suf_len)
725
 
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
 
919
           and (strcmp((dirst->d_name) + d_name_len-suf_len, *suf)
726
920
                == 0)){
727
921
          if(debug){
728
922
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
737
931
        continue;
738
932
      }
739
933
    }
740
 
 
 
934
    
741
935
    char *filename;
742
936
    if(plugindir == NULL){
743
 
      ret = asprintf(&filename, PDIR "/%s", dirst->d_name);
 
937
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
 
938
                                             dirst->d_name));
744
939
    } else {
745
 
      ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
940
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s",
 
941
                                             plugindir,
 
942
                                             dirst->d_name));
746
943
    }
747
944
    if(ret < 0){
748
 
      perror("asprintf");
 
945
      error(0, errno, "asprintf");
749
946
      continue;
750
947
    }
751
948
    
752
 
    ret = stat(filename, &st);
753
 
    if (ret == -1){
754
 
      perror("stat");
 
949
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
 
950
    if(ret == -1){
 
951
      error(0, errno, "stat");
755
952
      free(filename);
756
953
      continue;
757
954
    }
758
 
 
 
955
    
759
956
    /* Ignore non-executable files */
760
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
 
957
    if(not S_ISREG(st.st_mode)
 
958
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
761
959
      if(debug){
762
960
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
763
961
                " with bad type or mode\n", filename);
768
966
    
769
967
    plugin *p = getplugin(dirst->d_name);
770
968
    if(p == NULL){
771
 
      perror("getplugin");
 
969
      error(0, errno, "getplugin");
772
970
      free(filename);
773
971
      continue;
774
972
    }
786
984
      if(g != NULL){
787
985
        for(char **a = g->argv + 1; *a != NULL; a++){
788
986
          if(not add_argument(p, *a)){
789
 
            perror("add_argument");
 
987
            error(0, errno, "add_argument");
790
988
          }
791
989
        }
792
990
        /* Add global environment variables */
793
991
        for(char **e = g->environ; *e != NULL; e++){
794
992
          if(not add_environment(p, *e, false)){
795
 
            perror("add_environment");
 
993
            error(0, errno, "add_environment");
796
994
          }
797
995
        }
798
996
      }
803
1001
    if(p->environ[0] != NULL){
804
1002
      for(char **e = environ; *e != NULL; e++){
805
1003
        if(not add_environment(p, *e, false)){
806
 
          perror("add_environment");
 
1004
          error(0, errno, "add_environment");
807
1005
        }
808
1006
      }
809
1007
    }
810
1008
    
811
1009
    int pipefd[2];
812
 
    ret = pipe(pipefd);
813
 
    if (ret == -1){
814
 
      perror("pipe");
815
 
      exitstatus = EXIT_FAILURE;
 
1010
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
 
1011
    if(ret == -1){
 
1012
      error(0, errno, "pipe");
 
1013
      exitstatus = EX_OSERR;
816
1014
      goto fallback;
817
1015
    }
818
1016
    /* Ask OS to automatic close the pipe on exec */
819
1017
    ret = set_cloexec_flag(pipefd[0]);
820
1018
    if(ret < 0){
821
 
      perror("set_cloexec_flag");
822
 
      exitstatus = EXIT_FAILURE;
 
1019
      error(0, errno, "set_cloexec_flag");
 
1020
      exitstatus = EX_OSERR;
823
1021
      goto fallback;
824
1022
    }
825
1023
    ret = set_cloexec_flag(pipefd[1]);
826
1024
    if(ret < 0){
827
 
      perror("set_cloexec_flag");
828
 
      exitstatus = EXIT_FAILURE;
 
1025
      error(0, errno, "set_cloexec_flag");
 
1026
      exitstatus = EX_OSERR;
829
1027
      goto fallback;
830
1028
    }
831
1029
    /* Block SIGCHLD until process is safely in process list */
832
 
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
 
1030
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
 
1031
                                              &sigchld_action.sa_mask,
 
1032
                                              NULL));
833
1033
    if(ret < 0){
834
 
      perror("sigprocmask");
835
 
      exitstatus = EXIT_FAILURE;
 
1034
      error(0, errno, "sigprocmask");
 
1035
      exitstatus = EX_OSERR;
836
1036
      goto fallback;
837
1037
    }
838
1038
    /* Starting a new process to be watched */
839
 
    pid_t pid = fork();
 
1039
    pid_t pid;
 
1040
    do {
 
1041
      pid = fork();
 
1042
    } while(pid == -1 and errno == EINTR);
840
1043
    if(pid == -1){
841
 
      perror("fork");
842
 
      exitstatus = EXIT_FAILURE;
 
1044
      error(0, errno, "fork");
 
1045
      exitstatus = EX_OSERR;
843
1046
      goto fallback;
844
1047
    }
845
1048
    if(pid == 0){
846
1049
      /* this is the child process */
847
1050
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
848
1051
      if(ret < 0){
849
 
        perror("sigaction");
850
 
        _exit(EXIT_FAILURE);
 
1052
        error(0, errno, "sigaction");
 
1053
        _exit(EX_OSERR);
851
1054
      }
852
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1055
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
853
1056
      if(ret < 0){
854
 
        perror("sigprocmask");
855
 
        _exit(EXIT_FAILURE);
 
1057
        error(0, errno, "sigprocmask");
 
1058
        _exit(EX_OSERR);
856
1059
      }
857
 
 
 
1060
      
858
1061
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
859
1062
      if(ret == -1){
860
 
        perror("dup2");
861
 
        _exit(EXIT_FAILURE);
 
1063
        error(0, errno, "dup2");
 
1064
        _exit(EX_OSERR);
862
1065
      }
863
1066
      
864
1067
      if(dirfd(dir) < 0){
866
1069
           above and must now close it manually here. */
867
1070
        closedir(dir);
868
1071
      }
869
 
      if(p->environ[0] == NULL){
870
 
        if(execv(filename, p->argv) < 0){
871
 
          perror("execv");
872
 
          _exit(EXIT_FAILURE);
873
 
        }
874
 
      } else {
875
 
        if(execve(filename, p->argv, p->environ) < 0){
876
 
          perror("execve");
877
 
          _exit(EXIT_FAILURE);
878
 
        }
 
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);
879
1076
      }
880
1077
      /* no return */
881
1078
    }
882
1079
    /* Parent process */
883
 
    close(pipefd[1]);           /* Close unused write end of pipe */
 
1080
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
 
1081
                                             pipe */
884
1082
    free(filename);
885
1083
    plugin *new_plugin = getplugin(dirst->d_name);
886
 
    if (new_plugin == NULL){
887
 
      perror("getplugin");
888
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1084
    if(new_plugin == NULL){
 
1085
      error(0, errno, "getplugin");
 
1086
      ret = (int)(TEMP_FAILURE_RETRY
 
1087
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
 
1088
                               NULL)));
889
1089
      if(ret < 0){
890
 
        perror("sigprocmask");
 
1090
        error(0, errno, "sigprocmask");
891
1091
      }
892
 
      exitstatus = EXIT_FAILURE;
 
1092
      exitstatus = EX_OSERR;
893
1093
      goto fallback;
894
1094
    }
895
1095
    
898
1098
    
899
1099
    /* Unblock SIGCHLD so signal handler can be run if this process
900
1100
       has already completed */
901
 
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
1101
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
 
1102
                                              &sigchld_action.sa_mask,
 
1103
                                              NULL));
902
1104
    if(ret < 0){
903
 
      perror("sigprocmask");
904
 
      exitstatus = EXIT_FAILURE;
 
1105
      error(0, errno, "sigprocmask");
 
1106
      exitstatus = EX_OSERR;
905
1107
      goto fallback;
906
1108
    }
907
1109
    
908
 
    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
909
1124
    
910
 
    if (maxfd < new_plugin->fd){
 
1125
    if(maxfd < new_plugin->fd){
911
1126
      maxfd = new_plugin->fd;
912
1127
    }
913
 
    
914
1128
  }
915
1129
  
916
 
  closedir(dir);
 
1130
  TEMP_FAILURE_RETRY(closedir(dir));
917
1131
  dir = NULL;
918
 
 
 
1132
  free_plugin(getplugin(NULL));
 
1133
  
919
1134
  for(plugin *p = plugin_list; p != NULL; p = p->next){
920
1135
    if(p->pid != 0){
921
1136
      break;
926
1141
      free_plugin_list();
927
1142
    }
928
1143
  }
929
 
 
 
1144
  
930
1145
  /* Main loop while running plugins exist */
931
1146
  while(plugin_list){
932
1147
    fd_set rfds = rfds_all;
933
1148
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
934
 
    if (select_ret == -1){
935
 
      perror("select");
936
 
      exitstatus = EXIT_FAILURE;
 
1149
    if(select_ret == -1 and errno != EINTR){
 
1150
      error(0, errno, "select");
 
1151
      exitstatus = EX_OSERR;
937
1152
      goto fallback;
938
1153
    }
939
1154
    /* OK, now either a process completed, or something can be read
940
1155
       from one of them */
941
1156
    for(plugin *proc = plugin_list; proc != NULL;){
942
1157
      /* Is this process completely done? */
943
 
      if(proc->eof and proc->completed){
 
1158
      if(proc->completed and proc->eof){
944
1159
        /* Only accept the plugin output if it exited cleanly */
945
1160
        if(not WIFEXITED(proc->status)
946
1161
           or WEXITSTATUS(proc->status) != 0){
947
1162
          /* Bad exit by plugin */
948
 
 
 
1163
          
949
1164
          if(debug){
950
1165
            if(WIFEXITED(proc->status)){
951
 
              fprintf(stderr, "Plugin %u exited with status %d\n",
952
 
                      (unsigned int) (proc->pid),
 
1166
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] exited with"
 
1167
                      " status %d\n", proc->name,
 
1168
                      (intmax_t) (proc->pid),
953
1169
                      WEXITSTATUS(proc->status));
954
 
            } else if(WIFSIGNALED(proc->status)) {
955
 
              fprintf(stderr, "Plugin %u killed by signal %d\n",
956
 
                      (unsigned int) (proc->pid),
957
 
                      WTERMSIG(proc->status));
 
1170
            } else if(WIFSIGNALED(proc->status)){
 
1171
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] killed by"
 
1172
                      " signal %d: %s\n", proc->name,
 
1173
                      (intmax_t) (proc->pid),
 
1174
                      WTERMSIG(proc->status),
 
1175
                      strsignal(WTERMSIG(proc->status)));
958
1176
            } else if(WCOREDUMP(proc->status)){
959
 
              fprintf(stderr, "Plugin %d dumped core\n",
960
 
                      (unsigned int) (proc->pid));
 
1177
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
1178
                      " core\n", proc->name, (intmax_t) (proc->pid));
961
1179
            }
962
1180
          }
963
1181
          
964
1182
          /* Remove the plugin */
965
 
          FD_CLR(proc->fd, &rfds_all);
966
 
 
 
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
 
1197
          
967
1198
          /* Block signal while modifying process_list */
968
 
          ret = sigprocmask(SIG_BLOCK, &sigchld_action.sa_mask, NULL);
969
 
          if(ret < 0){
970
 
            perror("sigprocmask");
971
 
            exitstatus = EXIT_FAILURE;
972
 
            goto fallback;
973
 
          }
974
 
          
975
 
          /* We are done modifying process list, so unblock signal */
976
 
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
977
 
                             NULL);
978
 
          if(ret < 0){
979
 
            perror("sigprocmask");
980
 
            exitstatus = EXIT_FAILURE;
981
 
            goto fallback;
982
 
          }
983
 
          
984
 
          if(plugin_list == NULL){
985
 
            break;
 
1199
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
 
1200
                                        (SIG_BLOCK,
 
1201
                                         &sigchld_action.sa_mask,
 
1202
                                         NULL));
 
1203
          if(ret < 0){
 
1204
            error(0, errno, "sigprocmask");
 
1205
            exitstatus = EX_OSERR;
 
1206
            goto fallback;
986
1207
          }
987
1208
          
988
1209
          plugin *next_plugin = proc->next;
989
1210
          free_plugin(proc);
990
1211
          proc = next_plugin;
 
1212
          
 
1213
          /* We are done modifying process list, so unblock signal */
 
1214
          ret = (int)(TEMP_FAILURE_RETRY
 
1215
                      (sigprocmask(SIG_UNBLOCK,
 
1216
                                   &sigchld_action.sa_mask, NULL)));
 
1217
          if(ret < 0){
 
1218
            error(0, errno, "sigprocmask");
 
1219
            exitstatus = EX_OSERR;
 
1220
            goto fallback;
 
1221
          }
 
1222
          
 
1223
          if(plugin_list == NULL){
 
1224
            break;
 
1225
          }
 
1226
          
991
1227
          continue;
992
1228
        }
993
1229
        
994
1230
        /* This process exited nicely, so print its buffer */
995
 
 
 
1231
        
996
1232
        bool bret = print_out_password(proc->buffer,
997
1233
                                       proc->buffer_length);
998
1234
        if(not bret){
999
 
          perror("print_out_password");
1000
 
          exitstatus = EXIT_FAILURE;
 
1235
          error(0, errno, "print_out_password");
 
1236
          exitstatus = EX_IOERR;
1001
1237
        }
1002
1238
        goto fallback;
1003
1239
      }
1004
1240
      
1005
1241
      /* This process has not completed.  Does it have any output? */
1006
 
      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
1007
1259
        /* This process had nothing to say at this time */
1008
1260
        proc = proc->next;
1009
1261
        continue;
1010
1262
      }
1011
1263
      /* Before reading, make the process' data buffer large enough */
1012
1264
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1013
 
        proc->buffer = realloc(proc->buffer, proc->buffer_size
1014
 
                               + (size_t) BUFFER_SIZE);
1015
 
        if (proc->buffer == NULL){
1016
 
          perror("malloc");
1017
 
          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;
1018
1270
          goto fallback;
1019
1271
        }
 
1272
        proc->buffer = new_buffer;
1020
1273
        proc->buffer_size += BUFFER_SIZE;
1021
1274
      }
1022
1275
      /* Read from the process */
1023
 
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
1024
 
                 BUFFER_SIZE);
1025
 
      if(ret < 0){
 
1276
      sret = TEMP_FAILURE_RETRY(read(proc->fd,
 
1277
                                     proc->buffer
 
1278
                                     + proc->buffer_length,
 
1279
                                     BUFFER_SIZE));
 
1280
      if(sret < 0){
1026
1281
        /* Read error from this process; ignore the error */
1027
1282
        proc = proc->next;
1028
1283
        continue;
1029
1284
      }
1030
 
      if(ret == 0){
 
1285
      if(sret == 0){
1031
1286
        /* got EOF */
1032
1287
        proc->eof = true;
1033
1288
      } else {
1034
 
        proc->buffer_length += (size_t) ret;
 
1289
        proc->buffer_length += (size_t) sret;
1035
1290
      }
1036
1291
    }
1037
1292
  }
1038
 
 
1039
 
 
 
1293
  
 
1294
  
1040
1295
 fallback:
1041
1296
  
1042
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
 
1297
  if(plugin_list == NULL or (exitstatus != EXIT_SUCCESS
 
1298
                             and exitstatus != EX_OK)){
1043
1299
    /* Fallback if all plugins failed, none are found or an error
1044
1300
       occured */
1045
1301
    bool bret;
1053
1309
    }
1054
1310
    bret = print_out_password(passwordbuffer, len);
1055
1311
    if(not bret){
1056
 
      perror("print_out_password");
1057
 
      exitstatus = EXIT_FAILURE;
 
1312
      error(0, errno, "print_out_password");
 
1313
      exitstatus = EX_IOERR;
1058
1314
    }
1059
1315
  }
1060
1316
  
1061
1317
  /* Restore old signal handler */
1062
1318
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1063
1319
  if(ret == -1){
1064
 
    perror("sigaction");
1065
 
    exitstatus = EXIT_FAILURE;
 
1320
    error(0, errno, "sigaction");
 
1321
    exitstatus = EX_OSERR;
1066
1322
  }
1067
 
 
 
1323
  
1068
1324
  if(custom_argv != NULL){
1069
1325
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
1070
1326
      free(*arg);
1076
1332
    closedir(dir);
1077
1333
  }
1078
1334
  
1079
 
  /* Free the process list and kill the processes */
 
1335
  /* Kill the processes */
1080
1336
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1081
1337
    if(p->pid != 0){
1082
1338
      close(p->fd);
1083
1339
      ret = kill(p->pid, SIGTERM);
1084
1340
      if(ret == -1 and errno != ESRCH){
1085
1341
        /* Set-uid proccesses might not get closed */
1086
 
        perror("kill");
 
1342
        error(0, errno, "kill");
1087
1343
      }
1088
1344
    }
1089
1345
  }
1090
1346
  
1091
1347
  /* Wait for any remaining child processes to terminate */
1092
 
  do{
 
1348
  do {
1093
1349
    ret = wait(NULL);
1094
1350
  } while(ret >= 0);
1095
1351
  if(errno != ECHILD){
1096
 
    perror("wait");
 
1352
    error(0, errno, "wait");
1097
1353
  }
1098
 
 
 
1354
  
1099
1355
  free_plugin_list();
1100
1356
  
1101
1357
  free(plugindir);