/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-11-09 06:40:29 UTC
  • mto: (24.1.113 mandos)
  • mto: This revision was merged to the branch mainline in revision 238.
  • Revision ID: teddy@fukt.bsnet.se-20081109064029-df71jpoce308cq3v
First steps of a D-Bus interface to the server.

* mandos: Also import "dbus.service".
  (Client): Inherit from "dbus.service.Object", which is a new-style
            class, so inheriting from "object" is no longer necessary.
  (Client.interface): New temporary variable which only exists during
                     class definition.

  (Client.getName, Client.getFingerprint): New D-Bus getter methods.
  (Client.setSecret): New D-Bus setter method.
  (Client._set_timeout): Emit D-Bus signal "TimeoutChanged".
  (Client.getTimeout): New D-Bus getter method.
  (Client.TimeoutChanged): New D-Bus signal.
  (Client._set_interval): Emit D-Bus signal "IntervalChanged".
  (Client.getInterval): New D-Bus getter method.
  (Client.intervalChanged): New D-Bus signal.
  (Client.__init__): Also call "dbus.service.Object.__init__".
  (Client.started): New boolean attribute.
  (Client.start, Client.stop): Update "self.started", and emit D-Bus
                               signal "StateChanged".
  (Client.StateChanged): New D-Bus signal.
  (Client.stop): Use "self.started" instead of misusing "self.secret".
                 Also simplify code by using "getattr" instead of
                 "hasattr".
  (Client.checker_callback): Emit D-Bus signal "CheckerCompleted".
  (Client.CheckerCompleted): New D-Bus signal.
  (Client.bumpTimeout): D-Bus method name for "bump_timeout".
  (Client.start_checker): Emit D-Bus signal "CheckerStarted".
  (Client.CheckerStarted): New D-Bus signal.
  (Client.checkerIsRunning): New D-Bus method.
  (Client.StopChecker): D-Bus method name for "stop_checker".
  (Client.still_valid): First check "self.started".
  (Client.stillValid): D-Bus method name for "still_valid".

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