/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-08-24 10:49:09 UTC
  • mfrom: (24.1.63 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20080824104909-loh761dpgglkvos1
* mandos (fingerprint): Bug fix: Check crtverify.value, not crtverify.

* mandos-keygen (password): Also print "host = ".

* plugins.d/password-request.c (pgp_packet_decrypt): Only print
                                                     detailed result
                                                     of decryption if
                                                     it failed.

Show diffs side-by-side

added added

removed removed

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