/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: 2009-01-13 04:35:19 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090113043519-0yr39snphoegq8l1
* plugin-runner.c: Only space changes.
* plugins.d/mandos-client.c: - '' -
* plugins.d/password-prompt.c: - '' -

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