/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: 2008-09-04 12:38:35 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080904123835-hervuvv4pmpxl8r1
* README: Improved wording.

* initramfs-tools-hook: Do not copy auto-save files from
                        "/etc/mandos/plugins.d".  Do not create key
                        ring files.  Do not reset permissions on
                        things like "$DESTDIR/lib/mandos/plugins.d",
                        which should not be publicly accessible.

* plugin-runner.xml (DESCRIPTION, PLUGINS): Improved grammar.

Show diffs side-by-side

added added

removed removed

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