/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 mandos-client.c

* clients.conf.xml: Renamed to "mandos-clients.conf.xml".

* Makefile (DOCBOOKTOMAN, DOCS): New
  (all): Include $(DOCS)
  (%.5: %.xml, %.8: %.xml, %.8mandos: %.xml): New.
  (clean): Also remove $(DOCS)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*  -*- coding: utf-8; mode: c; mode: orgtbl -*- */
 
1
/*  -*- coding: utf-8 -*- */
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
22
21
 * Contact the authors at <mandos@fukt.bsnet.se>.
23
22
 */
24
23
 
25
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
26
 
                                   asprintf(), O_CLOEXEC */
27
 
#include <stddef.h>             /* size_t, NULL */
28
 
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
29
 
                                   EXIT_SUCCESS, realloc() */
30
 
#include <stdbool.h>            /* bool, true, false */
31
 
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
24
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY() */
 
25
 
 
26
#include <stdio.h>              /* popen(), fileno(), fprintf(),
32
27
                                   stderr, STDOUT_FILENO */
33
 
#include <sys/types.h>          /* DIR, fdopendir(), stat(), struct
34
 
                                   stat, waitpid(), WIFEXITED(),
35
 
                                   WEXITSTATUS(), wait(), pid_t,
36
 
                                   uid_t, gid_t, getuid(), getgid(),
37
 
                                   dirfd() */
38
 
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
39
 
                                   FD_SET(), FD_ISSET(), FD_CLR */
40
 
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
41
 
                                   WEXITSTATUS(), WTERMSIG(),
42
 
                                   WCOREDUMP() */
 
28
#include <iso646.h>             /* and, or, not */
 
29
#include <sys/types.h>          /* DIR, opendir(), stat(),
 
30
                                   struct stat, waitpid(),
 
31
                                   WIFEXITED(), WEXITSTATUS(),
 
32
                                   wait() */
 
33
#include <sys/wait.h>           /* wait() */
 
34
#include <dirent.h>             /* DIR, struct dirent, opendir(),
 
35
                                   readdir(), closedir() */
43
36
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
44
 
#include <iso646.h>             /* and, or, not */
45
 
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
46
 
                                   readdir(), closedir(), dirfd() */
47
37
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
48
 
                                   fcntl(), setuid(), setgid(),
49
 
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
50
 
                                   access(), pipe(), fork(), close()
51
 
                                   dup2(), STDOUT_FILENO, _exit(),
52
 
                                   execv(), write(), read(),
53
 
                                   close() */
54
 
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
55
 
                                   FD_CLOEXEC */
56
 
#include <string.h>             /* strsep, strlen(), asprintf(),
57
 
                                   strsignal() */
 
38
                                   fcntl() */
 
39
#include <fcntl.h>              /* fcntl() */
 
40
#include <stddef.h>             /* NULL */
 
41
#include <stdlib.h>             /* EXIT_FAILURE */
 
42
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
 
43
                                   FD_SET(), FD_ISSET() */
 
44
#include <string.h>             /* strlen(), strcpy(), strcat() */
 
45
#include <stdbool.h>            /* true */
 
46
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
47
                                   WEXITSTATUS() */
58
48
#include <errno.h>              /* errno */
59
 
#include <argp.h>               /* struct argp_option, struct
60
 
                                   argp_state, struct argp,
61
 
                                   argp_parse(), ARGP_ERR_UNKNOWN,
62
 
                                   ARGP_KEY_END, ARGP_KEY_ARG,
63
 
                                   error_t */
64
 
#include <signal.h>             /* struct sigaction, sigemptyset(),
65
 
                                   sigaddset(), sigaction(),
66
 
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
67
 
                                   SIG_UNBLOCK, kill(), sig_atomic_t
68
 
                                */
69
 
#include <errno.h>              /* errno, EBADF */
70
 
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
71
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE */
 
49
#include <argp.h>               /* struct argp_option,
 
50
                                   struct argp_state, struct argp,
 
51
                                   argp_parse() */
72
52
 
73
53
#define BUFFER_SIZE 256
74
54
 
75
 
#define PDIR "/lib/mandos/plugins.d"
76
 
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
77
 
 
78
 
const char *argp_program_version = "plugin-runner " VERSION;
79
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
80
 
 
81
 
typedef struct plugin{
82
 
  char *name;                   /* can be NULL or any plugin name */
83
 
  char **argv;
84
 
  int argc;
85
 
  char **environ;
86
 
  int envc;
87
 
  bool disabled;
88
 
  
89
 
  /* Variables used for running processes*/
 
55
struct process;
 
56
 
 
57
typedef struct process{
90
58
  pid_t pid;
91
59
  int fd;
92
60
  char *buffer;
93
61
  size_t buffer_size;
94
62
  size_t buffer_length;
95
63
  bool eof;
96
 
  volatile sig_atomic_t completed;
 
64
  bool completed;
97
65
  int status;
 
66
  struct process *next;
 
67
} process;
 
68
 
 
69
typedef struct plugin{
 
70
  char *name;                   /* can be NULL or any plugin name */
 
71
  char **argv;
 
72
  int argc;
 
73
  bool disabled;
98
74
  struct plugin *next;
99
75
} plugin;
100
76
 
101
 
static plugin *plugin_list = NULL;
102
 
 
103
 
/* Gets an existing plugin based on name,
104
 
   or if none is found, creates a new one */
105
 
static plugin *getplugin(char *name){
106
 
  /* Check for existing plugin with that name */
107
 
  for(plugin *p = plugin_list; p != NULL; p = p->next){
108
 
    if((p->name == name)
109
 
       or (p->name and name and (strcmp(p->name, name) == 0))){
 
77
static plugin *getplugin(char *name, plugin **plugin_list){
 
78
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
 
79
    if ((p->name == name)
 
80
        or (p->name and name and (strcmp(p->name, name) == 0))){
110
81
      return p;
111
82
    }
112
83
  }
113
84
  /* Create a new plugin */
114
 
  plugin *new_plugin = NULL;
115
 
  do {
116
 
    new_plugin = malloc(sizeof(plugin));
117
 
  } while(new_plugin == NULL and errno == EINTR);
118
 
  if(new_plugin == NULL){
119
 
    return NULL;
120
 
  }
121
 
  char *copy_name = NULL;
122
 
  if(name != NULL){
123
 
    do {
124
 
      copy_name = strdup(name);
125
 
    } while(copy_name == NULL and errno == EINTR);
126
 
    if(copy_name == NULL){
127
 
      int e = errno;
128
 
      free(new_plugin);
129
 
      errno = e;
130
 
      return NULL;
131
 
    }
132
 
  }
133
 
  
134
 
  *new_plugin = (plugin){ .name = copy_name,
135
 
                          .argc = 1,
136
 
                          .disabled = false,
137
 
                          .next = plugin_list };
138
 
  
139
 
  do {
140
 
    new_plugin->argv = malloc(sizeof(char *) * 2);
141
 
  } while(new_plugin->argv == NULL and errno == EINTR);
142
 
  if(new_plugin->argv == NULL){
143
 
    int e = errno;
144
 
    free(copy_name);
145
 
    free(new_plugin);
146
 
    errno = e;
147
 
    return NULL;
148
 
  }
149
 
  new_plugin->argv[0] = copy_name;
 
85
  plugin *new_plugin = malloc(sizeof(plugin));
 
86
  if (new_plugin == NULL){
 
87
    perror("malloc");
 
88
    exit(EXIT_FAILURE);
 
89
  }
 
90
  new_plugin->name = name;
 
91
  new_plugin->argv = malloc(sizeof(char *) * 2);
 
92
  if (new_plugin->argv == NULL){
 
93
    perror("malloc");
 
94
    exit(EXIT_FAILURE);
 
95
  }
 
96
  new_plugin->argv[0] = name;
150
97
  new_plugin->argv[1] = NULL;
151
 
  
152
 
  do {
153
 
    new_plugin->environ = malloc(sizeof(char *));
154
 
  } while(new_plugin->environ == NULL and errno == EINTR);
155
 
  if(new_plugin->environ == NULL){
156
 
    int e = errno;
157
 
    free(copy_name);
158
 
    free(new_plugin->argv);
159
 
    free(new_plugin);
160
 
    errno = e;
161
 
    return NULL;
162
 
  }
163
 
  new_plugin->environ[0] = NULL;
164
 
  
 
98
  new_plugin->argc = 1;
 
99
  new_plugin->disabled = false;
 
100
  new_plugin->next = *plugin_list;
165
101
  /* Append the new plugin to the list */
166
 
  plugin_list = new_plugin;
 
102
  *plugin_list = new_plugin;
167
103
  return new_plugin;
168
104
}
169
105
 
170
 
/* Helper function for add_argument and add_environment */
171
 
static bool add_to_char_array(const char *new, char ***array,
172
 
                              int *len){
173
 
  /* Resize the pointed-to array to hold one more pointer */
174
 
  do {
175
 
    *array = realloc(*array, sizeof(char *)
176
 
                     * (size_t) ((*len) + 2));
177
 
  } while(*array == NULL and errno == EINTR);
178
 
  /* Malloc check */
179
 
  if(*array == NULL){
180
 
    return false;
181
 
  }
182
 
  /* Make a copy of the new string */
183
 
  char *copy;
184
 
  do {
185
 
    copy = strdup(new);
186
 
  } while(copy == NULL and errno == EINTR);
187
 
  if(copy == NULL){
188
 
    return false;
189
 
  }
190
 
  /* Insert the copy */
191
 
  (*array)[*len] = copy;
192
 
  (*len)++;
193
 
  /* Add a new terminating NULL pointer to the last element */
194
 
  (*array)[*len] = NULL;
195
 
  return true;
196
 
}
197
 
 
198
 
/* Add to a plugin's argument vector */
199
 
static bool add_argument(plugin *p, const char *arg){
200
 
  if(p == NULL){
201
 
    return false;
202
 
  }
203
 
  return add_to_char_array(arg, &(p->argv), &(p->argc));
204
 
}
205
 
 
206
 
/* Add to a plugin's environment */
207
 
static bool add_environment(plugin *p, const char *def, bool replace){
208
 
  if(p == NULL){
209
 
    return false;
210
 
  }
211
 
  /* namelen = length of name of environment variable */
212
 
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
213
 
  /* Search for this environment variable */
214
 
  for(char **e = p->environ; *e != NULL; e++){
215
 
    if(strncmp(*e, def, namelen + 1) == 0){
216
 
      /* It already exists */
217
 
      if(replace){
218
 
        char *new;
219
 
        do {
220
 
          new = realloc(*e, strlen(def) + 1);
221
 
        } while(new == NULL and errno == EINTR);
222
 
        if(new == NULL){
223
 
          return false;
224
 
        }
225
 
        *e = new;
226
 
        strcpy(*e, def);
227
 
      }
228
 
      return true;
229
 
    }
230
 
  }
231
 
  return add_to_char_array(def, &(p->environ), &(p->envc));
 
106
static void addargument(plugin *p, char *arg){
 
107
  p->argv[p->argc] = arg;
 
108
  p->argv = realloc(p->argv, sizeof(char *) * (size_t)(p->argc + 2));
 
109
  if (p->argv == NULL){
 
110
    perror("malloc");
 
111
    exit(EXIT_FAILURE);
 
112
  }
 
113
  p->argc++;
 
114
  p->argv[p->argc] = NULL;
232
115
}
233
116
 
234
117
/*
235
118
 * Based on the example in the GNU LibC manual chapter 13.13 "File
236
119
 * Descriptor Flags".
237
 
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
 
120
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
238
121
 */
239
 
static int set_cloexec_flag(int fd){
240
 
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
 
122
static int set_cloexec_flag(int fd)
 
123
{
 
124
  int ret = fcntl(fd, F_GETFD, 0);
241
125
  /* If reading the flags failed, return error indication now. */
242
126
  if(ret < 0){
243
127
    return ret;
244
128
  }
245
129
  /* Store modified flag word in the descriptor. */
246
 
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
247
 
                                       ret | FD_CLOEXEC));
 
130
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
248
131
}
249
132
 
250
 
 
251
 
/* Mark processes as completed when they exit, and save their exit
 
133
const char *argp_program_version = "plugbasedclient 0.9";
 
134
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
135
 
 
136
process *process_list = NULL;
 
137
 
 
138
/* Mark a process as completed when it exits, and save its exit
252
139
   status. */
253
 
static void handle_sigchld(__attribute__((unused)) int sig){
254
 
  int old_errno = errno;
255
 
  while(true){
256
 
    plugin *proc = plugin_list;
257
 
    int status;
258
 
    pid_t pid = waitpid(-1, &status, WNOHANG);
259
 
    if(pid == 0){
260
 
      /* Only still running child processes */
261
 
      break;
262
 
    }
263
 
    if(pid == -1){
264
 
      if(errno == ECHILD){
265
 
        /* No child processes */
266
 
        break;
267
 
      }
268
 
      perror("waitpid");
269
 
    }
270
 
    
271
 
    /* A child exited, find it in process_list */
272
 
    while(proc != NULL and proc->pid != pid){
273
 
      proc = proc->next;
274
 
    }
275
 
    if(proc == NULL){
276
 
      /* Process not found in process list */
277
 
      continue;
278
 
    }
279
 
    proc->status = status;
280
 
    proc->completed = 1;
281
 
  }
282
 
  errno = old_errno;
283
 
}
284
 
 
285
 
/* Prints out a password to stdout */
286
 
static bool print_out_password(const char *buffer, size_t length){
287
 
  ssize_t ret;
288
 
  for(size_t written = 0; written < length; written += (size_t)ret){
289
 
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
290
 
                                   length - written));
291
 
    if(ret < 0){
292
 
      return false;
293
 
    }
294
 
  }
295
 
  return true;
296
 
}
297
 
 
298
 
/* Removes and free a plugin from the plugin list */
299
 
static void free_plugin(plugin *plugin_node){
300
 
  
301
 
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
302
 
    free(*arg);
303
 
  }
304
 
  free(plugin_node->argv);
305
 
  for(char **env = plugin_node->environ; *env != NULL; env++){
306
 
    free(*env);
307
 
  }
308
 
  free(plugin_node->environ);
309
 
  free(plugin_node->buffer);
310
 
  
311
 
  /* Removes the plugin from the singly-linked list */
312
 
  if(plugin_node == plugin_list){
313
 
    /* First one - simple */
314
 
    plugin_list = plugin_list->next;
315
 
  } else {
316
 
    /* Second one or later */
317
 
    for(plugin *p = plugin_list; p != NULL; p = p->next){
318
 
      if(p->next == plugin_node){
319
 
        p->next = plugin_node->next;
320
 
        break;
321
 
      }
322
 
    }
323
 
  }
324
 
  
325
 
  free(plugin_node);
326
 
}
327
 
 
328
 
static void free_plugin_list(void){
329
 
  while(plugin_list != NULL){
330
 
    free_plugin(plugin_list);
331
 
  }
 
140
void handle_sigchld(__attribute__((unused)) int sig){
 
141
  process *proc = process_list;
 
142
  int status;
 
143
  pid_t pid = wait(&status);
 
144
  while(proc != NULL and proc->pid != pid){
 
145
    proc = proc->next;
 
146
  }
 
147
  if(proc == NULL){
 
148
    /* Process not found in process list */
 
149
    return;
 
150
  }
 
151
  proc->status = status;
 
152
  proc->completed = true;
332
153
}
333
154
 
334
155
int main(int argc, char *argv[]){
335
 
  char *plugindir = NULL;
336
 
  char *argfile = NULL;
337
 
  FILE *conffp;
 
156
  const char *plugindir = "/conf/conf.d/mandos/plugins.d";
338
157
  size_t d_name_len;
339
158
  DIR *dir = NULL;
340
159
  struct dirent *dirst;
341
160
  struct stat st;
342
161
  fd_set rfds_all;
343
162
  int ret, maxfd = 0;
344
 
  ssize_t sret;
345
163
  uid_t uid = 65534;
346
164
  gid_t gid = 65534;
347
165
  bool debug = false;
349
167
  struct sigaction old_sigchld_action;
350
168
  struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
351
169
                                      .sa_flags = SA_NOCLDSTOP };
352
 
  char **custom_argv = NULL;
353
 
  int custom_argc = 0;
 
170
  char *plus_options = NULL;
 
171
  char **plus_argv = NULL;
354
172
  
355
173
  /* Establish a signal handler */
356
174
  sigemptyset(&sigchld_action.sa_mask);
357
175
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
358
 
  if(ret == -1){
 
176
  if(ret < 0){
359
177
    perror("sigaddset");
360
 
    exitstatus = EXIT_FAILURE;
361
 
    goto fallback;
 
178
    exit(EXIT_FAILURE);
362
179
  }
363
180
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
364
 
  if(ret == -1){
 
181
  if(ret < 0){
365
182
    perror("sigaction");
366
 
    exitstatus = EXIT_FAILURE;
367
 
    goto fallback;
 
183
    exit(EXIT_FAILURE);
368
184
  }
369
185
  
370
186
  /* The options we understand. */
372
188
    { .name = "global-options", .key = 'g',
373
189
      .arg = "OPTION[,OPTION[,...]]",
374
190
      .doc = "Options passed to all plugins" },
375
 
    { .name = "global-env", .key = 'G',
376
 
      .arg = "VAR=value",
377
 
      .doc = "Environment variable passed to all plugins" },
378
191
    { .name = "options-for", .key = 'o',
379
192
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
380
193
      .doc = "Options passed only to specified plugin" },
381
 
    { .name = "env-for", .key = 'E',
382
 
      .arg = "PLUGIN:ENV=value",
383
 
      .doc = "Environment variable passed to specified plugin" },
384
194
    { .name = "disable", .key = 'd',
385
195
      .arg = "PLUGIN",
386
196
      .doc = "Disable a specific plugin", .group = 1 },
387
 
    { .name = "enable", .key = 'e',
388
 
      .arg = "PLUGIN",
389
 
      .doc = "Enable a specific plugin", .group = 1 },
390
197
    { .name = "plugin-dir", .key = 128,
391
198
      .arg = "DIRECTORY",
392
199
      .doc = "Specify a different plugin directory", .group = 2 },
393
 
    { .name = "config-file", .key = 129,
394
 
      .arg = "FILE",
395
 
      .doc = "Specify a different configuration file", .group = 2 },
396
 
    { .name = "userid", .key = 130,
397
 
      .arg = "ID", .flags = 0,
398
 
      .doc = "User ID the plugins will run as", .group = 3 },
399
 
    { .name = "groupid", .key = 131,
400
 
      .arg = "ID", .flags = 0,
401
 
      .doc = "Group ID the plugins will run as", .group = 3 },
402
 
    { .name = "debug", .key = 132,
403
 
      .doc = "Debug mode", .group = 4 },
404
 
    /*
405
 
     * These reproduce what we would get without ARGP_NO_HELP
406
 
     */
407
 
    { .name = "help", .key = '?',
408
 
      .doc = "Give this help list", .group = -1 },
409
 
    { .name = "usage", .key = -3,
410
 
      .doc = "Give a short usage message", .group = -1 },
411
 
    { .name = "version", .key = 'V',
412
 
      .doc = "Print program version", .group = -1 },
 
200
    { .name = "userid", .key = 129,
 
201
      .arg = "ID", .flags = 0,
 
202
      .doc = "User ID the plugins will run as", .group = 2 },
 
203
    { .name = "groupid", .key = 130,
 
204
      .arg = "ID", .flags = 0,
 
205
      .doc = "Group ID the plugins will run as", .group = 2 },
 
206
    { .name = "debug", .key = 131,
 
207
      .doc = "Debug mode", .group = 3 },
413
208
    { .name = NULL }
414
209
  };
415
210
  
416
 
  error_t parse_opt(int key, char *arg, struct argp_state *state){
417
 
    errno = 0;
418
 
    switch(key){
419
 
      char *tmp;
420
 
      intmax_t tmpmax;
421
 
    case 'g':                   /* --global-options */
422
 
      {
423
 
        char *plugin_option;
424
 
        while((plugin_option = strsep(&arg, ",")) != NULL){
425
 
          if(not add_argument(getplugin(NULL), plugin_option)){
426
 
            break;
427
 
          }
428
 
        }
429
 
      }
430
 
      break;
431
 
    case 'G':                   /* --global-env */
432
 
      add_environment(getplugin(NULL), arg, true);
433
 
      break;
434
 
    case 'o':                   /* --options-for */
435
 
      {
436
 
        char *option_list = strchr(arg, ':');
437
 
        if(option_list == NULL){
438
 
          argp_error(state, "No colon in \"%s\"", arg);
439
 
          errno = EINVAL;
440
 
          break;
441
 
        }
442
 
        *option_list = '\0';
443
 
        option_list++;
444
 
        if(arg[0] == '\0'){
445
 
          argp_error(state, "Empty plugin name");
446
 
          errno = EINVAL;
447
 
          break;
448
 
        }
449
 
        char *option;
450
 
        while((option = strsep(&option_list, ",")) != NULL){
451
 
          if(not add_argument(getplugin(arg), option)){
452
 
            break;
453
 
          }
454
 
        }
455
 
      }
456
 
      break;
457
 
    case 'E':                   /* --env-for */
458
 
      {
459
 
        char *envdef = strchr(arg, ':');
460
 
        if(envdef == NULL){
461
 
          argp_error(state, "No colon in \"%s\"", arg);
462
 
          errno = EINVAL;
463
 
          break;
464
 
        }
465
 
        *envdef = '\0';
466
 
        envdef++;
467
 
        if(arg[0] == '\0'){
468
 
          argp_error(state, "Empty plugin name");
469
 
          errno = EINVAL;
470
 
          break;
471
 
        }
472
 
        add_environment(getplugin(arg), envdef, true);
473
 
      }
474
 
      break;
475
 
    case 'd':                   /* --disable */
476
 
      {
477
 
        plugin *p = getplugin(arg);
478
 
        if(p != NULL){
479
 
          p->disabled = true;
480
 
        }
481
 
      }
482
 
      break;
483
 
    case 'e':                   /* --enable */
484
 
      {
485
 
        plugin *p = getplugin(arg);
486
 
        if(p != NULL){
487
 
          p->disabled = false;
488
 
        }
489
 
      }
490
 
      break;
491
 
    case 128:                   /* --plugin-dir */
492
 
      free(plugindir);
493
 
      plugindir = strdup(arg);
494
 
      break;
495
 
    case 129:                   /* --config-file */
496
 
      /* This is already done by parse_opt_config_file() */
497
 
      break;
498
 
    case 130:                   /* --userid */
499
 
      tmpmax = strtoimax(arg, &tmp, 10);
500
 
      if(errno != 0 or tmp == arg or *tmp != '\0'
501
 
         or tmpmax != (uid_t)tmpmax){
502
 
        argp_error(state, "Bad user ID number: \"%s\", using %"
503
 
                   PRIdMAX, arg, (intmax_t)uid);
504
 
        break;
505
 
      }
506
 
      uid = (uid_t)tmpmax;
507
 
      break;
508
 
    case 131:                   /* --groupid */
509
 
      tmpmax = strtoimax(arg, &tmp, 10);
510
 
      if(errno != 0 or tmp == arg or *tmp != '\0'
511
 
         or tmpmax != (gid_t)tmpmax){
512
 
        argp_error(state, "Bad group ID number: \"%s\", using %"
513
 
                   PRIdMAX, arg, (intmax_t)gid);
514
 
        break;
515
 
      }
516
 
      gid = (gid_t)tmpmax;
517
 
      break;
518
 
    case 132:                   /* --debug */
 
211
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
 
212
    /* Get the INPUT argument from `argp_parse', which we know is a
 
213
       pointer to our plugin list pointer. */
 
214
    plugin **plugins = state->input;
 
215
    switch (key) {
 
216
    case 'g':
 
217
      if (arg != NULL){
 
218
        char *p = strtok(arg, ",");
 
219
        do{
 
220
          addargument(getplugin(NULL, plugins), p);
 
221
          p = strtok(NULL, ",");
 
222
        } while (p != NULL);
 
223
      }
 
224
      break;
 
225
    case 'o':
 
226
      if (arg != NULL){
 
227
        char *name = strtok(arg, ":");
 
228
        char *p = strtok(NULL, ":");
 
229
        if(p != NULL){
 
230
          p = strtok(p, ",");
 
231
          do{
 
232
            addargument(getplugin(name, plugins), p);
 
233
            p = strtok(NULL, ",");
 
234
          } while (p != NULL);
 
235
        }
 
236
      }
 
237
      break;
 
238
    case 'd':
 
239
      if (arg != NULL){
 
240
        getplugin(arg, plugins)->disabled = true;
 
241
      }
 
242
      break;
 
243
    case 128:
 
244
      plugindir = arg;
 
245
      break;
 
246
    case 129:
 
247
      uid = (uid_t)strtol(arg, NULL, 10);
 
248
      break;
 
249
    case 130:
 
250
      gid = (gid_t)strtol(arg, NULL, 10);
 
251
      break;
 
252
    case 131:
519
253
      debug = true;
520
254
      break;
521
 
      /*
522
 
       * These reproduce what we would get without ARGP_NO_HELP
523
 
       */
524
 
    case '?':                   /* --help */
525
 
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
526
 
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
527
 
    case -3:                    /* --usage */
528
 
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
529
 
      argp_state_help(state, state->out_stream,
530
 
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
531
 
    case 'V':                   /* --version */
532
 
      fprintf(state->out_stream, "%s\n", argp_program_version);
533
 
      exit(EXIT_SUCCESS);
534
 
      break;
535
 
/*
536
 
 * When adding more options before this line, remember to also add a
537
 
 * "case" to the "parse_opt_config_file" function below.
538
 
 */
539
255
    case ARGP_KEY_ARG:
540
 
      /* Cryptsetup always passes an argument, which is an empty
541
 
         string if "none" was specified in /etc/crypttab.  So if
542
 
         argument was empty, we ignore it silently. */
543
 
      if(arg[0] == '\0'){
544
 
        break;
 
256
      if(plus_options != NULL or arg == NULL or arg[0] != '+'){
 
257
        argp_usage (state);
545
258
      }
546
 
    default:
547
 
      return ARGP_ERR_UNKNOWN;
548
 
    }
549
 
    return errno;               /* Set to 0 at start */
550
 
  }
551
 
  
552
 
  /* This option parser is the same as parse_opt() above, except it
553
 
     ignores everything but the --config-file option. */
554
 
  error_t parse_opt_config_file(int key, char *arg,
555
 
                                __attribute__((unused))
556
 
                                struct argp_state *state){
557
 
    errno = 0;
558
 
    switch(key){
559
 
    case 'g':                   /* --global-options */
560
 
    case 'G':                   /* --global-env */
561
 
    case 'o':                   /* --options-for */
562
 
    case 'E':                   /* --env-for */
563
 
    case 'd':                   /* --disable */
564
 
    case 'e':                   /* --enable */
565
 
    case 128:                   /* --plugin-dir */
566
 
      break;
567
 
    case 129:                   /* --config-file */
568
 
      free(argfile);
569
 
      argfile = strdup(arg);
570
 
      break;
571
 
    case 130:                   /* --userid */
572
 
    case 131:                   /* --groupid */
573
 
    case 132:                   /* --debug */
574
 
    case '?':                   /* --help */
575
 
    case -3:                    /* --usage */
576
 
    case 'V':                   /* --version */
577
 
    case ARGP_KEY_ARG:
578
 
      break;
579
 
    default:
580
 
      return ARGP_ERR_UNKNOWN;
581
 
    }
582
 
    return errno;
583
 
  }
584
 
  
585
 
  struct argp argp = { .options = options,
586
 
                       .parser = parse_opt_config_file,
587
 
                       .args_doc = "",
 
259
      plus_options = arg;
 
260
      break;
 
261
    case ARGP_KEY_END:
 
262
      break;
 
263
    default:
 
264
      return ARGP_ERR_UNKNOWN;
 
265
    }
 
266
    return 0;
 
267
  }
 
268
  
 
269
  plugin *plugin_list = NULL;
 
270
  
 
271
  struct argp argp = { .options = options, .parser = parse_opt,
 
272
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
588
273
                       .doc = "Mandos plugin runner -- Run plugins" };
589
274
  
590
 
  /* Parse using parse_opt_config_file() in order to get the custom
591
 
     config file location, if any. */
592
 
  ret = argp_parse(&argp, argc, argv,
593
 
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
594
 
                   NULL, NULL);
595
 
  switch(ret){
596
 
  case 0:
597
 
    break;
598
 
  case ENOMEM:
599
 
  default:
600
 
    errno = ret;
601
 
    perror("argp_parse");
602
 
    exitstatus = EX_OSERR;
603
 
    goto fallback;
604
 
  case EINVAL:
605
 
    exitstatus = EX_USAGE;
606
 
    goto fallback;
607
 
  }
608
 
  
609
 
  /* Reset to the normal argument parser */
610
 
  argp.parser = parse_opt;
611
 
  
612
 
  /* Open the configfile if available */
613
 
  if(argfile == NULL){
614
 
    conffp = fopen(AFILE, "r");
615
 
  } else {
616
 
    conffp = fopen(argfile, "r");
617
 
  }
618
 
  if(conffp != NULL){
619
 
    char *org_line = NULL;
620
 
    char *p, *arg, *new_arg, *line;
621
 
    size_t size = 0;
622
 
    const char whitespace_delims[] = " \r\t\f\v\n";
623
 
    const char comment_delim[] = "#";
624
 
    
625
 
    custom_argc = 1;
626
 
    custom_argv = malloc(sizeof(char*) * 2);
627
 
    if(custom_argv == NULL){
 
275
  argp_parse (&argp, argc, argv, 0, 0, &plugin_list);  
 
276
  
 
277
  if(plus_options){
 
278
    /* This is a mangled argument in the form of
 
279
     "+--option+--other-option=parameter+--yet-another-option", etc */
 
280
    /* Make new argc and argv vars, and call argp_parse() again. */
 
281
    plus_options++;             /* skip the first '+' character */
 
282
    const char delims[] = "+";
 
283
    char *arg;
 
284
    int new_argc = 1;
 
285
    plus_argv = malloc(sizeof(char*) * 2);
 
286
    if(plus_argv == NULL){
628
287
      perror("malloc");
629
288
      exitstatus = EXIT_FAILURE;
630
 
      goto fallback;
631
 
    }
632
 
    custom_argv[0] = argv[0];
633
 
    custom_argv[1] = NULL;
634
 
    
635
 
    /* for each line in the config file, strip whitespace and ignore
636
 
       commented text */
637
 
    while(true){
638
 
      sret = getline(&org_line, &size, conffp);
639
 
      if(sret == -1){
640
 
        break;
641
 
      }
642
 
      
643
 
      line = org_line;
644
 
      arg = strsep(&line, comment_delim);
645
 
      while((p = strsep(&arg, whitespace_delims)) != NULL){
646
 
        if(p[0] == '\0'){
647
 
          continue;
648
 
        }
649
 
        new_arg = strdup(p);
650
 
        if(new_arg == NULL){
651
 
          perror("strdup");
652
 
          exitstatus = EXIT_FAILURE;
653
 
          free(org_line);
654
 
          goto fallback;
655
 
        }
656
 
        
657
 
        custom_argc += 1;
658
 
        custom_argv = realloc(custom_argv, sizeof(char *)
659
 
                              * ((unsigned int) custom_argc + 1));
660
 
        if(custom_argv == NULL){
661
 
          perror("realloc");
662
 
          exitstatus = EXIT_FAILURE;
663
 
          free(org_line);
664
 
          goto fallback;
665
 
        }
666
 
        custom_argv[custom_argc-1] = new_arg;
667
 
        custom_argv[custom_argc] = NULL;
668
 
      }
669
 
    }
670
 
    do {
671
 
      ret = fclose(conffp);
672
 
    } while(ret == EOF and errno == EINTR);
673
 
    if(ret == EOF){
674
 
      perror("fclose");
675
 
      exitstatus = EXIT_FAILURE;
676
 
      goto fallback;
677
 
    }
678
 
    free(org_line);
679
 
  } else {
680
 
    /* Check for harmful errors and go to fallback. Other errors might
681
 
       not affect opening plugins */
682
 
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
683
 
      perror("fopen");
684
 
      exitstatus = EXIT_FAILURE;
685
 
      goto fallback;
686
 
    }
687
 
  }
688
 
  /* If there were any arguments from the configuration file, pass
689
 
     them to parser as command line arguments */
690
 
  if(custom_argv != NULL){
691
 
    ret = argp_parse(&argp, custom_argc, custom_argv,
692
 
                     ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
693
 
                     NULL, NULL);
694
 
    switch(ret){
695
 
    case 0:
696
 
      break;
697
 
    case ENOMEM:
698
 
    default:
699
 
      errno = ret;
700
 
      perror("argp_parse");
701
 
      exitstatus = EX_OSERR;
702
 
      goto fallback;
703
 
    case EINVAL:
704
 
      exitstatus = EX_CONFIG;
705
 
      goto fallback;
706
 
    }
707
 
  }
708
 
  
709
 
  /* Parse actual command line arguments, to let them override the
710
 
     config file */
711
 
  ret = argp_parse(&argp, argc, argv,
712
 
                   ARGP_IN_ORDER | ARGP_NO_EXIT | ARGP_NO_HELP,
713
 
                   NULL, NULL);
714
 
  switch(ret){
715
 
  case 0:
716
 
    break;
717
 
  case ENOMEM:
718
 
  default:
719
 
    errno = ret;
720
 
    perror("argp_parse");
721
 
    exitstatus = EX_OSERR;
722
 
    goto fallback;
723
 
  case EINVAL:
724
 
    exitstatus = EX_USAGE;
725
 
    goto fallback;
 
289
      goto end;
 
290
    }
 
291
    plus_argv[0] = argv[0];
 
292
    plus_argv[1] = NULL;
 
293
    arg = strtok(plus_options, delims); /* Get first argument */
 
294
    while(arg != NULL){
 
295
      new_argc++;
 
296
      plus_argv = realloc(plus_argv, sizeof(char *)
 
297
                         * ((unsigned int) new_argc + 1));
 
298
      if(plus_argv == NULL){
 
299
        perror("malloc");
 
300
        exitstatus = EXIT_FAILURE;
 
301
        goto end;
 
302
      }
 
303
      plus_argv[new_argc-1] = arg;
 
304
      plus_argv[new_argc] = NULL;
 
305
      arg = strtok(NULL, delims); /* Get next argument */
 
306
    }
 
307
    argp_parse (&argp, new_argc, plus_argv, 0, 0, &plugin_list);  
726
308
  }
727
309
  
728
310
  if(debug){
732
314
      for(char **a = p->argv; *a != NULL; a++){
733
315
        fprintf(stderr, "\tArg: %s\n", *a);
734
316
      }
735
 
      fprintf(stderr, "...and %d environment variables\n", p->envc);
736
 
      for(char **a = p->environ; *a != NULL; a++){
737
 
        fprintf(stderr, "\t%s\n", *a);
738
 
      }
739
317
    }
740
318
  }
741
319
  
742
 
  /* Strip permissions down to nobody */
 
320
  ret = setuid(uid);
 
321
  if (ret == -1){
 
322
    perror("setuid");
 
323
  }
 
324
  
743
325
  setgid(gid);
744
 
  if(ret == -1){
 
326
  if (ret == -1){
745
327
    perror("setgid");
746
328
  }
747
 
  ret = setuid(uid);
748
 
  if(ret == -1){
749
 
    perror("setuid");
 
329
  
 
330
  dir = opendir(plugindir);
 
331
  if(dir == NULL){
 
332
    perror("Could not open plugin dir");
 
333
    exitstatus = EXIT_FAILURE;
 
334
    goto end;
750
335
  }
751
336
  
752
 
  /* Open plugin directory with close_on_exec flag */
 
337
  /* Set the FD_CLOEXEC flag on the directory, if possible */
753
338
  {
754
 
    int dir_fd = -1;
755
 
    if(plugindir == NULL){
756
 
      dir_fd = open(PDIR, O_RDONLY |
757
 
#ifdef O_CLOEXEC
758
 
                    O_CLOEXEC
759
 
#else  /* not O_CLOEXEC */
760
 
                    0
761
 
#endif  /* not O_CLOEXEC */
762
 
                    );
763
 
    } else {
764
 
      dir_fd = open(plugindir, O_RDONLY |
765
 
#ifdef O_CLOEXEC
766
 
                    O_CLOEXEC
767
 
#else  /* not O_CLOEXEC */
768
 
                    0
769
 
#endif  /* not O_CLOEXEC */
770
 
                    );
771
 
    }
772
 
    if(dir_fd == -1){
773
 
      perror("Could not open plugin dir");
774
 
      exitstatus = EXIT_FAILURE;
775
 
      goto fallback;
776
 
    }
777
 
    
778
 
#ifndef O_CLOEXEC
779
 
  /* Set the FD_CLOEXEC flag on the directory */
780
 
    ret = set_cloexec_flag(dir_fd);
781
 
    if(ret < 0){
782
 
      perror("set_cloexec_flag");
783
 
      TEMP_FAILURE_RETRY(close(dir_fd));
784
 
      exitstatus = EXIT_FAILURE;
785
 
      goto fallback;
786
 
    }
787
 
#endif  /* O_CLOEXEC */
788
 
    
789
 
    dir = fdopendir(dir_fd);
790
 
    if(dir == NULL){
791
 
      perror("Could not open plugin dir");
792
 
      TEMP_FAILURE_RETRY(close(dir_fd));
793
 
      exitstatus = EXIT_FAILURE;
794
 
      goto fallback;
 
339
    int dir_fd = dirfd(dir);
 
340
    if(dir_fd >= 0){
 
341
      ret = set_cloexec_flag(dir_fd);
 
342
      if(ret < 0){
 
343
        perror("set_cloexec_flag");
 
344
        exitstatus = EXIT_FAILURE;
 
345
        goto end;
 
346
      }
795
347
    }
796
348
  }
797
349
  
798
350
  FD_ZERO(&rfds_all);
799
351
  
800
 
  /* Read and execute any executable in the plugin directory*/
801
352
  while(true){
802
 
    do {
803
 
      dirst = readdir(dir);
804
 
    } while(dirst == NULL and errno == EINTR);
 
353
    dirst = readdir(dir);
805
354
    
806
 
    /* All directory entries have been processed */
 
355
    // All directory entries have been processed
807
356
    if(dirst == NULL){
808
 
      if(errno == EBADF){
809
 
        perror("readdir");
810
 
        exitstatus = EXIT_FAILURE;
811
 
        goto fallback;
812
 
      }
813
357
      break;
814
358
    }
815
359
    
816
360
    d_name_len = strlen(dirst->d_name);
817
361
    
818
 
    /* Ignore dotfiles, backup files and other junk */
 
362
    // Ignore dotfiles, backup files and other junk
819
363
    {
820
364
      bool bad_name = false;
821
365
      
823
367
      
824
368
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
825
369
                                           ".dpkg-old",
826
 
                                           ".dpkg-bak",
827
370
                                           ".dpkg-divert", NULL };
828
371
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
829
372
        size_t pre_len = strlen(*pre);
837
380
          break;
838
381
        }
839
382
      }
 
383
      
840
384
      if(bad_name){
841
385
        continue;
842
386
      }
 
387
      
843
388
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
844
389
        size_t suf_len = strlen(*suf);
845
390
        if((d_name_len >= suf_len)
859
404
      }
860
405
    }
861
406
    
862
 
    char *filename;
863
 
    if(plugindir == NULL){
864
 
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
865
 
                                             dirst->d_name));
866
 
    } else {
867
 
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s",
868
 
                                             plugindir,
869
 
                                             dirst->d_name));
870
 
    }
871
 
    if(ret < 0){
872
 
      perror("asprintf");
873
 
      continue;
874
 
    }
875
 
    
876
 
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
877
 
    if(ret == -1){
878
 
      perror("stat");
879
 
      free(filename);
880
 
      continue;
881
 
    }
882
 
    
883
 
    /* Ignore non-executable files */
884
 
    if(not S_ISREG(st.st_mode)
885
 
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
 
407
    char *filename = malloc(d_name_len + strlen(plugindir) + 2);
 
408
    if (filename == NULL){
 
409
      perror("malloc");
 
410
      exitstatus = EXIT_FAILURE;
 
411
      goto end;
 
412
    }
 
413
    strcpy(filename, plugindir); /* Spurious warning */
 
414
    strcat(filename, "/");      /* Spurious warning */
 
415
    strcat(filename, dirst->d_name); /* Spurious warning */
 
416
    
 
417
    stat(filename, &st);
 
418
    
 
419
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
886
420
      if(debug){
887
421
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
888
422
                " with bad type or mode\n", filename);
890
424
      free(filename);
891
425
      continue;
892
426
    }
893
 
    
894
 
    plugin *p = getplugin(dirst->d_name);
895
 
    if(p == NULL){
896
 
      perror("getplugin");
897
 
      free(filename);
898
 
      continue;
899
 
    }
900
 
    if(p->disabled){
 
427
    if(getplugin(dirst->d_name, &plugin_list)->disabled){
901
428
      if(debug){
902
429
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
903
430
                dirst->d_name);
905
432
      free(filename);
906
433
      continue;
907
434
    }
 
435
    plugin *p = getplugin(dirst->d_name, &plugin_list);
908
436
    {
909
437
      /* Add global arguments to argument list for this plugin */
910
 
      plugin *g = getplugin(NULL);
911
 
      if(g != NULL){
912
 
        for(char **a = g->argv + 1; *a != NULL; a++){
913
 
          if(not add_argument(p, *a)){
914
 
            perror("add_argument");
915
 
          }
916
 
        }
917
 
        /* Add global environment variables */
918
 
        for(char **e = g->environ; *e != NULL; e++){
919
 
          if(not add_environment(p, *e, false)){
920
 
            perror("add_environment");
921
 
          }
922
 
        }
923
 
      }
924
 
    }
925
 
    /* If this plugin has any environment variables, we will call
926
 
       using execve and need to duplicate the environment from this
927
 
       process, too. */
928
 
    if(p->environ[0] != NULL){
929
 
      for(char **e = environ; *e != NULL; e++){
930
 
        if(not add_environment(p, *e, false)){
931
 
          perror("add_environment");
932
 
        }
933
 
      }
934
 
    }
935
 
    
936
 
    int pipefd[2];
937
 
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
938
 
    if(ret == -1){
 
438
      plugin *g = getplugin(NULL, &plugin_list);
 
439
      for(char **a = g->argv + 1; *a != NULL; a++){
 
440
        addargument(p, *a);
 
441
      }
 
442
    }
 
443
    int pipefd[2]; 
 
444
    ret = pipe(pipefd);
 
445
    if (ret == -1){
939
446
      perror("pipe");
940
447
      exitstatus = EXIT_FAILURE;
941
 
      goto fallback;
 
448
      goto end;
942
449
    }
943
 
    /* Ask OS to automatic close the pipe on exec */
944
450
    ret = set_cloexec_flag(pipefd[0]);
945
451
    if(ret < 0){
946
452
      perror("set_cloexec_flag");
947
453
      exitstatus = EXIT_FAILURE;
948
 
      goto fallback;
 
454
      goto end;
949
455
    }
950
456
    ret = set_cloexec_flag(pipefd[1]);
951
457
    if(ret < 0){
952
458
      perror("set_cloexec_flag");
953
459
      exitstatus = EXIT_FAILURE;
954
 
      goto fallback;
 
460
      goto end;
955
461
    }
956
462
    /* Block SIGCHLD until process is safely in process list */
957
 
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
958
 
                                              &sigchld_action.sa_mask,
959
 
                                              NULL));
 
463
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
960
464
    if(ret < 0){
961
465
      perror("sigprocmask");
962
466
      exitstatus = EXIT_FAILURE;
963
 
      goto fallback;
964
 
    }
965
 
    /* Starting a new process to be watched */
966
 
    pid_t pid;
967
 
    do {
968
 
      pid = fork();
969
 
    } while(pid == -1 and errno == EINTR);
970
 
    if(pid == -1){
971
 
      perror("fork");
972
 
      exitstatus = EXIT_FAILURE;
973
 
      goto fallback;
974
 
    }
 
467
      goto end;
 
468
    }
 
469
    // Starting a new process to be watched
 
470
    pid_t pid = fork();
975
471
    if(pid == 0){
976
472
      /* this is the child process */
977
473
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
979
475
        perror("sigaction");
980
476
        _exit(EXIT_FAILURE);
981
477
      }
982
 
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
478
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
983
479
      if(ret < 0){
984
480
        perror("sigprocmask");
985
481
        _exit(EXIT_FAILURE);
986
482
      }
987
 
      
988
 
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
989
 
      if(ret == -1){
990
 
        perror("dup2");
991
 
        _exit(EXIT_FAILURE);
992
 
      }
 
483
      dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
993
484
      
994
485
      if(dirfd(dir) < 0){
995
486
        /* If dir has no file descriptor, we could not set FD_CLOEXEC
996
487
           above and must now close it manually here. */
997
488
        closedir(dir);
998
489
      }
999
 
      if(p->environ[0] == NULL){
1000
 
        if(execv(filename, p->argv) < 0){
1001
 
          perror("execv");
1002
 
          _exit(EXIT_FAILURE);
1003
 
        }
1004
 
      } else {
1005
 
        if(execve(filename, p->argv, p->environ) < 0){
1006
 
          perror("execve");
1007
 
          _exit(EXIT_FAILURE);
1008
 
        }
 
490
      if(execv(filename, p->argv) < 0){
 
491
        perror("execv");
 
492
        _exit(EXIT_FAILURE);
1009
493
      }
1010
494
      /* no return */
1011
495
    }
1012
 
    /* Parent process */
1013
 
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
1014
 
                                             pipe */
 
496
    /* parent process */
1015
497
    free(filename);
1016
 
    plugin *new_plugin = getplugin(dirst->d_name);
1017
 
    if(new_plugin == NULL){
1018
 
      perror("getplugin");
1019
 
      ret = (int)(TEMP_FAILURE_RETRY
1020
 
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
1021
 
                               NULL)));
 
498
    close(pipefd[1]);           /* close unused write end of pipe */
 
499
    process *new_process = malloc(sizeof(process));
 
500
    if (new_process == NULL){
 
501
      perror("malloc");
 
502
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
1022
503
      if(ret < 0){
1023
 
        perror("sigprocmask");
 
504
        perror("sigprocmask");
1024
505
      }
1025
506
      exitstatus = EXIT_FAILURE;
1026
 
      goto fallback;
 
507
      goto end;
1027
508
    }
1028
509
    
1029
 
    new_plugin->pid = pid;
1030
 
    new_plugin->fd = pipefd[0];
1031
 
    
 
510
    *new_process = (struct process){ .pid = pid,
 
511
                                     .fd = pipefd[0],
 
512
                                     .next = process_list };
 
513
    // List handling
 
514
    process_list = new_process;
1032
515
    /* Unblock SIGCHLD so signal handler can be run if this process
1033
516
       has already completed */
1034
 
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
1035
 
                                              &sigchld_action.sa_mask,
1036
 
                                              NULL));
 
517
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
1037
518
    if(ret < 0){
1038
519
      perror("sigprocmask");
1039
520
      exitstatus = EXIT_FAILURE;
1040
 
      goto fallback;
1041
 
    }
1042
 
    
1043
 
    FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from
1044
 
                                          -Wconversion */
1045
 
    
1046
 
    if(maxfd < new_plugin->fd){
1047
 
      maxfd = new_plugin->fd;
1048
 
    }
1049
 
  }
1050
 
  
1051
 
  TEMP_FAILURE_RETRY(closedir(dir));
 
521
      goto end;
 
522
    }
 
523
    
 
524
    FD_SET(new_process->fd, &rfds_all);
 
525
    
 
526
    if (maxfd < new_process->fd){
 
527
      maxfd = new_process->fd;
 
528
    }
 
529
    
 
530
  }
 
531
  
 
532
  /* Free the plugin list */
 
533
  for(plugin *next; plugin_list != NULL; plugin_list = next){
 
534
    next = plugin_list->next;
 
535
    free(plugin_list->argv);
 
536
    free(plugin_list);
 
537
  }
 
538
  
 
539
  closedir(dir);
1052
540
  dir = NULL;
1053
 
  free_plugin(getplugin(NULL));
1054
541
  
1055
 
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1056
 
    if(p->pid != 0){
1057
 
      break;
1058
 
    }
1059
 
    if(p->next == NULL){
1060
 
      fprintf(stderr, "No plugin processes started. Incorrect plugin"
1061
 
              " directory?\n");
1062
 
      free_plugin_list();
1063
 
    }
 
542
  if (process_list == NULL){
 
543
    fprintf(stderr, "No plugin processes started, exiting\n");
 
544
    exitstatus = EXIT_FAILURE;
 
545
    goto end;
1064
546
  }
1065
 
  
1066
 
  /* Main loop while running plugins exist */
1067
 
  while(plugin_list){
 
547
  while(process_list){
1068
548
    fd_set rfds = rfds_all;
1069
549
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
1070
 
    if(select_ret == -1 and errno != EINTR){
 
550
    if (select_ret == -1){
1071
551
      perror("select");
1072
552
      exitstatus = EXIT_FAILURE;
1073
 
      goto fallback;
 
553
      goto end;
1074
554
    }
1075
555
    /* OK, now either a process completed, or something can be read
1076
556
       from one of them */
1077
 
    for(plugin *proc = plugin_list; proc != NULL;){
 
557
    for(process *proc = process_list; proc ; proc = proc->next){
1078
558
      /* Is this process completely done? */
1079
 
      if(proc->completed and proc->eof){
 
559
      if(proc->eof and proc->completed){
1080
560
        /* Only accept the plugin output if it exited cleanly */
1081
561
        if(not WIFEXITED(proc->status)
1082
562
           or WEXITSTATUS(proc->status) != 0){
1083
563
          /* Bad exit by plugin */
1084
 
          
1085
564
          if(debug){
1086
565
            if(WIFEXITED(proc->status)){
1087
 
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] exited with"
1088
 
                      " status %d\n", proc->name,
1089
 
                      (intmax_t) (proc->pid),
1090
 
                      WEXITSTATUS(proc->status));
1091
 
            } else if(WIFSIGNALED(proc->status)){
1092
 
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] killed by"
1093
 
                      " signal %d: %s\n", proc->name,
1094
 
                      (intmax_t) (proc->pid),
1095
 
                      WTERMSIG(proc->status),
1096
 
                      strsignal(WTERMSIG(proc->status)));
 
566
              fprintf(stderr, "Plugin %d exited with status %d\n",
 
567
                      proc->pid, WEXITSTATUS(proc->status));
 
568
            } else if(WIFSIGNALED(proc->status)) {
 
569
              fprintf(stderr, "Plugin %d killed by signal %d\n",
 
570
                      proc->pid, WTERMSIG(proc->status));
1097
571
            } else if(WCOREDUMP(proc->status)){
1098
 
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
1099
 
                      " core\n", proc->name, (intmax_t) (proc->pid));
 
572
              fprintf(stderr, "Plugin %d dumped core\n", proc->pid);
1100
573
            }
1101
574
          }
1102
 
          
1103
575
          /* Remove the plugin */
1104
 
          FD_CLR(proc->fd, &rfds_all); /* Spurious warning from
1105
 
                                          -Wconversion */
1106
 
          
 
576
          FD_CLR(proc->fd, &rfds_all);
1107
577
          /* Block signal while modifying process_list */
1108
 
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
1109
 
                                        (SIG_BLOCK,
1110
 
                                         &sigchld_action.sa_mask,
1111
 
                                         NULL));
 
578
          ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
1112
579
          if(ret < 0){
1113
580
            perror("sigprocmask");
1114
581
            exitstatus = EXIT_FAILURE;
1115
 
            goto fallback;
1116
 
          }
1117
 
          
1118
 
          plugin *next_plugin = proc->next;
1119
 
          free_plugin(proc);
1120
 
          proc = next_plugin;
1121
 
          
 
582
            goto end;
 
583
          }
 
584
          /* Delete this process entry from the list */
 
585
          if(process_list == proc){
 
586
            /* First one - simple */
 
587
            process_list = proc->next;
 
588
          } else {
 
589
            /* Second one or later */
 
590
            for(process *p = process_list; p != NULL; p = p->next){
 
591
              if(p->next == proc){
 
592
                p->next = proc->next;
 
593
                break;
 
594
              }
 
595
            }
 
596
          }
1122
597
          /* We are done modifying process list, so unblock signal */
1123
 
          ret = (int)(TEMP_FAILURE_RETRY
1124
 
                      (sigprocmask(SIG_UNBLOCK,
1125
 
                                   &sigchld_action.sa_mask, NULL)));
 
598
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
 
599
                             NULL);
1126
600
          if(ret < 0){
1127
601
            perror("sigprocmask");
1128
 
            exitstatus = EXIT_FAILURE;
1129
 
            goto fallback;
1130
 
          }
1131
 
          
1132
 
          if(plugin_list == NULL){
1133
 
            break;
1134
 
          }
1135
 
          
1136
 
          continue;
 
602
          }
 
603
          free(proc->buffer);
 
604
          free(proc);
 
605
          /* We deleted this process from the list, so we can't go
 
606
             proc->next.  Therefore, start over from the beginning of
 
607
             the process list */
 
608
          break;
1137
609
        }
1138
 
        
1139
610
        /* This process exited nicely, so print its buffer */
1140
 
        
1141
 
        bool bret = print_out_password(proc->buffer,
1142
 
                                       proc->buffer_length);
1143
 
        if(not bret){
1144
 
          perror("print_out_password");
1145
 
          exitstatus = EXIT_FAILURE;
 
611
        for(size_t written = 0; written < proc->buffer_length;
 
612
            written += (size_t)ret){
 
613
          ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO,
 
614
                                         proc->buffer + written,
 
615
                                         proc->buffer_length
 
616
                                         - written));
 
617
          if(ret < 0){
 
618
            perror("write");
 
619
            exitstatus = EXIT_FAILURE;
 
620
            goto end;
 
621
          }
1146
622
        }
1147
 
        goto fallback;
 
623
        goto end;
1148
624
      }
1149
 
      
1150
625
      /* This process has not completed.  Does it have any output? */
1151
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious
1152
 
                                                         warning from
1153
 
                                                         -Wconversion */
 
626
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
1154
627
        /* This process had nothing to say at this time */
1155
 
        proc = proc->next;
1156
628
        continue;
1157
629
      }
1158
630
      /* Before reading, make the process' data buffer large enough */
1159
631
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1160
632
        proc->buffer = realloc(proc->buffer, proc->buffer_size
1161
633
                               + (size_t) BUFFER_SIZE);
1162
 
        if(proc->buffer == NULL){
 
634
        if (proc->buffer == NULL){
1163
635
          perror("malloc");
1164
636
          exitstatus = EXIT_FAILURE;
1165
 
          goto fallback;
 
637
          goto end;
1166
638
        }
1167
639
        proc->buffer_size += BUFFER_SIZE;
1168
640
      }
1169
641
      /* Read from the process */
1170
 
      sret = TEMP_FAILURE_RETRY(read(proc->fd,
1171
 
                                     proc->buffer
1172
 
                                     + proc->buffer_length,
1173
 
                                     BUFFER_SIZE));
1174
 
      if(sret < 0){
 
642
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
 
643
                 BUFFER_SIZE);
 
644
      if(ret < 0){
1175
645
        /* Read error from this process; ignore the error */
1176
 
        proc = proc->next;
1177
646
        continue;
1178
647
      }
1179
 
      if(sret == 0){
 
648
      if(ret == 0){
1180
649
        /* got EOF */
1181
650
        proc->eof = true;
1182
651
      } else {
1183
 
        proc->buffer_length += (size_t) sret;
 
652
        proc->buffer_length += (size_t) ret;
1184
653
      }
1185
654
    }
1186
655
  }
1187
 
  
1188
 
  
1189
 
 fallback:
1190
 
  
1191
 
  if(plugin_list == NULL or exitstatus != EXIT_SUCCESS){
1192
 
    /* Fallback if all plugins failed, none are found or an error
1193
 
       occured */
1194
 
    bool bret;
1195
 
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
1196
 
    char *passwordbuffer = getpass("Password: ");
1197
 
    size_t len = strlen(passwordbuffer);
1198
 
    /* Strip trailing newline */
1199
 
    if(len > 0 and passwordbuffer[len-1] == '\n'){
1200
 
      passwordbuffer[len-1] = '\0'; /* not strictly necessary */
1201
 
      len--;
1202
 
    }
1203
 
    bret = print_out_password(passwordbuffer, len);
1204
 
    if(not bret){
1205
 
      perror("print_out_password");
1206
 
      exitstatus = EXIT_FAILURE;
1207
 
    }
 
656
  if(process_list == NULL){
 
657
    fprintf(stderr, "All plugin processes failed, exiting\n");
 
658
    exitstatus = EXIT_FAILURE;
1208
659
  }
1209
660
  
 
661
 end:
1210
662
  /* Restore old signal handler */
1211
 
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1212
 
  if(ret == -1){
1213
 
    perror("sigaction");
1214
 
    exitstatus = EXIT_FAILURE;
1215
 
  }
1216
 
  
1217
 
  if(custom_argv != NULL){
1218
 
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
1219
 
      free(*arg);
1220
 
    }
1221
 
    free(custom_argv);
 
663
  sigaction(SIGCHLD, &old_sigchld_action, NULL);
 
664
  
 
665
  free(plus_argv);
 
666
  
 
667
  /* Free the plugin list */
 
668
  for(plugin *next; plugin_list != NULL; plugin_list = next){
 
669
    next = plugin_list->next;
 
670
    free(plugin_list->argv);
 
671
    free(plugin_list);
1222
672
  }
1223
673
  
1224
674
  if(dir != NULL){
1225
675
    closedir(dir);
1226
676
  }
1227
677
  
1228
 
  /* Kill the processes */
1229
 
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1230
 
    if(p->pid != 0){
1231
 
      close(p->fd);
1232
 
      ret = kill(p->pid, SIGTERM);
1233
 
      if(ret == -1 and errno != ESRCH){
1234
 
        /* Set-uid proccesses might not get closed */
1235
 
        perror("kill");
1236
 
      }
1237
 
    }
 
678
  /* Free the process list and kill the processes */
 
679
  for(process *next; process_list != NULL; process_list = next){
 
680
    next = process_list->next;
 
681
    close(process_list->fd);
 
682
    kill(process_list->pid, SIGTERM);
 
683
    free(process_list->buffer);
 
684
    free(process_list);
1238
685
  }
1239
686
  
1240
687
  /* Wait for any remaining child processes to terminate */
1241
 
  do {
 
688
  do{
1242
689
    ret = wait(NULL);
1243
690
  } while(ret >= 0);
1244
691
  if(errno != ECHILD){
1245
692
    perror("wait");
1246
693
  }
1247
694
  
1248
 
  free_plugin_list();
1249
 
  
1250
 
  free(plugindir);
1251
 
  free(argfile);
1252
 
  
1253
695
  return exitstatus;
1254
696
}