/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 plugbasedclient.c

  • Committer: Björn Påhlsson
  • Date: 2008-07-20 02:52:20 UTC
  • Revision ID: belorn@braxen-20080720025220-r5u0388uy9iu23h6
Added following support:
Pluginbased client handler
rewritten Mandos client
       Avahi instead of udp server discovery
       openpgp encrypted key support
Passprompt stand alone application for direct console input
Added logging for Mandos server

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*  -*- coding: utf-8 -*- */
2
 
/*
3
 
 * Mandos plugin runner - Run Mandos plugins
4
 
 *
5
 
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
6
 
 * 
7
 
 * This program is free software: you can redistribute it and/or
8
 
 * modify it under the terms of the GNU General Public License as
9
 
 * published by the Free Software Foundation, either version 3 of the
10
 
 * License, or (at your option) any later version.
11
 
 * 
12
 
 * This program is distributed in the hope that it will be useful, but
13
 
 * WITHOUT ANY WARRANTY; without even the implied warranty of
14
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 
 * General Public License for more details.
16
 
 * 
17
 
 * You should have received a copy of the GNU General Public License
18
 
 * along with this program.  If not, see
19
 
 * <http://www.gnu.org/licenses/>.
20
 
 * 
21
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
22
 
 */
23
 
 
24
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
25
 
                                   asprintf() */
26
 
#include <stddef.h>             /* size_t, NULL */
27
 
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
 
                                   EXIT_SUCCESS, realloc() */
29
 
#include <stdbool.h>            /* bool, true, false */
30
 
#include <stdio.h>              /* perror, popen(), fileno(),
31
 
                                   fprintf(), stderr, STDOUT_FILENO */
32
 
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
33
 
                                   stat, waitpid(), WIFEXITED(),
34
 
                                   WEXITSTATUS(), wait(), pid_t,
35
 
                                   uid_t, gid_t, getuid(), getgid(),
36
 
                                   dirfd() */
37
 
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
38
 
                                   FD_SET(), FD_ISSET(), FD_CLR */
39
 
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
40
 
                                   WEXITSTATUS() */
41
 
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
42
 
#include <iso646.h>             /* and, or, not */
43
 
#include <dirent.h>             /* DIR, struct dirent, opendir(),
44
 
                                   readdir(), closedir(), dirfd() */
45
 
#include <unistd.h>             /* struct stat, stat(), S_ISREG(),
46
 
                                   fcntl(), setuid(), setgid(),
47
 
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
48
 
                                   access(), pipe(), fork(), close()
49
 
                                   dup2, STDOUT_FILENO, _exit(),
50
 
                                   execv(), write(), read(),
51
 
                                   close() */
52
 
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
 
                                   FD_CLOEXEC */
54
 
#include <string.h>             /* strsep, strlen(), asprintf() */
55
 
#include <errno.h>              /* errno */
56
 
#include <argp.h>               /* struct argp_option, struct
57
 
                                   argp_state, struct argp,
58
 
                                   argp_parse(), ARGP_ERR_UNKNOWN,
59
 
                                   ARGP_KEY_END, ARGP_KEY_ARG, error_t */
60
 
#include <signal.h>             /* struct sigaction, sigemptyset(),
61
 
                                   sigaddset(), sigaction(),
62
 
                                   sigprocmask(), SIG_BLOCK, SIGCHLD,
63
 
                                   SIG_UNBLOCK, kill() */
64
 
#include <errno.h>              /* errno, EBADF */
65
 
 
66
 
#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";
70
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
1
#include <stdio.h>      /* popen, fileno */
 
2
#include <iso646.h>     /* and, or, not */
 
3
#include <sys/types.h>  /* DIR, opendir, stat, struct stat, waitpid,
 
4
                           WIFEXITED, WEXITSTATUS, wait */
 
5
#include <sys/wait.h>   /* wait */
 
6
#include <dirent.h>     /* DIR, opendir */
 
7
#include <sys/stat.h>   /* stat, struct stat */
 
8
#include <unistd.h>     /* stat, struct stat, chdir */
 
9
#include <stdlib.h>     /* EXIT_FAILURE */
 
10
#include <sys/select.h> /* fd_set, select, FD_ZERO, FD_SET, FD_ISSET */
 
11
#include <string.h>     /* strlen, strcpy, strcat */
 
12
#include <stdbool.h>    /* true */
 
13
#include <sys/wait.h>   /* waitpid, WIFEXITED, WEXITSTATUS */
 
14
#include <errno.h>      /* errno */
71
15
 
72
16
struct process;
73
17
 
75
19
  pid_t pid;
76
20
  int fd;
77
21
  char *buffer;
78
 
  size_t buffer_size;
79
 
  size_t buffer_length;
80
 
  bool eof;
81
 
  bool completed;
82
 
  int status;
 
22
  int buffer_size;
 
23
  int buffer_length;
83
24
  struct process *next;
84
25
} process;
85
26
 
86
 
typedef struct plugin{
87
 
  char *name;                   /* can be NULL or any plugin name */
88
 
  char **argv;
89
 
  int argc;
90
 
  char **environ;
91
 
  int envc;
92
 
  bool disabled;
93
 
  struct plugin *next;
94
 
} plugin;
95
 
 
96
 
static plugin *getplugin(char *name, plugin **plugin_list){
97
 
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
98
 
    if ((p->name == name)
99
 
        or (p->name and name and (strcmp(p->name, name) == 0))){
100
 
      return p;
101
 
    }
102
 
  }
103
 
  /* Create a new plugin */
104
 
  plugin *new_plugin = malloc(sizeof(plugin));
105
 
  if (new_plugin == NULL){
106
 
    return NULL;
107
 
  }
108
 
  char *copy_name = NULL;
109
 
  if(name != NULL){
110
 
    copy_name = strdup(name);
111
 
  }
112
 
  if(copy_name == NULL){
113
 
    return NULL;
114
 
  }
115
 
  
116
 
  *new_plugin = (plugin) { .name = copy_name,
117
 
                           .argc = 1,
118
 
                           .envc = 0,
119
 
                           .disabled = false,
120
 
                           .next = *plugin_list };
121
 
  
122
 
  new_plugin->argv = malloc(sizeof(char *) * 2);
123
 
  if (new_plugin->argv == NULL){
124
 
    free(copy_name);
125
 
    free(new_plugin);
126
 
    return NULL;
127
 
  }
128
 
  new_plugin->argv[0] = copy_name;
129
 
  new_plugin->argv[1] = NULL;
130
 
 
131
 
  new_plugin->environ = malloc(sizeof(char *));
132
 
  if(new_plugin->environ == NULL){
133
 
    free(copy_name);
134
 
    free(new_plugin->argv);
135
 
    free(new_plugin);
136
 
    return NULL;
137
 
  }
138
 
  new_plugin->environ[0] = NULL;
139
 
  /* Append the new plugin to the list */
140
 
  *plugin_list = new_plugin;
141
 
  return new_plugin;
142
 
}
143
 
 
144
 
/* Helper function for add_argument and add_environment */
145
 
static bool add_to_char_array(const char *new, char ***array,
146
 
                              int *len){
147
 
  /* Resize the pointed-to array to hold one more pointer */
148
 
  *array = realloc(*array, sizeof(char *)
149
 
                   * (size_t) ((*len) + 2));
150
 
  /* Malloc check */
151
 
  if(*array == NULL){
152
 
    return false;
153
 
  }
154
 
  /* Make a copy of the new string */
155
 
  char *copy = strdup(new);
156
 
  if(copy == NULL){
157
 
    return false;
158
 
  }
159
 
  /* Insert the copy */
160
 
  (*array)[*len] = copy;
161
 
  (*len)++;
162
 
  /* Add a new terminating NULL pointer to the last element */
163
 
  (*array)[*len] = NULL;
164
 
  return true;
165
 
}
166
 
 
167
 
/* Add to a plugin's argument vector */
168
 
static bool add_argument(plugin *p, const char *arg){
169
 
  if(p == NULL){
170
 
    return false;
171
 
  }
172
 
  return add_to_char_array(arg, &(p->argv), &(p->argc));
173
 
}
174
 
 
175
 
/* Add to a plugin's environment */
176
 
static bool add_environment(plugin *p, const char *def){
177
 
  if(p == NULL){
178
 
    return false;
179
 
  }
180
 
  return add_to_char_array(def, &(p->environ), &(p->envc));
181
 
}
182
 
 
183
 
 
184
 
/*
185
 
 * Based on the example in the GNU LibC manual chapter 13.13 "File
186
 
 * Descriptor Flags".
187
 
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
188
 
 */
189
 
static int set_cloexec_flag(int fd)
190
 
{
191
 
  int ret = fcntl(fd, F_GETFD, 0);
192
 
  /* If reading the flags failed, return error indication now. */
193
 
  if(ret < 0){
194
 
    return ret;
195
 
  }
196
 
  /* Store modified flag word in the descriptor. */
197
 
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
198
 
}
199
 
 
200
 
process *process_list = NULL;
201
 
 
202
 
/* Mark a process as completed when it exits, and save its exit
203
 
   status. */
204
 
void handle_sigchld(__attribute__((unused)) int sig){
205
 
  process *proc = process_list;
206
 
  int status;
207
 
  pid_t pid = wait(&status);
208
 
  if(pid == -1){
209
 
    perror("wait");
210
 
    return;
211
 
  }
212
 
  while(proc != NULL and proc->pid != pid){
213
 
    proc = proc->next;
214
 
  }
215
 
  if(proc == NULL){
216
 
    /* Process not found in process list */
217
 
    return;
218
 
  }
219
 
  proc->status = status;
220
 
  proc->completed = true;
221
 
}
222
 
 
223
 
bool print_out_password(const char *buffer, size_t length){
224
 
  ssize_t ret;
225
 
  if(length>0 and buffer[length-1] == '\n'){
226
 
    length--;
227
 
  }
228
 
  for(size_t written = 0; written < length; written += (size_t)ret){
229
 
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
230
 
                                   length - written));
231
 
    if(ret < 0){
232
 
      return false;
233
 
    }
234
 
  }
235
 
  return true;
236
 
}
237
 
 
238
 
char **add_to_argv(char **argv, int *argc, char *arg){
239
 
  if (argv == NULL){
240
 
    *argc = 1;
241
 
    argv = malloc(sizeof(char*) * 2);
242
 
    if(argv == NULL){
243
 
      return NULL;
244
 
    }
245
 
    argv[0] = NULL;     /* Will be set to argv[0] in main before parsing */
246
 
    argv[1] = NULL;
247
 
  }
248
 
  *argc += 1;
249
 
  argv = realloc(argv, sizeof(char *)
250
 
                  * ((unsigned int) *argc + 1));
251
 
  if(argv == NULL){
252
 
    return NULL;
253
 
  }
254
 
  argv[*argc-1] = arg;
255
 
  argv[*argc] = NULL;   
256
 
  return argv;
257
 
}
258
 
 
259
 
static void free_plugin_list(plugin *plugin_list){
260
 
  for(plugin *next = plugin_list; plugin_list != NULL; plugin_list = next){
261
 
    next = plugin_list->next;
262
 
    free(plugin_list->name);
263
 
    for(char **arg = plugin_list->argv; *arg != NULL; arg++){
264
 
      free(*arg);
265
 
    }    
266
 
    free(plugin_list->argv);
267
 
    for(char **env = plugin_list->environ; *env != NULL; env++){
268
 
      free(*env);
269
 
    }
270
 
    free(plugin_list->environ);
271
 
    free(plugin_list);
272
 
  }  
273
 
}
 
27
#define BUFFER_SIZE 256
274
28
 
275
29
int main(int argc, char *argv[]){
276
 
  const char *plugindir = "/lib/mandos/plugins.d";
277
 
  const char *argfile = ARGFILE;
278
 
  FILE *conffp;
279
 
  size_t d_name_len;
280
 
  DIR *dir = NULL;
 
30
  char plugindir[] = "plugins.d";
 
31
  size_t d_name_len, plugindir_len = sizeof(plugindir)-1;
 
32
  DIR *dir;
281
33
  struct dirent *dirst;
282
34
  struct stat st;
283
 
  fd_set rfds_all;
 
35
  fd_set rfds_orig;
284
36
  int ret, maxfd = 0;
285
 
  uid_t uid = 65534;
286
 
  gid_t gid = 65534;
287
 
  bool debug = false;
288
 
  int exitstatus = EXIT_SUCCESS;
289
 
  struct sigaction old_sigchld_action;
290
 
  struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
291
 
                                      .sa_flags = SA_NOCLDSTOP };
292
 
  char **custom_argv = NULL;
293
 
  int custom_argc = 0;
294
 
  
295
 
  /* Establish a signal handler */
296
 
  sigemptyset(&sigchld_action.sa_mask);
297
 
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
298
 
  if(ret == -1){
299
 
    perror("sigaddset");
300
 
    exitstatus = EXIT_FAILURE;
301
 
    goto fallback;
302
 
  }
303
 
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
304
 
  if(ret == -1){
305
 
    perror("sigaction");
306
 
    exitstatus = EXIT_FAILURE;    
307
 
    goto fallback;
308
 
  }
309
 
  
310
 
  /* The options we understand. */
311
 
  struct argp_option options[] = {
312
 
    { .name = "global-options", .key = 'g',
313
 
      .arg = "OPTION[,OPTION[,...]]",
314
 
      .doc = "Options passed to all plugins" },
315
 
    { .name = "global-envs", .key = 'e',
316
 
      .arg = "VAR=value",
317
 
      .doc = "Environment variable passed to all plugins" },
318
 
    { .name = "options-for", .key = 'o',
319
 
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
320
 
      .doc = "Options passed only to specified plugin" },
321
 
    { .name = "envs-for", .key = 'f',
322
 
      .arg = "PLUGIN:ENV=value",
323
 
      .doc = "Environment variable passed to specified plugin" },
324
 
    { .name = "disable", .key = 'd',
325
 
      .arg = "PLUGIN",
326
 
      .doc = "Disable a specific plugin", .group = 1 },
327
 
    { .name = "plugin-dir", .key = 128,
328
 
      .arg = "DIRECTORY",
329
 
      .doc = "Specify a different plugin directory", .group = 2 },
330
 
    { .name = "userid", .key = 129,
331
 
      .arg = "ID", .flags = 0,
332
 
      .doc = "User ID the plugins will run as", .group = 2 },
333
 
    { .name = "groupid", .key = 130,
334
 
      .arg = "ID", .flags = 0,
335
 
      .doc = "Group ID the plugins will run as", .group = 2 },
336
 
    { .name = "debug", .key = 131,
337
 
      .doc = "Debug mode", .group = 3 },
338
 
    { .name = NULL }
339
 
  };
340
 
  
341
 
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
342
 
    /* Get the INPUT argument from `argp_parse', which we know is a
343
 
       pointer to our plugin list pointer. */
344
 
    plugin **plugins = state->input;
345
 
    switch (key) {
346
 
    case 'g':
347
 
      if (arg != NULL){
348
 
        char *p;
349
 
        while((p = strsep(&arg, ",")) != NULL){
350
 
          if(p[0] == '\0'){
351
 
            continue;
352
 
          }
353
 
          if(not add_argument(getplugin(NULL, plugins), p)){
354
 
            perror("add_argument");
355
 
            return ARGP_ERR_UNKNOWN;
356
 
          }
357
 
        }
358
 
      }
359
 
      break;
360
 
    case 'e':
361
 
      if(arg == NULL){
362
 
        break;
363
 
      }
364
 
      {
365
 
        char *envdef = strdup(arg);
366
 
        if(envdef == NULL){
367
 
          break;
368
 
        }
369
 
        if(not add_environment(getplugin(NULL, plugins), envdef)){
370
 
          perror("add_environment");
371
 
        }
372
 
      }
373
 
      break;
374
 
    case 'o':
375
 
      if (arg != NULL){
376
 
        char *p_name = strsep(&arg, ":");
377
 
        if(p_name[0] == '\0'){
378
 
          break;
379
 
        }
380
 
        char *opt = strsep(&arg, ":");
381
 
        if(opt[0] == '\0'){
382
 
          break;
383
 
        }
384
 
        if(opt != NULL){
385
 
          char *p;
386
 
          while((p = strsep(&opt, ",")) != NULL){
387
 
            if(p[0] == '\0'){
388
 
              continue;
389
 
            }
390
 
            if(not add_argument(getplugin(p_name, plugins), p)){
391
 
              perror("add_argument");
392
 
              return ARGP_ERR_UNKNOWN;
393
 
            }
394
 
          }
395
 
        }
396
 
      }
397
 
      break;
398
 
    case 'f':
399
 
      if(arg == NULL){
400
 
        break;
401
 
      }
402
 
      {
403
 
        char *envdef = strchr(arg, ':');
404
 
        if(envdef == NULL){
405
 
          break;
406
 
        }
407
 
        char *p_name = strndup(arg, (size_t) (envdef-arg));
408
 
        if(p_name == NULL){
409
 
          break;
410
 
        }
411
 
        envdef++;
412
 
        if(not add_environment(getplugin(p_name, plugins), envdef)){
413
 
          perror("add_environment");
414
 
        }
415
 
      }
416
 
      break;
417
 
    case 'd':
418
 
      if (arg != NULL){
419
 
        plugin *p = getplugin(arg, plugins);
420
 
        if(p == NULL){
421
 
          return ARGP_ERR_UNKNOWN;
422
 
        }
423
 
        p->disabled = true;
424
 
      }
425
 
      break;
426
 
    case 128:
427
 
      plugindir = arg;
428
 
      break;
429
 
    case 129:
430
 
      uid = (uid_t)strtol(arg, NULL, 10);
431
 
      break;
432
 
    case 130:
433
 
      gid = (gid_t)strtol(arg, NULL, 10);
434
 
      break;
435
 
    case 131:
436
 
      debug = true;
437
 
      break;
438
 
    case ARGP_KEY_ARG:
439
 
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
440
 
      break;
441
 
    case ARGP_KEY_END:
442
 
      break;
443
 
    default:
444
 
      return ARGP_ERR_UNKNOWN;
445
 
    }
446
 
    return 0;
447
 
  }
448
 
  
449
 
  plugin *plugin_list = NULL;
450
 
  
451
 
  struct argp argp = { .options = options, .parser = parse_opt,
452
 
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
453
 
                       .doc = "Mandos plugin runner -- Run plugins" };
454
 
  
455
 
  ret = argp_parse (&argp, argc, argv, 0, 0, &plugin_list);
456
 
  if (ret == ARGP_ERR_UNKNOWN){
457
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
458
 
    exitstatus = EXIT_FAILURE;
459
 
    goto fallback;
460
 
  }
461
 
 
462
 
  conffp = fopen(argfile, "r");
463
 
  if(conffp != NULL){
464
 
    char *org_line = NULL;
465
 
    char *p, *arg, *new_arg, *line;
466
 
    size_t size = 0;
467
 
    ssize_t sret;
468
 
    const char whitespace_delims[] = " \r\t\f\v\n";
469
 
    const char comment_delim[] = "#";
470
 
 
471
 
    while(true){
472
 
      sret = getline(&org_line, &size, conffp);
473
 
      if(sret == -1){
474
 
        break;
475
 
      }
476
 
 
477
 
      line = org_line;
478
 
      arg = strsep(&line, comment_delim);
479
 
      while((p = strsep(&arg, whitespace_delims)) != NULL){
480
 
        if(p[0] == '\0'){
481
 
          continue;
482
 
        }
483
 
        new_arg = strdup(p);
484
 
        custom_argv = add_to_argv(custom_argv, &custom_argc, new_arg);
485
 
        if (custom_argv == NULL){
486
 
          perror("add_to_argv");
487
 
          exitstatus = EXIT_FAILURE;
488
 
          goto fallback;
489
 
        }
490
 
      }
491
 
    }
492
 
    free(org_line);
493
 
  } else{
494
 
    /* Check for harmful errors and go to fallback. Other errors might
495
 
       not affect opening plugins */
496
 
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
497
 
      perror("fopen");
498
 
      exitstatus = EXIT_FAILURE;
499
 
      goto fallback;
500
 
    }
501
 
  }
502
 
 
503
 
  if(custom_argv != NULL){
504
 
    custom_argv[0] = argv[0];
505
 
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, &plugin_list);
506
 
    if (ret == ARGP_ERR_UNKNOWN){
507
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
508
 
      exitstatus = EXIT_FAILURE;
509
 
      goto fallback;
510
 
    }
511
 
  }
512
 
  
513
 
  if(debug){
514
 
    for(plugin *p = plugin_list; p != NULL; p=p->next){
515
 
      fprintf(stderr, "Plugin: %s has %d arguments\n",
516
 
              p->name ? p->name : "Global", p->argc - 1);
517
 
      for(char **a = p->argv; *a != NULL; a++){
518
 
        fprintf(stderr, "\tArg: %s\n", *a);
519
 
      }
520
 
      fprintf(stderr, "...and %u environment variables\n", p->envc);
521
 
      for(char **a = p->environ; *a != NULL; a++){
522
 
        fprintf(stderr, "\t%s\n", *a);
523
 
      }
524
 
    }
525
 
  }
526
 
  
527
 
  ret = setuid(uid);
528
 
  if (ret == -1){
529
 
    perror("setuid");
530
 
  }
531
 
  
532
 
  setgid(gid);
533
 
  if (ret == -1){
534
 
    perror("setgid");
535
 
  }
 
37
  process *process_list = NULL;
536
38
  
537
39
  dir = opendir(plugindir);
 
40
 
538
41
  if(dir == NULL){
539
 
    perror("Could not open plugin dir");
540
 
    exitstatus = EXIT_FAILURE;
541
 
    goto fallback;
542
 
  }
543
 
  
544
 
  /* Set the FD_CLOEXEC flag on the directory, if possible */
545
 
  {
546
 
    int dir_fd = dirfd(dir);
547
 
    if(dir_fd >= 0){
548
 
      ret = set_cloexec_flag(dir_fd);
549
 
      if(ret < 0){
550
 
        perror("set_cloexec_flag");
551
 
        exitstatus = EXIT_FAILURE;
552
 
        goto fallback;
553
 
      }
554
 
    }
555
 
  }
556
 
  
557
 
  FD_ZERO(&rfds_all);
 
42
    fprintf(stderr, "Can not open directory\n");
 
43
    return EXIT_FAILURE;
 
44
  }
 
45
  
 
46
  FD_ZERO(&rfds_orig);
558
47
  
559
48
  while(true){
560
49
    dirst = readdir(dir);
561
50
    
562
51
    // All directory entries have been processed
563
52
    if(dirst == NULL){
564
 
      if (errno == EBADF){
565
 
        perror("readdir");
566
 
        exitstatus = EXIT_FAILURE;
567
 
        goto fallback;
568
 
      }
569
53
      break;
570
54
    }
571
55
    
572
56
    d_name_len = strlen(dirst->d_name);
573
57
    
574
 
    // Ignore dotfiles, backup files and other junk
575
 
    {
576
 
      bool bad_name = false;
577
 
      
578
 
      const char const *bad_prefixes[] = { ".", "#", NULL };
579
 
      
580
 
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
581
 
                                           ".dpkg-old",
582
 
                                           ".dpkg-divert", NULL };
583
 
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
584
 
        size_t pre_len = strlen(*pre);
585
 
        if((d_name_len >= pre_len)
586
 
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
587
 
          if(debug){
588
 
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
589
 
                    " with bad prefix %s\n", dirst->d_name, *pre);
590
 
          }
591
 
          bad_name = true;
592
 
          break;
593
 
        }
594
 
      }
595
 
      
596
 
      if(bad_name){
597
 
        continue;
598
 
      }
599
 
      
600
 
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
601
 
        size_t suf_len = strlen(*suf);
602
 
        if((d_name_len >= suf_len)
603
 
           and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
604
 
                == 0)){
605
 
          if(debug){
606
 
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
607
 
                    " with bad suffix %s\n", dirst->d_name, *suf);
608
 
          }
609
 
          bad_name = true;
610
 
          break;
611
 
        }
612
 
      }
613
 
      
614
 
      if(bad_name){
615
 
        continue;
616
 
      }
617
 
    }
618
 
 
619
 
    char *filename;
620
 
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
621
 
    if(ret < 0){
622
 
      perror("asprintf");
623
 
      continue;
624
 
    }
625
 
    
626
 
    ret = stat(filename, &st);
627
 
    if (ret == -1){
628
 
      perror("stat");
629
 
      free(filename);
630
 
      continue;
631
 
    }
632
 
    
633
 
    if (not S_ISREG(st.st_mode) or (access(filename, X_OK) != 0)){
634
 
      if(debug){
635
 
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
636
 
                " with bad type or mode\n", filename);
637
 
      }
638
 
      free(filename);
639
 
      continue;
640
 
    }
641
 
    plugin *p = getplugin(dirst->d_name, &plugin_list);
642
 
    if(p == NULL){
643
 
      perror("getplugin");
644
 
      free(filename);
645
 
      continue;
646
 
    }
647
 
    if(p->disabled){
648
 
      if(debug){
649
 
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
650
 
                dirst->d_name);
651
 
      }
652
 
      free(filename);
653
 
      continue;
654
 
    }
655
 
    {
656
 
      /* Add global arguments to argument list for this plugin */
657
 
      plugin *g = getplugin(NULL, &plugin_list);
658
 
      if(g != NULL){
659
 
        for(char **a = g->argv + 1; *a != NULL; a++){
660
 
          if(not add_argument(p, *a)){
661
 
            perror("add_argument");
662
 
          }
663
 
        }
664
 
        /* Add global environment variables */
665
 
        for(char **e = g->environ; *e != NULL; e++){
666
 
          if(not add_environment(p, *e)){
667
 
            perror("add_environment");
668
 
          }
669
 
        }
670
 
      }
671
 
    }
672
 
    /* If this plugin has any environment variables, we will call
673
 
       using execve and need to duplicate the environment from this
674
 
       process, too. */
675
 
    if(p->environ[0] != NULL){
676
 
      for(char **e = environ; *e != NULL; e++){
677
 
        char *copy = strdup(*e);
678
 
        if(copy == NULL){
679
 
          perror("strdup");
680
 
          continue;
681
 
        }
682
 
        if(not add_environment(p, copy)){
683
 
          perror("add_environment");
684
 
        }
685
 
      }
686
 
    }
687
 
    
688
 
    int pipefd[2]; 
689
 
    ret = pipe(pipefd);
690
 
    if (ret == -1){
691
 
      perror("pipe");
692
 
      exitstatus = EXIT_FAILURE;
693
 
      goto fallback;
694
 
    }
695
 
    ret = set_cloexec_flag(pipefd[0]);
696
 
    if(ret < 0){
697
 
      perror("set_cloexec_flag");
698
 
      exitstatus = EXIT_FAILURE;
699
 
      goto fallback;
700
 
    }
701
 
    ret = set_cloexec_flag(pipefd[1]);
702
 
    if(ret < 0){
703
 
      perror("set_cloexec_flag");
704
 
      exitstatus = EXIT_FAILURE;
705
 
      goto fallback;
706
 
    }
707
 
    /* Block SIGCHLD until process is safely in process list */
708
 
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
709
 
    if(ret < 0){
710
 
      perror("sigprocmask");
711
 
      exitstatus = EXIT_FAILURE;
712
 
      goto fallback;
713
 
    }
714
 
    // Starting a new process to be watched
715
 
    pid_t pid = fork();
716
 
    if(pid == -1){
717
 
      perror("fork");
718
 
      exitstatus = EXIT_FAILURE;
719
 
      goto fallback;
720
 
    }
721
 
    if(pid == 0){
722
 
      /* this is the child process */
723
 
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
724
 
      if(ret < 0){
725
 
        perror("sigaction");
726
 
        _exit(EXIT_FAILURE);
727
 
      }
728
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
729
 
      if(ret < 0){
730
 
        perror("sigprocmask");
731
 
        _exit(EXIT_FAILURE);
732
 
      }
733
 
 
734
 
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
735
 
      if(ret == -1){
736
 
        perror("dup2");
737
 
        _exit(EXIT_FAILURE);
738
 
      }
739
 
      
740
 
      if(dirfd(dir) < 0){
741
 
        /* If dir has no file descriptor, we could not set FD_CLOEXEC
742
 
           above and must now close it manually here. */
 
58
    // Ignore dotfiles and backup files
 
59
    if (dirst->d_name[0] == '.'
 
60
        or dirst->d_name[d_name_len - 1] == '~'){
 
61
      continue;
 
62
    }
 
63
    
 
64
    char *filename = malloc(d_name_len + plugindir_len + 1);
 
65
    strcpy(filename, plugindir);
 
66
    strcat(filename, "/");
 
67
    strcat(filename, dirst->d_name);    
 
68
    
 
69
    stat(filename, &st);
 
70
 
 
71
    if (S_ISREG(st.st_mode) and (access(filename, X_OK) == 0)){
 
72
      // Starting a new process to be watched
 
73
      process *new_process = malloc(sizeof(process));
 
74
      int pipefd[2];
 
75
      pipe(pipefd);
 
76
      new_process->pid = fork();
 
77
      if(new_process->pid == 0){
 
78
        /* this is the child process */
743
79
        closedir(dir);
744
 
      }
745
 
      if(p->environ[0] == NULL){
746
 
        if(execv(filename, p->argv) < 0){
747
 
          perror("execv");
748
 
          _exit(EXIT_FAILURE);
749
 
        }
750
 
      } else {
751
 
        if(execve(filename, p->argv, p->environ) < 0){
752
 
          perror("execve");
753
 
          _exit(EXIT_FAILURE);
754
 
        }
755
 
      }
756
 
      /* no return */
757
 
    }
758
 
    /* parent process */
759
 
    free(filename);
760
 
    close(pipefd[1]);           /* close unused write end of pipe */
761
 
    process *new_process = malloc(sizeof(process));
762
 
    if (new_process == NULL){
763
 
      perror("malloc");
764
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
765
 
      if(ret < 0){
766
 
        perror("sigprocmask");
767
 
      }
768
 
      exitstatus = EXIT_FAILURE;
769
 
      goto fallback;
770
 
    }
771
 
    
772
 
    *new_process = (struct process){ .pid = pid,
773
 
                                     .fd = pipefd[0],
774
 
                                     .next = process_list };
775
 
    // List handling
776
 
    process_list = new_process;
777
 
    /* Unblock SIGCHLD so signal handler can be run if this process
778
 
       has already completed */
779
 
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
780
 
    if(ret < 0){
781
 
      perror("sigprocmask");
782
 
      exitstatus = EXIT_FAILURE;
783
 
      goto fallback;
784
 
    }
785
 
    
786
 
    FD_SET(new_process->fd, &rfds_all);
787
 
    
788
 
    if (maxfd < new_process->fd){
789
 
      maxfd = new_process->fd;
790
 
    }
791
 
    
 
80
        close(pipefd[0]);       /* close unused read end of pipe */
 
81
        dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
 
82
        /* create a new modified argument list */
 
83
        char **new_argv = malloc(sizeof(char *) * argc + 1);
 
84
        new_argv[0] = filename;
 
85
        for(int i = 1; i < argc; i++){
 
86
          new_argv[i] = argv[i];
 
87
        }
 
88
        new_argv[argc] = NULL;
 
89
        if(execv(filename, new_argv) < 0){
 
90
          perror(argv[0]);
 
91
          close(pipefd[1]);
 
92
          exit(EXIT_FAILURE);
 
93
        }
 
94
        /* no return */
 
95
      }
 
96
      close(pipefd[1]);         /* close unused write end of pipe */
 
97
      new_process->fd = pipefd[0];
 
98
      new_process->buffer = malloc(BUFFER_SIZE);
 
99
      if (new_process->buffer == NULL){
 
100
        perror(argv[0]);
 
101
        goto end;
 
102
      }
 
103
      new_process->buffer_size = BUFFER_SIZE;
 
104
      new_process->buffer_length = 0;
 
105
      FD_SET(new_process->fd, &rfds_orig);
 
106
      
 
107
      if (maxfd < new_process->fd){
 
108
        maxfd = new_process->fd;
 
109
      }
 
110
      
 
111
      //List handling
 
112
      new_process->next = process_list;
 
113
      process_list = new_process;
 
114
    }
792
115
  }
793
116
  
794
 
  free_plugin_list(plugin_list);
795
 
  
796
117
  closedir(dir);
797
 
  dir = NULL;
798
 
    
799
 
  if (process_list == NULL){
800
 
    fprintf(stderr, "No plugin processes started. Incorrect plugin"
801
 
            " directory?\n");
802
 
    process_list = NULL;
803
 
  }
804
 
  while(process_list){
805
 
    fd_set rfds = rfds_all;
806
 
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
807
 
    if (select_ret == -1){
808
 
      perror("select");
809
 
      exitstatus = EXIT_FAILURE;
810
 
      goto fallback;
811
 
    }
812
 
    /* OK, now either a process completed, or something can be read
813
 
       from one of them */
814
 
    for(process *proc = process_list; proc ; proc = proc->next){
815
 
      /* Is this process completely done? */
816
 
      if(proc->eof and proc->completed){
817
 
        /* Only accept the plugin output if it exited cleanly */
818
 
        if(not WIFEXITED(proc->status)
819
 
           or WEXITSTATUS(proc->status) != 0){
820
 
          /* Bad exit by plugin */
821
 
          if(debug){
822
 
            if(WIFEXITED(proc->status)){
823
 
              fprintf(stderr, "Plugin %u exited with status %d\n",
824
 
                      (unsigned int) (proc->pid),
825
 
                      WEXITSTATUS(proc->status));
826
 
            } else if(WIFSIGNALED(proc->status)) {
827
 
              fprintf(stderr, "Plugin %u killed by signal %d\n",
828
 
                      (unsigned int) (proc->pid),
829
 
                      WTERMSIG(proc->status));
830
 
            } else if(WCOREDUMP(proc->status)){
831
 
              fprintf(stderr, "Plugin %d dumped core\n",
832
 
                      (unsigned int) (proc->pid));
 
118
  
 
119
  if (process_list != NULL){
 
120
    while(true){
 
121
      fd_set rfds = rfds_orig;
 
122
      int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
 
123
      if (select_ret == -1){
 
124
        perror(argv[0]);
 
125
        goto end;
 
126
      }else{    
 
127
        for(process *process_itr = process_list; process_itr != NULL;
 
128
            process_itr = process_itr->next){
 
129
          if(FD_ISSET(process_itr->fd, &rfds)){
 
130
            if(process_itr->buffer_length + BUFFER_SIZE
 
131
               > process_itr->buffer_size){
 
132
                process_itr->buffer = realloc(process_itr->buffer,
 
133
                                              process_itr->buffer_size
 
134
                                              + BUFFER_SIZE);
 
135
                if (process_itr->buffer == NULL){
 
136
                  perror(argv[0]);
 
137
                  goto end;
 
138
                }
 
139
                process_itr->buffer_size += BUFFER_SIZE;
833
140
            }
834
 
          }
835
 
          /* Remove the plugin */
836
 
          FD_CLR(proc->fd, &rfds_all);
837
 
          /* Block signal while modifying process_list */
838
 
          ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
839
 
          if(ret < 0){
840
 
            perror("sigprocmask");
841
 
            exitstatus = EXIT_FAILURE;
842
 
            goto fallback;
843
 
          }
844
 
          /* Delete this process entry from the list */
845
 
          if(process_list == proc){
846
 
            /* First one - simple */
847
 
            process_list = proc->next;
848
 
          } else {
849
 
            /* Second one or later */
850
 
            for(process *p = process_list; p != NULL; p = p->next){
851
 
              if(p->next == proc){
852
 
                p->next = proc->next;
853
 
                break;
 
141
            ret = read(process_itr->fd, process_itr->buffer
 
142
                       + process_itr->buffer_length, BUFFER_SIZE);
 
143
            process_itr->buffer_length+=ret;
 
144
            if(ret == 0){
 
145
              /* got EOF */
 
146
              /* wait for process exit */
 
147
              int status;
 
148
              waitpid(process_itr->pid, &status, 0);
 
149
              if(WIFEXITED(status) and WEXITSTATUS(status) == 0){
 
150
                write(STDOUT_FILENO, process_itr->buffer,
 
151
                      process_itr->buffer_length);
 
152
                goto end;
 
153
              } else {
 
154
                FD_CLR(process_itr->fd, &rfds_orig);
854
155
              }
855
156
            }
856
157
          }
857
 
          /* We are done modifying process list, so unblock signal */
858
 
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
859
 
                             NULL);
860
 
          if(ret < 0){
861
 
            perror("sigprocmask");
862
 
          }
863
 
          free(proc->buffer);
864
 
          free(proc);
865
 
          /* We deleted this process from the list, so we can't go
866
 
             proc->next.  Therefore, start over from the beginning of
867
 
             the process list */
868
 
          break;
869
 
        }
870
 
        /* This process exited nicely, so print its buffer */
871
 
 
872
 
        bool bret = print_out_password(proc->buffer, proc->buffer_length);
873
 
        if(not bret){
874
 
          perror("print_out_password");
875
 
          exitstatus = EXIT_FAILURE;
876
 
        }
877
 
        goto fallback;
878
 
      }
879
 
      /* This process has not completed.  Does it have any output? */
880
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
881
 
        /* This process had nothing to say at this time */
882
 
        continue;
883
 
      }
884
 
      /* Before reading, make the process' data buffer large enough */
885
 
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
886
 
        proc->buffer = realloc(proc->buffer, proc->buffer_size
887
 
                               + (size_t) BUFFER_SIZE);
888
 
        if (proc->buffer == NULL){
889
 
          perror("malloc");
890
 
          exitstatus = EXIT_FAILURE;
891
 
          goto fallback;
892
 
        }
893
 
        proc->buffer_size += BUFFER_SIZE;
894
 
      }
895
 
      /* Read from the process */
896
 
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
897
 
                 BUFFER_SIZE);
898
 
      if(ret < 0){
899
 
        /* Read error from this process; ignore the error */
900
 
        continue;
901
 
      }
902
 
      if(ret == 0){
903
 
        /* got EOF */
904
 
        proc->eof = true;
905
 
      } else {
906
 
        proc->buffer_length += (size_t) ret;
907
 
      }
908
 
    }
909
 
  }
910
 
 
911
 
 
912
 
 fallback:
913
 
  
914
 
  if(process_list == NULL or exitstatus != EXIT_SUCCESS){
915
 
    /* Fallback if all plugins failed, none are found or an error occured */
916
 
    bool bret;
917
 
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
918
 
    char *passwordbuffer = getpass("Password: ");
919
 
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
920
 
    if(not bret){
921
 
      perror("print_out_password");
922
 
      exitstatus = EXIT_FAILURE;
923
 
    }
924
 
  }
925
 
  
926
 
  /* Restore old signal handler */
927
 
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
928
 
  if(ret == -1){
929
 
    perror("sigaction");
930
 
    exitstatus = EXIT_FAILURE;
931
 
  }
932
 
 
933
 
  if(custom_argv != NULL){
934
 
    for(char **arg = custom_argv; *arg != NULL; arg++){
935
 
      free(*arg);
936
 
    }
937
 
    free(custom_argv);
938
 
  }
939
 
  free_plugin_list(plugin_list);
940
 
  
941
 
  if(dir != NULL){
942
 
    closedir(dir);
943
 
  }
944
 
  
945
 
  /* Free the process list and kill the processes */
946
 
  for(process *next; process_list != NULL; process_list = next){
947
 
    next = process_list->next;
948
 
    close(process_list->fd);
949
 
    ret = kill(process_list->pid, SIGTERM);
950
 
    if(ret == -1 and errno != ESRCH){
951
 
      /* set-uid proccesses migth not get closed */
952
 
      perror("kill");
953
 
    }
954
 
    free(process_list->buffer);
955
 
    free(process_list);
956
 
  }
957
 
  
958
 
  /* Wait for any remaining child processes to terminate */
959
 
  do{
960
 
    ret = wait(NULL);
961
 
  } while(ret >= 0);
962
 
  if(errno != ECHILD){
963
 
    perror("wait");
964
 
  }
965
 
  
966
 
  return exitstatus;
 
158
        }
 
159
      }
 
160
    }
 
161
  }
 
162
  
 
163
 end:
 
164
  for(process *process_itr = process_list; process_itr != NULL;
 
165
      process_itr = process_itr->next){
 
166
    close(process_itr->fd);
 
167
    kill(process_itr->pid, SIGTERM);
 
168
    free(process_itr->buffer);
 
169
  }
 
170
  
 
171
  while(true){
 
172
    int status;
 
173
    ret = wait(&status);
 
174
    if (ret == -1){
 
175
      if(errno != ECHILD){
 
176
        perror("wait");
 
177
      }
 
178
      break;
 
179
    }
 
180
  }  
 
181
  return EXIT_SUCCESS;
967
182
}