/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugin-runner.c

* plugin-runner.c (main): Use "sscanf" instead of "strtol"; using the
                          correct type instead of casting.
* plugins.d/mandos-cliend.c (main): Detect an empty string when
                                    parsing DH bits and port number.
* plugins.d/splashy.c (main): Use "sscanf" instead of "strtoul"; using
                              the correct type instead of casting.
* plugins.d/usplash.c (main): - '' -

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