/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

merge
new approve/deny functionallity in mandos-monitor

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
/*
3
3
 * Mandos plugin runner - Run Mandos plugins
4
4
 *
5
 
 * Copyright © 2008-2018 Teddy Hogeborn
6
 
 * Copyright © 2008-2018 Björn Påhlsson
7
 
 * 
8
 
 * This file is part of Mandos.
9
 
 * 
10
 
 * Mandos is free software: you can redistribute it and/or modify it
11
 
 * under the terms of the GNU General Public License as published by
12
 
 * the Free Software Foundation, either version 3 of the License, or
13
 
 * (at your option) any later version.
14
 
 * 
15
 
 * Mandos is distributed in the hope that it will be useful, but
 
5
 * Copyright © 2008,2009 Teddy Hogeborn
 
6
 * Copyright © 2008,2009 Björn Påhlsson
 
7
 * 
 
8
 * This program is free software: you can redistribute it and/or
 
9
 * modify it under the terms of the GNU General Public License as
 
10
 * published by the Free Software Foundation, either version 3 of the
 
11
 * License, or (at your option) any later version.
 
12
 * 
 
13
 * This program is distributed in the hope that it will be useful, but
16
14
 * WITHOUT ANY WARRANTY; without even the implied warranty of
17
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
16
 * General Public License for more details.
19
17
 * 
20
18
 * You should have received a copy of the GNU General Public License
21
 
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
 
19
 * along with this program.  If not, see
 
20
 * <http://www.gnu.org/licenses/>.
22
21
 * 
23
 
 * Contact the authors at <mandos@recompile.se>.
 
22
 * Contact the authors at <mandos@fukt.bsnet.se>.
24
23
 */
25
24
 
26
25
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), getline(),
27
 
                                   O_CLOEXEC, pipe2() */
 
26
                                   asprintf(), O_CLOEXEC */
28
27
#include <stddef.h>             /* size_t, NULL */
29
28
#include <stdlib.h>             /* malloc(), exit(), EXIT_SUCCESS,
30
29
                                   realloc() */
31
30
#include <stdbool.h>            /* bool, true, false */
32
 
#include <stdio.h>              /* fileno(), fprintf(),
33
 
                                   stderr, STDOUT_FILENO, fclose() */
34
 
#include <sys/types.h>          /* fstat(), struct stat, waitpid(),
35
 
                                   WIFEXITED(), WEXITSTATUS(), wait(),
36
 
                                   pid_t, uid_t, gid_t, getuid(),
37
 
                                   getgid() */
 
31
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
32
                                   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
38
#include <sys/select.h>         /* fd_set, select(), FD_ZERO(),
39
39
                                   FD_SET(), FD_ISSET(), FD_CLR */
40
40
#include <sys/wait.h>           /* wait(), waitpid(), WIFEXITED(),
41
 
                                   WEXITSTATUS(), WTERMSIG() */
42
 
#include <sys/stat.h>           /* struct stat, fstat(), S_ISREG() */
 
41
                                   WEXITSTATUS(), WTERMSIG(),
 
42
                                   WCOREDUMP() */
 
43
#include <sys/stat.h>           /* struct stat, stat(), S_ISREG() */
43
44
#include <iso646.h>             /* and, or, not */
44
 
#include <dirent.h>             /* struct dirent, scandirat() */
45
 
#include <unistd.h>             /* fcntl(), F_GETFD, F_SETFD,
46
 
                                   FD_CLOEXEC, write(), STDOUT_FILENO,
47
 
                                   struct stat, fstat(), close(),
48
 
                                   setgid(), setuid(), S_ISREG(),
49
 
                                   faccessat() pipe2(), fork(),
50
 
                                   _exit(), dup2(), fexecve(), read()
51
 
                                */
 
45
#include <dirent.h>             /* DIR, struct dirent, fdopendir(),
 
46
                                   readdir(), closedir(), dirfd() */
 
47
#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() */
52
54
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
53
 
                                   FD_CLOEXEC, openat(), scandirat(),
54
 
                                   pipe2() */
55
 
#include <string.h>             /* strsep, strlen(), strsignal(),
56
 
                                   strcmp(), strncmp() */
 
55
                                   FD_CLOEXEC */
 
56
#include <string.h>             /* strsep, strlen(), asprintf(),
 
57
                                   strsignal(), strcmp(), strncmp() */
57
58
#include <errno.h>              /* errno */
58
59
#include <argp.h>               /* struct argp_option, struct
59
60
                                   argp_state, struct argp,
69
70
#include <inttypes.h>           /* intmax_t, PRIdMAX, strtoimax() */
70
71
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_IOERR,
71
72
                                   EX_CONFIG, EX_UNAVAILABLE, EX_OK */
72
 
#include <errno.h>              /* errno */
73
 
#include <error.h>              /* error() */
74
 
#include <fnmatch.h>            /* fnmatch() */
75
73
 
76
74
#define BUFFER_SIZE 256
77
75
 
78
76
#define PDIR "/lib/mandos/plugins.d"
79
 
#define PHDIR "/lib/mandos/plugin-helpers"
80
77
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
81
78
 
82
79
const char *argp_program_version = "plugin-runner " VERSION;
83
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
80
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
84
81
 
85
82
typedef struct plugin{
86
83
  char *name;                   /* can be NULL or any plugin name */
106
103
 
107
104
/* Gets an existing plugin based on name,
108
105
   or if none is found, creates a new one */
109
 
__attribute__((warn_unused_result))
110
106
static plugin *getplugin(char *name){
111
107
  /* Check for existing plugin with that name */
112
108
  for(plugin *p = plugin_list; p != NULL; p = p->next){
173
169
}
174
170
 
175
171
/* Helper function for add_argument and add_environment */
176
 
__attribute__((nonnull, warn_unused_result))
177
172
static bool add_to_char_array(const char *new, char ***array,
178
173
                              int *len){
179
174
  /* Resize the pointed-to array to hold one more pointer */
180
 
  char **new_array = NULL;
181
175
  do {
182
 
    new_array = realloc(*array, sizeof(char *)
183
 
                        * (size_t) ((*len) + 2));
184
 
  } while(new_array == NULL and errno == EINTR);
 
176
    *array = realloc(*array, sizeof(char *)
 
177
                     * (size_t) ((*len) + 2));
 
178
  } while(*array == NULL and errno == EINTR);
185
179
  /* Malloc check */
186
 
  if(new_array == NULL){
 
180
  if(*array == NULL){
187
181
    return false;
188
182
  }
189
 
  *array = new_array;
190
183
  /* Make a copy of the new string */
191
184
  char *copy;
192
185
  do {
204
197
}
205
198
 
206
199
/* Add to a plugin's argument vector */
207
 
__attribute__((nonnull(2), warn_unused_result))
208
200
static bool add_argument(plugin *p, const char *arg){
209
201
  if(p == NULL){
210
202
    return false;
213
205
}
214
206
 
215
207
/* Add to a plugin's environment */
216
 
__attribute__((nonnull(2), warn_unused_result))
217
208
static bool add_environment(plugin *p, const char *def, bool replace){
218
209
  if(p == NULL){
219
210
    return false;
221
212
  /* namelen = length of name of environment variable */
222
213
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
223
214
  /* Search for this environment variable */
224
 
  for(char **envdef = p->environ; *envdef != NULL; envdef++){
225
 
    if(strncmp(*envdef, def, namelen + 1) == 0){
 
215
  for(char **e = p->environ; *e != NULL; e++){
 
216
    if(strncmp(*e, def, namelen + 1) == 0){
226
217
      /* It already exists */
227
218
      if(replace){
228
 
        char *new_envdef;
 
219
        char *new;
229
220
        do {
230
 
          new_envdef = realloc(*envdef, strlen(def) + 1);
231
 
        } while(new_envdef == NULL and errno == EINTR);
232
 
        if(new_envdef == NULL){
 
221
          new = realloc(*e, strlen(def) + 1);
 
222
        } while(new == NULL and errno == EINTR);
 
223
        if(new == NULL){
233
224
          return false;
234
225
        }
235
 
        *envdef = new_envdef;
236
 
        strcpy(*envdef, def);
 
226
        *e = new;
 
227
        strcpy(*e, def);
237
228
      }
238
229
      return true;
239
230
    }
241
232
  return add_to_char_array(def, &(p->environ), &(p->envc));
242
233
}
243
234
 
244
 
#ifndef O_CLOEXEC
245
235
/*
246
236
 * Based on the example in the GNU LibC manual chapter 13.13 "File
247
237
 * Descriptor Flags".
248
238
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
249
239
 */
250
 
__attribute__((warn_unused_result))
251
240
static int set_cloexec_flag(int fd){
252
241
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
253
242
  /* If reading the flags failed, return error indication now. */
258
247
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
259
248
                                       ret | FD_CLOEXEC));
260
249
}
261
 
#endif  /* not O_CLOEXEC */
262
250
 
263
251
 
264
252
/* Mark processes as completed when they exit, and save their exit
278
266
        /* No child processes */
279
267
        break;
280
268
      }
281
 
      error(0, errno, "waitpid");
 
269
      perror("waitpid");
282
270
    }
283
271
    
284
272
    /* A child exited, find it in process_list */
296
284
}
297
285
 
298
286
/* Prints out a password to stdout */
299
 
__attribute__((nonnull, warn_unused_result))
300
287
static bool print_out_password(const char *buffer, size_t length){
301
288
  ssize_t ret;
302
289
  for(size_t written = 0; written < length; written += (size_t)ret){
310
297
}
311
298
 
312
299
/* Removes and free a plugin from the plugin list */
313
 
__attribute__((nonnull))
314
300
static void free_plugin(plugin *plugin_node){
315
301
  
316
 
  for(char **arg = (plugin_node->argv)+1; *arg != NULL; arg++){
 
302
  for(char **arg = plugin_node->argv; *arg != NULL; arg++){
317
303
    free(*arg);
318
304
  }
319
 
  free(plugin_node->name);
320
305
  free(plugin_node->argv);
321
306
  for(char **env = plugin_node->environ; *env != NULL; env++){
322
307
    free(*env);
349
334
 
350
335
int main(int argc, char *argv[]){
351
336
  char *plugindir = NULL;
352
 
  char *pluginhelperdir = NULL;
353
337
  char *argfile = NULL;
354
338
  FILE *conffp;
355
 
  struct dirent **direntries = NULL;
 
339
  size_t d_name_len;
 
340
  DIR *dir = NULL;
 
341
  struct dirent *dirst;
356
342
  struct stat st;
357
343
  fd_set rfds_all;
358
344
  int ret, maxfd = 0;
366
352
                                      .sa_flags = SA_NOCLDSTOP };
367
353
  char **custom_argv = NULL;
368
354
  int custom_argc = 0;
369
 
  int dir_fd = -1;
370
355
  
371
356
  /* Establish a signal handler */
372
357
  sigemptyset(&sigchld_action.sa_mask);
373
358
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
374
359
  if(ret == -1){
375
 
    error(0, errno, "sigaddset");
 
360
    perror("sigaddset");
376
361
    exitstatus = EX_OSERR;
377
362
    goto fallback;
378
363
  }
379
364
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
380
365
  if(ret == -1){
381
 
    error(0, errno, "sigaction");
 
366
    perror("sigaction");
382
367
    exitstatus = EX_OSERR;
383
368
    goto fallback;
384
369
  }
417
402
      .doc = "Group ID the plugins will run as", .group = 3 },
418
403
    { .name = "debug", .key = 132,
419
404
      .doc = "Debug mode", .group = 4 },
420
 
    { .name = "plugin-helper-dir", .key = 133,
421
 
      .arg = "DIRECTORY",
422
 
      .doc = "Specify a different plugin helper directory",
423
 
      .group = 2 },
424
405
    /*
425
406
     * These reproduce what we would get without ARGP_NO_HELP
426
407
     */
433
414
    { .name = NULL }
434
415
  };
435
416
  
436
 
  __attribute__((nonnull(3)))
437
417
  error_t parse_opt(int key, char *arg, struct argp_state *state){
438
418
    errno = 0;
439
419
    switch(key){
440
420
      char *tmp;
441
 
      intmax_t tmp_id;
 
421
      intmax_t tmpmax;
442
422
    case 'g':                   /* --global-options */
443
423
      {
444
424
        char *plugin_option;
447
427
            break;
448
428
          }
449
429
        }
450
 
        errno = 0;
451
430
      }
452
431
      break;
453
432
    case 'G':                   /* --global-env */
454
 
      if(add_environment(getplugin(NULL), arg, true)){
455
 
        errno = 0;
456
 
      }
 
433
      add_environment(getplugin(NULL), arg, true);
457
434
      break;
458
435
    case 'o':                   /* --options-for */
459
436
      {
476
453
            break;
477
454
          }
478
455
        }
479
 
        errno = 0;
480
456
      }
481
457
      break;
482
458
    case 'E':                   /* --env-for */
494
470
          errno = EINVAL;
495
471
          break;
496
472
        }
497
 
        if(add_environment(getplugin(arg), envdef, true)){
498
 
          errno = 0;
499
 
        }
 
473
        add_environment(getplugin(arg), envdef, true);
500
474
      }
501
475
      break;
502
476
    case 'd':                   /* --disable */
504
478
        plugin *p = getplugin(arg);
505
479
        if(p != NULL){
506
480
          p->disabled = true;
507
 
          errno = 0;
508
481
        }
509
482
      }
510
483
      break;
513
486
        plugin *p = getplugin(arg);
514
487
        if(p != NULL){
515
488
          p->disabled = false;
516
 
          errno = 0;
517
489
        }
518
490
      }
519
491
      break;
520
492
    case 128:                   /* --plugin-dir */
521
493
      free(plugindir);
522
494
      plugindir = strdup(arg);
523
 
      if(plugindir != NULL){
524
 
        errno = 0;
525
 
      }
526
495
      break;
527
496
    case 129:                   /* --config-file */
528
497
      /* This is already done by parse_opt_config_file() */
529
498
      break;
530
499
    case 130:                   /* --userid */
531
 
      tmp_id = strtoimax(arg, &tmp, 10);
 
500
      tmpmax = strtoimax(arg, &tmp, 10);
532
501
      if(errno != 0 or tmp == arg or *tmp != '\0'
533
 
         or tmp_id != (uid_t)tmp_id){
 
502
         or tmpmax != (uid_t)tmpmax){
534
503
        argp_error(state, "Bad user ID number: \"%s\", using %"
535
504
                   PRIdMAX, arg, (intmax_t)uid);
536
505
        break;
537
506
      }
538
 
      uid = (uid_t)tmp_id;
539
 
      errno = 0;
 
507
      uid = (uid_t)tmpmax;
540
508
      break;
541
509
    case 131:                   /* --groupid */
542
 
      tmp_id = strtoimax(arg, &tmp, 10);
 
510
      tmpmax = strtoimax(arg, &tmp, 10);
543
511
      if(errno != 0 or tmp == arg or *tmp != '\0'
544
 
         or tmp_id != (gid_t)tmp_id){
 
512
         or tmpmax != (gid_t)tmpmax){
545
513
        argp_error(state, "Bad group ID number: \"%s\", using %"
546
514
                   PRIdMAX, arg, (intmax_t)gid);
547
515
        break;
548
516
      }
549
 
      gid = (gid_t)tmp_id;
550
 
      errno = 0;
 
517
      gid = (gid_t)tmpmax;
551
518
      break;
552
519
    case 132:                   /* --debug */
553
520
      debug = true;
554
521
      break;
555
 
    case 133:                   /* --plugin-helper-dir */
556
 
      free(pluginhelperdir);
557
 
      pluginhelperdir = strdup(arg);
558
 
      if(pluginhelperdir != NULL){
559
 
        errno = 0;
560
 
      }
561
 
      break;
562
522
      /*
563
523
       * These reproduce what we would get without ARGP_NO_HELP
564
524
       */
565
525
    case '?':                   /* --help */
566
526
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
567
527
      argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP);
568
 
      __builtin_unreachable();
569
528
    case -3:                    /* --usage */
570
529
      state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */
571
530
      argp_state_help(state, state->out_stream,
572
531
                      ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK);
573
 
      __builtin_unreachable();
574
532
    case 'V':                   /* --version */
575
533
      fprintf(state->out_stream, "%s\n", argp_program_version);
576
534
      exit(EXIT_SUCCESS);
586
544
      if(arg[0] == '\0'){
587
545
        break;
588
546
      }
589
 
#if __GNUC__ >= 7
590
 
      __attribute__((fallthrough));
591
 
#else
592
 
          /* FALLTHROUGH */
593
 
#endif
594
547
    default:
595
548
      return ARGP_ERR_UNKNOWN;
596
549
    }
615
568
    case 129:                   /* --config-file */
616
569
      free(argfile);
617
570
      argfile = strdup(arg);
618
 
      if(argfile != NULL){
619
 
        errno = 0;
620
 
      }
621
571
      break;
622
572
    case 130:                   /* --userid */
623
573
    case 131:                   /* --groupid */
624
574
    case 132:                   /* --debug */
625
 
    case 133:                   /* --plugin-helper-dir */
626
575
    case '?':                   /* --help */
627
576
    case -3:                    /* --usage */
628
577
    case 'V':                   /* --version */
650
599
  case ENOMEM:
651
600
  default:
652
601
    errno = ret;
653
 
    error(0, errno, "argp_parse");
 
602
    perror("argp_parse");
654
603
    exitstatus = EX_OSERR;
655
604
    goto fallback;
656
605
  case EINVAL:
677
626
    custom_argc = 1;
678
627
    custom_argv = malloc(sizeof(char*) * 2);
679
628
    if(custom_argv == NULL){
680
 
      error(0, errno, "malloc");
 
629
      perror("malloc");
681
630
      exitstatus = EX_OSERR;
682
631
      goto fallback;
683
632
    }
700
649
        }
701
650
        new_arg = strdup(p);
702
651
        if(new_arg == NULL){
703
 
          error(0, errno, "strdup");
 
652
          perror("strdup");
704
653
          exitstatus = EX_OSERR;
705
654
          free(org_line);
706
655
          goto fallback;
707
656
        }
708
657
        
709
658
        custom_argc += 1;
710
 
        {
711
 
          char **new_argv = realloc(custom_argv, sizeof(char *)
712
 
                                    * ((size_t)custom_argc + 1));
713
 
          if(new_argv == NULL){
714
 
            error(0, errno, "realloc");
715
 
            exitstatus = EX_OSERR;
716
 
            free(new_arg);
717
 
            free(org_line);
718
 
            goto fallback;
719
 
          } else {
720
 
            custom_argv = new_argv;
721
 
          }
 
659
        custom_argv = realloc(custom_argv, sizeof(char *)
 
660
                              * ((unsigned int) custom_argc + 1));
 
661
        if(custom_argv == NULL){
 
662
          perror("realloc");
 
663
          exitstatus = EX_OSERR;
 
664
          free(org_line);
 
665
          goto fallback;
722
666
        }
723
667
        custom_argv[custom_argc-1] = new_arg;
724
668
        custom_argv[custom_argc] = NULL;
728
672
      ret = fclose(conffp);
729
673
    } while(ret == EOF and errno == EINTR);
730
674
    if(ret == EOF){
731
 
      error(0, errno, "fclose");
 
675
      perror("fclose");
732
676
      exitstatus = EX_IOERR;
733
677
      goto fallback;
734
678
    }
737
681
    /* Check for harmful errors and go to fallback. Other errors might
738
682
       not affect opening plugins */
739
683
    if(errno == EMFILE or errno == ENFILE or errno == ENOMEM){
740
 
      error(0, errno, "fopen");
 
684
      perror("fopen");
741
685
      exitstatus = EX_OSERR;
742
686
      goto fallback;
743
687
    }
754
698
    case ENOMEM:
755
699
    default:
756
700
      errno = ret;
757
 
      error(0, errno, "argp_parse");
 
701
      perror("argp_parse");
758
702
      exitstatus = EX_OSERR;
759
703
      goto fallback;
760
704
    case EINVAL:
774
718
  case ENOMEM:
775
719
  default:
776
720
    errno = ret;
777
 
    error(0, errno, "argp_parse");
 
721
    perror("argp_parse");
778
722
    exitstatus = EX_OSERR;
779
723
    goto fallback;
780
724
  case EINVAL:
782
726
    goto fallback;
783
727
  }
784
728
  
785
 
  {
786
 
    char *pluginhelperenv;
787
 
    bool bret = true;
788
 
    ret = asprintf(&pluginhelperenv, "MANDOSPLUGINHELPERDIR=%s",
789
 
                   pluginhelperdir != NULL ? pluginhelperdir : PHDIR);
790
 
    if(ret != -1){
791
 
      bret = add_environment(getplugin(NULL), pluginhelperenv, true);
792
 
    }
793
 
    if(ret == -1 or not bret){
794
 
      error(0, errno, "Failed to set MANDOSPLUGINHELPERDIR"
795
 
            " environment variable to \"%s\" for all plugins\n",
796
 
            pluginhelperdir != NULL ? pluginhelperdir : PHDIR);
797
 
    }
798
 
    if(ret != -1){
799
 
      free(pluginhelperenv);
800
 
    }
801
 
  }
802
 
  
803
729
  if(debug){
804
 
    for(plugin *p = plugin_list; p != NULL; p = p->next){
 
730
    for(plugin *p = plugin_list; p != NULL; p=p->next){
805
731
      fprintf(stderr, "Plugin: %s has %d arguments\n",
806
732
              p->name ? p->name : "Global", p->argc - 1);
807
733
      for(char **a = p->argv; *a != NULL; a++){
814
740
    }
815
741
  }
816
742
  
817
 
  if(getuid() == 0){
818
 
    /* Work around Debian bug #633582:
819
 
       <https://bugs.debian.org/633582> */
820
 
    int plugindir_fd = open(/* plugindir or */ PDIR, O_RDONLY);
821
 
    if(plugindir_fd == -1){
822
 
      if(errno != ENOENT){
823
 
        error(0, errno, "open(\"" PDIR "\")");
824
 
      }
825
 
    } else {
826
 
      ret = (int)TEMP_FAILURE_RETRY(fstat(plugindir_fd, &st));
827
 
      if(ret == -1){
828
 
        error(0, errno, "fstat");
829
 
      } else {
830
 
        if(S_ISDIR(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
831
 
          ret = fchown(plugindir_fd, uid, gid);
832
 
          if(ret == -1){
833
 
            error(0, errno, "fchown");
834
 
          }
835
 
        }
836
 
      }
837
 
      close(plugindir_fd);
838
 
    }
839
 
  }
840
 
  
841
 
  /* Lower permissions */
842
 
  ret = setgid(gid);
 
743
  /* Strip permissions down to nobody */
 
744
  setgid(gid);
843
745
  if(ret == -1){
844
 
    error(0, errno, "setgid");
 
746
    perror("setgid");
845
747
  }
846
748
  ret = setuid(uid);
847
749
  if(ret == -1){
848
 
    error(0, errno, "setuid");
 
750
    perror("setuid");
849
751
  }
850
752
  
851
753
  /* Open plugin directory with close_on_exec flag */
852
754
  {
853
 
    dir_fd = open(plugindir != NULL ? plugindir : PDIR, O_RDONLY |
854
 
#ifdef O_CLOEXEC
855
 
                  O_CLOEXEC
856
 
#else  /* not O_CLOEXEC */
857
 
                  0
858
 
#endif  /* not O_CLOEXEC */
859
 
                  );
 
755
    int dir_fd = -1;
 
756
    if(plugindir == NULL){
 
757
      dir_fd = open(PDIR, O_RDONLY |
 
758
#ifdef O_CLOEXEC
 
759
                    O_CLOEXEC
 
760
#else  /* not O_CLOEXEC */
 
761
                    0
 
762
#endif  /* not O_CLOEXEC */
 
763
                    );
 
764
    } else {
 
765
      dir_fd = open(plugindir, O_RDONLY |
 
766
#ifdef O_CLOEXEC
 
767
                    O_CLOEXEC
 
768
#else  /* not O_CLOEXEC */
 
769
                    0
 
770
#endif  /* not O_CLOEXEC */
 
771
                    );
 
772
    }
860
773
    if(dir_fd == -1){
861
 
      error(0, errno, "Could not open plugin dir");
 
774
      perror("Could not open plugin dir");
862
775
      exitstatus = EX_UNAVAILABLE;
863
776
      goto fallback;
864
777
    }
867
780
  /* Set the FD_CLOEXEC flag on the directory */
868
781
    ret = set_cloexec_flag(dir_fd);
869
782
    if(ret < 0){
870
 
      error(0, errno, "set_cloexec_flag");
 
783
      perror("set_cloexec_flag");
 
784
      TEMP_FAILURE_RETRY(close(dir_fd));
871
785
      exitstatus = EX_OSERR;
872
786
      goto fallback;
873
787
    }
874
788
#endif  /* O_CLOEXEC */
875
 
  }
876
 
  
877
 
  int good_name(const struct dirent * const dirent){
878
 
    const char * const patterns[] = { ".*", "#*#", "*~", "*.dpkg-new",
879
 
                                      "*.dpkg-old", "*.dpkg-bak",
880
 
                                      "*.dpkg-divert", NULL };
881
 
#ifdef __GNUC__
882
 
#pragma GCC diagnostic push
883
 
#pragma GCC diagnostic ignored "-Wcast-qual"
884
 
#endif
885
 
    for(const char **pat = (const char **)patterns;
886
 
        *pat != NULL; pat++){
887
 
#ifdef __GNUC__
888
 
#pragma GCC diagnostic pop
889
 
#endif
890
 
      if(fnmatch(*pat, dirent->d_name, FNM_FILE_NAME | FNM_PERIOD)
891
 
         != FNM_NOMATCH){
892
 
        if(debug){
893
 
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
894
 
                    " matching pattern %s\n", dirent->d_name, *pat);
895
 
        }
896
 
        return 0;
897
 
      }
 
789
    
 
790
    dir = fdopendir(dir_fd);
 
791
    if(dir == NULL){
 
792
      perror("Could not open plugin dir");
 
793
      TEMP_FAILURE_RETRY(close(dir_fd));
 
794
      exitstatus = EX_OSERR;
 
795
      goto fallback;
898
796
    }
899
 
    return 1;
900
 
  }
901
 
  
902
 
  int numplugins = scandirat(dir_fd, ".", &direntries, good_name,
903
 
                             alphasort);
904
 
  if(numplugins == -1){
905
 
    error(0, errno, "Could not scan plugin dir");
906
 
    direntries = NULL;
907
 
    exitstatus = EX_OSERR;
908
 
    goto fallback;
909
797
  }
910
798
  
911
799
  FD_ZERO(&rfds_all);
912
800
  
913
801
  /* Read and execute any executable in the plugin directory*/
914
 
  for(int i = 0; i < numplugins; i++){
915
 
    
916
 
    int plugin_fd = openat(dir_fd, direntries[i]->d_name, O_RDONLY);
917
 
    if(plugin_fd == -1){
918
 
      error(0, errno, "Could not open plugin");
919
 
      free(direntries[i]);
 
802
  while(true){
 
803
    do {
 
804
      dirst = readdir(dir);
 
805
    } while(dirst == NULL and errno == EINTR);
 
806
    
 
807
    /* All directory entries have been processed */
 
808
    if(dirst == NULL){
 
809
      if(errno == EBADF){
 
810
        perror("readdir");
 
811
        exitstatus = EX_IOERR;
 
812
        goto fallback;
 
813
      }
 
814
      break;
 
815
    }
 
816
    
 
817
    d_name_len = strlen(dirst->d_name);
 
818
    
 
819
    /* Ignore dotfiles, backup files and other junk */
 
820
    {
 
821
      bool bad_name = false;
 
822
      
 
823
      const char const *bad_prefixes[] = { ".", "#", NULL };
 
824
      
 
825
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
 
826
                                           ".dpkg-old",
 
827
                                           ".dpkg-bak",
 
828
                                           ".dpkg-divert", NULL };
 
829
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
 
830
        size_t pre_len = strlen(*pre);
 
831
        if((d_name_len >= pre_len)
 
832
           and strncmp((dirst->d_name), *pre, pre_len) == 0){
 
833
          if(debug){
 
834
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
835
                    " with bad prefix %s\n", dirst->d_name, *pre);
 
836
          }
 
837
          bad_name = true;
 
838
          break;
 
839
        }
 
840
      }
 
841
      if(bad_name){
 
842
        continue;
 
843
      }
 
844
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
 
845
        size_t suf_len = strlen(*suf);
 
846
        if((d_name_len >= suf_len)
 
847
           and (strcmp((dirst->d_name) + d_name_len-suf_len, *suf)
 
848
                == 0)){
 
849
          if(debug){
 
850
            fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
851
                    " with bad suffix %s\n", dirst->d_name, *suf);
 
852
          }
 
853
          bad_name = true;
 
854
          break;
 
855
        }
 
856
      }
 
857
      
 
858
      if(bad_name){
 
859
        continue;
 
860
      }
 
861
    }
 
862
    
 
863
    char *filename;
 
864
    if(plugindir == NULL){
 
865
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, PDIR "/%s",
 
866
                                             dirst->d_name));
 
867
    } else {
 
868
      ret = (int)TEMP_FAILURE_RETRY(asprintf(&filename, "%s/%s",
 
869
                                             plugindir,
 
870
                                             dirst->d_name));
 
871
    }
 
872
    if(ret < 0){
 
873
      perror("asprintf");
920
874
      continue;
921
875
    }
922
 
    ret = (int)TEMP_FAILURE_RETRY(fstat(plugin_fd, &st));
 
876
    
 
877
    ret = (int)TEMP_FAILURE_RETRY(stat(filename, &st));
923
878
    if(ret == -1){
924
 
      error(0, errno, "stat");
925
 
      close(plugin_fd);
926
 
      free(direntries[i]);
 
879
      perror("stat");
 
880
      free(filename);
927
881
      continue;
928
882
    }
929
883
    
930
884
    /* Ignore non-executable files */
931
885
    if(not S_ISREG(st.st_mode)
932
 
       or (TEMP_FAILURE_RETRY(faccessat(dir_fd, direntries[i]->d_name,
933
 
                                        X_OK, 0)) != 0)){
 
886
       or (TEMP_FAILURE_RETRY(access(filename, X_OK)) != 0)){
934
887
      if(debug){
935
 
        fprintf(stderr, "Ignoring plugin dir entry \"%s/%s\""
936
 
                " with bad type or mode\n",
937
 
                plugindir != NULL ? plugindir : PDIR,
938
 
                direntries[i]->d_name);
 
888
        fprintf(stderr, "Ignoring plugin dir entry \"%s\""
 
889
                " with bad type or mode\n", filename);
939
890
      }
940
 
      close(plugin_fd);
941
 
      free(direntries[i]);
 
891
      free(filename);
942
892
      continue;
943
893
    }
944
894
    
945
 
    plugin *p = getplugin(direntries[i]->d_name);
 
895
    plugin *p = getplugin(dirst->d_name);
946
896
    if(p == NULL){
947
 
      error(0, errno, "getplugin");
948
 
      close(plugin_fd);
949
 
      free(direntries[i]);
 
897
      perror("getplugin");
 
898
      free(filename);
950
899
      continue;
951
900
    }
952
901
    if(p->disabled){
953
902
      if(debug){
954
903
        fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
955
 
                direntries[i]->d_name);
 
904
                dirst->d_name);
956
905
      }
957
 
      close(plugin_fd);
958
 
      free(direntries[i]);
 
906
      free(filename);
959
907
      continue;
960
908
    }
961
909
    {
964
912
      if(g != NULL){
965
913
        for(char **a = g->argv + 1; *a != NULL; a++){
966
914
          if(not add_argument(p, *a)){
967
 
            error(0, errno, "add_argument");
 
915
            perror("add_argument");
968
916
          }
969
917
        }
970
918
        /* Add global environment variables */
971
919
        for(char **e = g->environ; *e != NULL; e++){
972
920
          if(not add_environment(p, *e, false)){
973
 
            error(0, errno, "add_environment");
 
921
            perror("add_environment");
974
922
          }
975
923
        }
976
924
      }
977
925
    }
978
 
    /* If this plugin has any environment variables, we need to
979
 
       duplicate the environment from this process, too. */
 
926
    /* If this plugin has any environment variables, we will call
 
927
       using execve and need to duplicate the environment from this
 
928
       process, too. */
980
929
    if(p->environ[0] != NULL){
981
930
      for(char **e = environ; *e != NULL; e++){
982
931
        if(not add_environment(p, *e, false)){
983
 
          error(0, errno, "add_environment");
 
932
          perror("add_environment");
984
933
        }
985
934
      }
986
935
    }
987
936
    
988
937
    int pipefd[2];
989
 
#ifndef O_CLOEXEC
990
938
    ret = (int)TEMP_FAILURE_RETRY(pipe(pipefd));
991
 
#else  /* O_CLOEXEC */
992
 
    ret = (int)TEMP_FAILURE_RETRY(pipe2(pipefd, O_CLOEXEC));
993
 
#endif  /* O_CLOEXEC */
994
939
    if(ret == -1){
995
 
      error(0, errno, "pipe");
996
 
      exitstatus = EX_OSERR;
997
 
      free(direntries[i]);
998
 
      goto fallback;
999
 
    }
1000
 
    if(pipefd[0] >= FD_SETSIZE){
1001
 
      fprintf(stderr, "pipe()[0] (%d) >= FD_SETSIZE (%d)", pipefd[0],
1002
 
              FD_SETSIZE);
1003
 
      close(pipefd[0]);
1004
 
      close(pipefd[1]);
1005
 
      exitstatus = EX_OSERR;
1006
 
      free(direntries[i]);
1007
 
      goto fallback;
1008
 
    }
1009
 
#ifndef O_CLOEXEC
 
940
      perror("pipe");
 
941
      exitstatus = EX_OSERR;
 
942
      goto fallback;
 
943
    }
1010
944
    /* Ask OS to automatic close the pipe on exec */
1011
945
    ret = set_cloexec_flag(pipefd[0]);
1012
946
    if(ret < 0){
1013
 
      error(0, errno, "set_cloexec_flag");
1014
 
      close(pipefd[0]);
1015
 
      close(pipefd[1]);
 
947
      perror("set_cloexec_flag");
1016
948
      exitstatus = EX_OSERR;
1017
 
      free(direntries[i]);
1018
949
      goto fallback;
1019
950
    }
1020
951
    ret = set_cloexec_flag(pipefd[1]);
1021
952
    if(ret < 0){
1022
 
      error(0, errno, "set_cloexec_flag");
1023
 
      close(pipefd[0]);
1024
 
      close(pipefd[1]);
 
953
      perror("set_cloexec_flag");
1025
954
      exitstatus = EX_OSERR;
1026
 
      free(direntries[i]);
1027
955
      goto fallback;
1028
956
    }
1029
 
#endif  /* not O_CLOEXEC */
1030
957
    /* Block SIGCHLD until process is safely in process list */
1031
958
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_BLOCK,
1032
959
                                              &sigchld_action.sa_mask,
1033
960
                                              NULL));
1034
961
    if(ret < 0){
1035
 
      error(0, errno, "sigprocmask");
 
962
      perror("sigprocmask");
1036
963
      exitstatus = EX_OSERR;
1037
 
      free(direntries[i]);
1038
964
      goto fallback;
1039
965
    }
1040
966
    /* Starting a new process to be watched */
1043
969
      pid = fork();
1044
970
    } while(pid == -1 and errno == EINTR);
1045
971
    if(pid == -1){
1046
 
      error(0, errno, "fork");
1047
 
      TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
1048
 
                                     &sigchld_action.sa_mask, NULL));
1049
 
      close(pipefd[0]);
1050
 
      close(pipefd[1]);
 
972
      perror("fork");
1051
973
      exitstatus = EX_OSERR;
1052
 
      free(direntries[i]);
1053
974
      goto fallback;
1054
975
    }
1055
976
    if(pid == 0){
1056
977
      /* this is the child process */
1057
978
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1058
979
      if(ret < 0){
1059
 
        error(0, errno, "sigaction");
 
980
        perror("sigaction");
1060
981
        _exit(EX_OSERR);
1061
982
      }
1062
983
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
1063
984
      if(ret < 0){
1064
 
        error(0, errno, "sigprocmask");
 
985
        perror("sigprocmask");
1065
986
        _exit(EX_OSERR);
1066
987
      }
1067
988
      
1068
989
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
1069
990
      if(ret == -1){
1070
 
        error(0, errno, "dup2");
 
991
        perror("dup2");
1071
992
        _exit(EX_OSERR);
1072
993
      }
1073
994
      
1074
 
      if(fexecve(plugin_fd, p->argv,
1075
 
                (p->environ[0] != NULL) ? p->environ : environ) < 0){
1076
 
        error(0, errno, "fexecve for %s/%s",
1077
 
              plugindir != NULL ? plugindir : PDIR,
1078
 
              direntries[i]->d_name);
1079
 
        _exit(EX_OSERR);
 
995
      if(dirfd(dir) < 0){
 
996
        /* If dir has no file descriptor, we could not set FD_CLOEXEC
 
997
           above and must now close it manually here. */
 
998
        closedir(dir);
 
999
      }
 
1000
      if(p->environ[0] == NULL){
 
1001
        if(execv(filename, p->argv) < 0){
 
1002
          perror("execv");
 
1003
          _exit(EX_OSERR);
 
1004
        }
 
1005
      } else {
 
1006
        if(execve(filename, p->argv, p->environ) < 0){
 
1007
          perror("execve");
 
1008
          _exit(EX_OSERR);
 
1009
        }
1080
1010
      }
1081
1011
      /* no return */
1082
1012
    }
1083
1013
    /* Parent process */
1084
 
    close(pipefd[1]);           /* Close unused write end of pipe */
1085
 
    close(plugin_fd);
1086
 
    plugin *new_plugin = getplugin(direntries[i]->d_name);
 
1014
    TEMP_FAILURE_RETRY(close(pipefd[1])); /* Close unused write end of
 
1015
                                             pipe */
 
1016
    free(filename);
 
1017
    plugin *new_plugin = getplugin(dirst->d_name);
1087
1018
    if(new_plugin == NULL){
1088
 
      error(0, errno, "getplugin");
 
1019
      perror("getplugin");
1089
1020
      ret = (int)(TEMP_FAILURE_RETRY
1090
1021
                  (sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask,
1091
1022
                               NULL)));
1092
1023
      if(ret < 0){
1093
 
        error(0, errno, "sigprocmask");
 
1024
        perror("sigprocmask");
1094
1025
      }
1095
1026
      exitstatus = EX_OSERR;
1096
 
      free(direntries[i]);
1097
1027
      goto fallback;
1098
1028
    }
1099
 
    free(direntries[i]);
1100
1029
    
1101
1030
    new_plugin->pid = pid;
1102
1031
    new_plugin->fd = pipefd[0];
1103
 
 
1104
 
    if(debug){
1105
 
      fprintf(stderr, "Plugin %s started (PID %" PRIdMAX ")\n",
1106
 
              new_plugin->name, (intmax_t) (new_plugin->pid));
1107
 
    }
1108
 
 
 
1032
    
1109
1033
    /* Unblock SIGCHLD so signal handler can be run if this process
1110
1034
       has already completed */
1111
1035
    ret = (int)TEMP_FAILURE_RETRY(sigprocmask(SIG_UNBLOCK,
1112
1036
                                              &sigchld_action.sa_mask,
1113
1037
                                              NULL));
1114
1038
    if(ret < 0){
1115
 
      error(0, errno, "sigprocmask");
 
1039
      perror("sigprocmask");
1116
1040
      exitstatus = EX_OSERR;
1117
1041
      goto fallback;
1118
1042
    }
1119
1043
    
1120
 
    FD_SET(new_plugin->fd, &rfds_all);
 
1044
    FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from
 
1045
                                          -Wconversion */
1121
1046
    
1122
1047
    if(maxfd < new_plugin->fd){
1123
1048
      maxfd = new_plugin->fd;
1124
1049
    }
1125
1050
  }
1126
1051
  
1127
 
  free(direntries);
1128
 
  direntries = NULL;
1129
 
  close(dir_fd);
1130
 
  dir_fd = -1;
 
1052
  TEMP_FAILURE_RETRY(closedir(dir));
 
1053
  dir = NULL;
1131
1054
  free_plugin(getplugin(NULL));
1132
1055
  
1133
1056
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1146
1069
    fd_set rfds = rfds_all;
1147
1070
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
1148
1071
    if(select_ret == -1 and errno != EINTR){
1149
 
      error(0, errno, "select");
 
1072
      perror("select");
1150
1073
      exitstatus = EX_OSERR;
1151
1074
      goto fallback;
1152
1075
    }
1172
1095
                      (intmax_t) (proc->pid),
1173
1096
                      WTERMSIG(proc->status),
1174
1097
                      strsignal(WTERMSIG(proc->status)));
 
1098
            } else if(WCOREDUMP(proc->status)){
 
1099
              fprintf(stderr, "Plugin %s [%" PRIdMAX "] dumped"
 
1100
                      " core\n", proc->name, (intmax_t) (proc->pid));
1175
1101
            }
1176
1102
          }
1177
1103
          
1178
1104
          /* Remove the plugin */
1179
 
          FD_CLR(proc->fd, &rfds_all);
 
1105
          FD_CLR(proc->fd, &rfds_all); /* Spurious warning from
 
1106
                                          -Wconversion */
1180
1107
          
1181
1108
          /* Block signal while modifying process_list */
1182
1109
          ret = (int)TEMP_FAILURE_RETRY(sigprocmask
1184
1111
                                         &sigchld_action.sa_mask,
1185
1112
                                         NULL));
1186
1113
          if(ret < 0){
1187
 
            error(0, errno, "sigprocmask");
 
1114
            perror("sigprocmask");
1188
1115
            exitstatus = EX_OSERR;
1189
1116
            goto fallback;
1190
1117
          }
1198
1125
                      (sigprocmask(SIG_UNBLOCK,
1199
1126
                                   &sigchld_action.sa_mask, NULL)));
1200
1127
          if(ret < 0){
1201
 
            error(0, errno, "sigprocmask");
 
1128
            perror("sigprocmask");
1202
1129
            exitstatus = EX_OSERR;
1203
1130
            goto fallback;
1204
1131
          }
1215
1142
        bool bret = print_out_password(proc->buffer,
1216
1143
                                       proc->buffer_length);
1217
1144
        if(not bret){
1218
 
          error(0, errno, "print_out_password");
 
1145
          perror("print_out_password");
1219
1146
          exitstatus = EX_IOERR;
1220
1147
        }
1221
1148
        goto fallback;
1222
1149
      }
1223
1150
      
1224
1151
      /* This process has not completed.  Does it have any output? */
1225
 
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
 
1152
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious
 
1153
                                                         warning from
 
1154
                                                         -Wconversion */
1226
1155
        /* This process had nothing to say at this time */
1227
1156
        proc = proc->next;
1228
1157
        continue;
1229
1158
      }
1230
1159
      /* Before reading, make the process' data buffer large enough */
1231
1160
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
1232
 
        char *new_buffer = realloc(proc->buffer, proc->buffer_size
1233
 
                                   + (size_t) BUFFER_SIZE);
1234
 
        if(new_buffer == NULL){
1235
 
          error(0, errno, "malloc");
 
1161
        proc->buffer = realloc(proc->buffer, proc->buffer_size
 
1162
                               + (size_t) BUFFER_SIZE);
 
1163
        if(proc->buffer == NULL){
 
1164
          perror("malloc");
1236
1165
          exitstatus = EX_OSERR;
1237
1166
          goto fallback;
1238
1167
        }
1239
 
        proc->buffer = new_buffer;
1240
1168
        proc->buffer_size += BUFFER_SIZE;
1241
1169
      }
1242
1170
      /* Read from the process */
1276
1204
    }
1277
1205
    bret = print_out_password(passwordbuffer, len);
1278
1206
    if(not bret){
1279
 
      error(0, errno, "print_out_password");
 
1207
      perror("print_out_password");
1280
1208
      exitstatus = EX_IOERR;
1281
1209
    }
1282
1210
  }
1284
1212
  /* Restore old signal handler */
1285
1213
  ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
1286
1214
  if(ret == -1){
1287
 
    error(0, errno, "sigaction");
 
1215
    perror("sigaction");
1288
1216
    exitstatus = EX_OSERR;
1289
1217
  }
1290
1218
  
1295
1223
    free(custom_argv);
1296
1224
  }
1297
1225
  
1298
 
  free(direntries);
1299
 
  
1300
 
  if(dir_fd != -1){
1301
 
    close(dir_fd);
 
1226
  if(dir != NULL){
 
1227
    closedir(dir);
1302
1228
  }
1303
1229
  
1304
1230
  /* Kill the processes */
1308
1234
      ret = kill(p->pid, SIGTERM);
1309
1235
      if(ret == -1 and errno != ESRCH){
1310
1236
        /* Set-uid proccesses might not get closed */
1311
 
        error(0, errno, "kill");
 
1237
        perror("kill");
1312
1238
      }
1313
1239
    }
1314
1240
  }
1318
1244
    ret = wait(NULL);
1319
1245
  } while(ret >= 0);
1320
1246
  if(errno != ECHILD){
1321
 
    error(0, errno, "wait");
 
1247
    perror("wait");
1322
1248
  }
1323
1249
  
1324
1250
  free_plugin_list();
1325
1251
  
1326
1252
  free(plugindir);
1327
 
  free(pluginhelperdir);
1328
1253
  free(argfile);
1329
1254
  
1330
1255
  return exitstatus;