/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-25 06:44:13 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080825064413-smqg5qwxfvhkeop4
* Makefile (DOCBOOKTOMAN): Only cd to one directory.

* mandos-options.xml (interface): Removed mention of a specific
                                  replaceable.
  (debug): Reworded slightly.

* mandos.conf.xml (OPTIONS): Renamed some replaceable names.

* mandos.xml (SYNOPSIS, OPTIONS): Renamed replaceable of "interface"
                                  from "IF" to "NAME".

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