/mandos/trunk

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

« back to all changes in this revision

Viewing changes to plugin-runner.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-31 16:04:47 UTC
  • mfrom: (24.1.77 mandos)
  • Revision ID: teddy@fukt.bsnet.se-20080831160447-2xte5k90onspphki
Merge.

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 Teddy Hogeborn & Björn Påhlsson
 
5
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
6
6
 * 
7
7
 * This program is free software: you can redistribute it and/or
8
8
 * modify it under the terms of the GNU General Public License as
27
27
#include <stdlib.h>             /* malloc(), exit(), EXIT_FAILURE,
28
28
                                   EXIT_SUCCESS, realloc() */
29
29
#include <stdbool.h>            /* bool, true, false */
30
 
#include <stdio.h>              /* perror, fileno(), fprintf(),
31
 
                                   stderr, STDOUT_FILENO */
 
30
#include <stdio.h>              /* perror, popen(), fileno(),
 
31
                                   fprintf(), stderr, STDOUT_FILENO */
32
32
#include <sys/types.h>          /* DIR, opendir(), stat(), struct
33
33
                                   stat, waitpid(), WIFEXITED(),
34
34
                                   WEXITSTATUS(), wait(), pid_t,
46
46
                                   fcntl(), setuid(), setgid(),
47
47
                                   F_GETFD, F_SETFD, FD_CLOEXEC,
48
48
                                   access(), pipe(), fork(), close()
49
 
                                   dup2(), STDOUT_FILENO, _exit(),
 
49
                                   dup2, STDOUT_FILENO, _exit(),
50
50
                                   execv(), write(), read(),
51
51
                                   close() */
52
52
#include <fcntl.h>              /* fcntl(), F_GETFD, F_SETFD,
69
69
#define PDIR "/lib/mandos/plugins.d"
70
70
#define AFILE "/conf/conf.d/mandos/plugin-runner.conf"
71
71
 
72
 
const char *argp_program_version = "plugin-runner " VERSION;
 
72
const char *argp_program_version = "plugin-runner 1.0";
73
73
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
74
74
 
 
75
struct plugin;
 
76
 
75
77
typedef struct plugin{
76
78
  char *name;                   /* can be NULL or any plugin name */
77
79
  char **argv;
94
96
 
95
97
static plugin *plugin_list = NULL;
96
98
 
97
 
/* Gets an existing plugin based on name,
 
99
/* Gets a existing plugin based on name,
98
100
   or if none is found, creates a new one */
99
101
static plugin *getplugin(char *name){
100
102
  /* Check for exiting plugin with that name */
116
118
      return NULL;
117
119
    }
118
120
  }
119
 
  
 
121
 
120
122
  *new_plugin = (plugin) { .name = copy_name,
121
123
                           .argc = 1,
122
124
                           .disabled = false,
130
132
  }
131
133
  new_plugin->argv[0] = copy_name;
132
134
  new_plugin->argv[1] = NULL;
133
 
  
 
135
 
134
136
  new_plugin->environ = malloc(sizeof(char *));
135
137
  if(new_plugin->environ == NULL){
136
138
    free(copy_name);
139
141
    return NULL;
140
142
  }
141
143
  new_plugin->environ[0] = NULL;
142
 
  
 
144
 
143
145
  /* Append the new plugin to the list */
144
146
  plugin_list = new_plugin;
145
147
  return new_plugin;
177
179
}
178
180
 
179
181
/* Add to a plugin's environment */
180
 
static bool add_environment(plugin *p, const char *def, bool replace){
 
182
static bool add_environment(plugin *p, const char *def){
181
183
  if(p == NULL){
182
184
    return false;
183
185
  }
184
 
  /* namelen = length of name of environment variable */
185
 
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
186
 
  /* Search for this environment variable */
187
 
  for(char **e = p->environ; *e != NULL; e++){
188
 
    if(strncmp(*e, def, namelen + 1) == 0){
189
 
      /* It already exists */
190
 
      if(replace){
191
 
        char *new = realloc(*e, strlen(def) + 1);
192
 
        if(new == NULL){
193
 
          return false;
194
 
        }
195
 
        *e = new;
196
 
        strcpy(*e, def);
197
 
      }
198
 
      return true;
199
 
    }
200
 
  }
201
186
  return add_to_char_array(def, &(p->environ), &(p->envc));
202
187
}
203
188
 
206
191
 * Descriptor Flags".
207
192
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
208
193
 */
209
 
static int set_cloexec_flag(int fd){
 
194
static int set_cloexec_flag(int fd)
 
195
{
210
196
  int ret = fcntl(fd, F_GETFD, 0);
211
197
  /* If reading the flags failed, return error indication now. */
212
198
  if(ret < 0){
219
205
 
220
206
/* Mark processes as completed when they exit, and save their exit
221
207
   status. */
222
 
static void handle_sigchld(__attribute__((unused)) int sig){
 
208
void handle_sigchld(__attribute__((unused)) int sig){
223
209
  while(true){
224
210
    plugin *proc = plugin_list;
225
211
    int status;
235
221
      /* No child processes */
236
222
      break;
237
223
    }
238
 
    
 
224
 
239
225
    /* A child exited, find it in process_list */
240
226
    while(proc != NULL and proc->pid != pid){
241
227
      proc = proc->next;
250
236
}
251
237
 
252
238
/* Prints out a password to stdout */
253
 
static bool print_out_password(const char *buffer, size_t length){
 
239
bool print_out_password(const char *buffer, size_t length){
254
240
  ssize_t ret;
 
241
  if(length>0 and buffer[length-1] == '\n'){
 
242
    length--;
 
243
  }
255
244
  for(size_t written = 0; written < length; written += (size_t)ret){
256
245
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
257
246
                                   length - written));
338
327
    { .name = "global-options", .key = 'g',
339
328
      .arg = "OPTION[,OPTION[,...]]",
340
329
      .doc = "Options passed to all plugins" },
341
 
    { .name = "global-env", .key = 'G',
 
330
    { .name = "global-envs", .key = 'e',
342
331
      .arg = "VAR=value",
343
332
      .doc = "Environment variable passed to all plugins" },
344
333
    { .name = "options-for", .key = 'o',
345
334
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
346
335
      .doc = "Options passed only to specified plugin" },
347
 
    { .name = "env-for", .key = 'E',
 
336
    { .name = "envs-for", .key = 'f',
348
337
      .arg = "PLUGIN:ENV=value",
349
338
      .doc = "Environment variable passed to specified plugin" },
350
339
    { .name = "disable", .key = 'd',
351
340
      .arg = "PLUGIN",
352
341
      .doc = "Disable a specific plugin", .group = 1 },
353
 
    { .name = "enable", .key = 'e',
354
 
      .arg = "PLUGIN",
355
 
      .doc = "Enable a specific plugin", .group = 1 },
356
342
    { .name = "plugin-dir", .key = 128,
357
343
      .arg = "DIRECTORY",
358
344
      .doc = "Specify a different plugin directory", .group = 2 },
370
356
    { .name = NULL }
371
357
  };
372
358
  
373
 
  error_t parse_opt (int key, char *arg, __attribute__((unused))
374
 
                     struct argp_state *state) {
 
359
  error_t parse_opt (int key, char *arg, __attribute__((unused)) struct argp_state *state) {
 
360
    /* Get the INPUT argument from `argp_parse', which we know is a
 
361
       pointer to our plugin list pointer. */
375
362
    switch (key) {
376
363
    case 'g':                   /* --global-options */
377
364
      if (arg != NULL){
387
374
        }
388
375
      }
389
376
      break;
390
 
    case 'G':                   /* --global-env */
 
377
    case 'e':                   /* --global-envs */
391
378
      if(arg == NULL){
392
379
        break;
393
380
      }
394
 
      if(not add_environment(getplugin(NULL), arg, true)){
395
 
        perror("add_environment");
 
381
      {
 
382
        char *envdef = strdup(arg);
 
383
        if(envdef == NULL){
 
384
          break;
 
385
        }
 
386
        if(not add_environment(getplugin(NULL), envdef)){
 
387
          perror("add_environment");
 
388
        }
396
389
      }
397
390
      break;
398
391
    case 'o':                   /* --options-for */
399
392
      if (arg != NULL){
400
393
        char *p_name = strsep(&arg, ":");
401
 
        if(p_name[0] == '\0' or arg == NULL){
 
394
        if(p_name[0] == '\0'){
402
395
          break;
403
396
        }
404
397
        char *opt = strsep(&arg, ":");
405
 
        if(opt[0] == '\0' or opt == NULL){
 
398
        if(opt[0] == '\0'){
406
399
          break;
407
400
        }
408
 
        char *p;
409
 
        while((p = strsep(&opt, ",")) != NULL){
410
 
          if(p[0] == '\0'){
411
 
            continue;
412
 
          }
413
 
          if(not add_argument(getplugin(p_name), p)){
414
 
            perror("add_argument");
415
 
            return ARGP_ERR_UNKNOWN;
 
401
        if(opt != NULL){
 
402
          char *p;
 
403
          while((p = strsep(&opt, ",")) != NULL){
 
404
            if(p[0] == '\0'){
 
405
              continue;
 
406
            }
 
407
            if(not add_argument(getplugin(p_name), p)){
 
408
              perror("add_argument");
 
409
              return ARGP_ERR_UNKNOWN;
 
410
            }
416
411
          }
417
412
        }
418
413
      }
419
414
      break;
420
 
    case 'E':                   /* --env-for */
 
415
    case 'f':                   /* --envs-for */
421
416
      if(arg == NULL){
422
417
        break;
423
418
      }
426
421
        if(envdef == NULL){
427
422
          break;
428
423
        }
429
 
        *envdef = '\0';
430
 
        if(not add_environment(getplugin(arg), envdef+1, true)){
 
424
        char *p_name = strndup(arg, (size_t) (envdef-arg));
 
425
        if(p_name == NULL){
 
426
          break;
 
427
        }
 
428
        envdef++;
 
429
        if(not add_environment(getplugin(p_name), envdef)){
431
430
          perror("add_environment");
432
431
        }
433
432
      }
441
440
        p->disabled = true;
442
441
      }
443
442
      break;
444
 
    case 'e':                   /* --enable */
445
 
      if (arg != NULL){
446
 
        plugin *p = getplugin(arg);
447
 
        if(p == NULL){
448
 
          return ARGP_ERR_UNKNOWN;
449
 
        }
450
 
        p->disabled = false;
451
 
      }
452
 
      break;
453
443
    case 128:                   /* --plugin-dir */
454
 
      free(plugindir);
455
444
      plugindir = strdup(arg);
456
445
      if(plugindir == NULL){
457
446
        perror("strdup");
458
447
      }      
459
448
      break;
460
449
    case 129:                   /* --config-file */
461
 
      /* This is already done by parse_opt_config_file() */
462
 
      break;
 
450
      argfile = strdup(arg);
 
451
      if(argfile == NULL){
 
452
        perror("strdup");
 
453
      }
 
454
      break;      
463
455
    case 130:                   /* --userid */
464
456
      uid = (uid_t)strtol(arg, NULL, 10);
465
457
      break;
470
462
      debug = true;
471
463
      break;
472
464
    case ARGP_KEY_ARG:
473
 
      /* Cryptsetup always passes an argument, which is an empty
474
 
         string if "none" was specified in /etc/crypttab.  So if
475
 
         argument was empty, we ignore it silently. */
476
 
      if(arg[0] != '\0'){
477
 
        fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
478
 
      }
479
 
      break;
480
 
    case ARGP_KEY_END:
481
 
      break;
482
 
    default:
483
 
      return ARGP_ERR_UNKNOWN;
484
 
    }
485
 
    return 0;
486
 
  }
487
 
  
488
 
  /* This option parser is the same as parse_opt() above, except it
489
 
     ignores everything but the --config-file option. */
490
 
  error_t parse_opt_config_file (int key, char *arg,
491
 
                                 __attribute__((unused))
492
 
                                 struct argp_state *state) {
493
 
    switch (key) {
494
 
    case 'g':                   /* --global-options */
495
 
    case 'G':                   /* --global-env */
496
 
    case 'o':                   /* --options-for */
497
 
    case 'E':                   /* --env-for */
498
 
    case 'd':                   /* --disable */
499
 
    case 'e':                   /* --enable */
500
 
    case 128:                   /* --plugin-dir */
501
 
      break;
502
 
    case 129:                   /* --config-file */
503
 
      free(argfile);
504
 
      argfile = strdup(arg);
505
 
      if(argfile == NULL){
506
 
        perror("strdup");
507
 
      }
508
 
      break;      
509
 
    case 130:                   /* --userid */
510
 
    case 131:                   /* --groupid */
511
 
    case 132:                   /* --debug */
512
 
    case ARGP_KEY_ARG:
513
 
    case ARGP_KEY_END:
514
 
      break;
515
 
    default:
516
 
      return ARGP_ERR_UNKNOWN;
517
 
    }
518
 
    return 0;
519
 
  }
520
 
  
521
 
  struct argp argp = { .options = options,
522
 
                       .parser = parse_opt_config_file,
523
 
                       .args_doc = "",
 
465
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
 
466
      break;
 
467
    case ARGP_KEY_END:
 
468
      break;
 
469
    default:
 
470
      return ARGP_ERR_UNKNOWN;
 
471
    }
 
472
    return 0;
 
473
  }
 
474
  
 
475
  struct argp argp = { .options = options, .parser = parse_opt,
 
476
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
524
477
                       .doc = "Mandos plugin runner -- Run plugins" };
525
478
  
526
 
  /* Parse using the parse_opt_config_file in order to get the custom
527
 
     config file location, if any. */
528
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
 
479
  ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
529
480
  if (ret == ARGP_ERR_UNKNOWN){
530
481
    fprintf(stderr, "Unknown error while parsing arguments\n");
531
482
    exitstatus = EXIT_FAILURE;
532
483
    goto fallback;
533
484
  }
534
 
  
535
 
  /* Reset to the normal argument parser */
536
 
  argp.parser = parse_opt;
537
 
  
538
 
  /* Open the configfile if available */
 
485
 
 
486
  /* Opens the configfile if aviable */
539
487
  if (argfile == NULL){
540
488
    conffp = fopen(AFILE, "r");
541
489
  } else {
559
507
    custom_argv[0] = argv[0];
560
508
    custom_argv[1] = NULL;
561
509
 
562
 
    /* for each line in the config file, strip whitespace and ignore
563
 
       commented text */
 
510
    /* for each line in the config file, strip whitespace and ignore commented text */
564
511
    while(true){
565
512
      sret = getline(&org_line, &size, conffp);
566
513
      if(sret == -1){
595
542
      }
596
543
    }
597
544
    free(org_line);
598
 
  } else {
 
545
  } else{
599
546
    /* Check for harmful errors and go to fallback. Other errors might
600
547
       not affect opening plugins */
601
548
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
607
554
  /* If there was any arguments from configuration file,
608
555
     pass them to parser as command arguments */
609
556
  if(custom_argv != NULL){
610
 
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
611
 
                      0, NULL);
 
557
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, NULL);
612
558
    if (ret == ARGP_ERR_UNKNOWN){
613
559
      fprintf(stderr, "Unknown error while parsing arguments\n");
614
560
      exitstatus = EXIT_FAILURE;
616
562
    }
617
563
  }
618
564
  
619
 
  /* Parse actual command line arguments, to let them override the
620
 
     config file */
621
 
  ret = argp_parse (&argp, argc, argv, ARGP_IN_ORDER, 0, NULL);
622
 
  if (ret == ARGP_ERR_UNKNOWN){
623
 
    fprintf(stderr, "Unknown error while parsing arguments\n");
624
 
    exitstatus = EXIT_FAILURE;
625
 
    goto fallback;
626
 
  }
627
 
  
628
565
  if(debug){
629
566
    for(plugin *p = plugin_list; p != NULL; p=p->next){
630
567
      fprintf(stderr, "Plugin: %s has %d arguments\n",
638
575
      }
639
576
    }
640
577
  }
641
 
  
 
578
 
642
579
  /* Strip permissions down to nobody */
643
580
  ret = setuid(uid);
644
581
  if (ret == -1){
648
585
  if (ret == -1){
649
586
    perror("setgid");
650
587
  }
651
 
  
 
588
 
652
589
  if (plugindir == NULL){
653
590
    dir = opendir(PDIR);
654
591
  } else {
675
612
  }
676
613
  
677
614
  FD_ZERO(&rfds_all);
678
 
  
 
615
 
679
616
  /* Read and execute any executable in the plugin directory*/
680
617
  while(true){
681
618
    dirst = readdir(dir);
682
619
    
683
 
    /* All directory entries have been processed */
 
620
    // All directory entries have been processed
684
621
    if(dirst == NULL){
685
622
      if (errno == EBADF){
686
623
        perror("readdir");
692
629
    
693
630
    d_name_len = strlen(dirst->d_name);
694
631
    
695
 
    /* Ignore dotfiles, backup files and other junk */
 
632
    // Ignore dotfiles, backup files and other junk
696
633
    {
697
634
      bool bad_name = false;
698
635
      
736
673
    }
737
674
 
738
675
    char *filename;
739
 
    if(plugindir == NULL){
740
 
      ret = asprintf(&filename, PDIR "/%s", dirst->d_name);
741
 
    } else {
742
 
      ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
743
 
    }
 
676
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
744
677
    if(ret < 0){
745
678
      perror("asprintf");
746
679
      continue;
788
721
        }
789
722
        /* Add global environment variables */
790
723
        for(char **e = g->environ; *e != NULL; e++){
791
 
          if(not add_environment(p, *e, false)){
 
724
          if(not add_environment(p, *e)){
792
725
            perror("add_environment");
793
726
          }
794
727
        }
799
732
       process, too. */
800
733
    if(p->environ[0] != NULL){
801
734
      for(char **e = environ; *e != NULL; e++){
802
 
        if(not add_environment(p, *e, false)){
 
735
        char *copy = strdup(*e);
 
736
        if(copy == NULL){
 
737
          perror("strdup");
 
738
          continue;
 
739
        }
 
740
        if(not add_environment(p, copy)){
803
741
          perror("add_environment");
804
742
        }
805
743
      }
832
770
      exitstatus = EXIT_FAILURE;
833
771
      goto fallback;
834
772
    }
835
 
    /* Starting a new process to be watched */
 
773
    // Starting a new process to be watched
836
774
    pid_t pid = fork();
837
775
    if(pid == -1){
838
776
      perror("fork");
846
784
        perror("sigaction");
847
785
        _exit(EXIT_FAILURE);
848
786
      }
849
 
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
787
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
850
788
      if(ret < 0){
851
789
        perror("sigprocmask");
852
790
        _exit(EXIT_FAILURE);
853
791
      }
854
 
      
 
792
 
855
793
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
856
794
      if(ret == -1){
857
795
        perror("dup2");
907
845
    if (maxfd < new_plugin->fd){
908
846
      maxfd = new_plugin->fd;
909
847
    }
 
848
    
910
849
  }
911
850
  
912
851
  closedir(dir);
913
852
  dir = NULL;
914
 
  
 
853
 
915
854
  for(plugin *p = plugin_list; p != NULL; p = p->next){
916
855
    if(p->pid != 0){
917
856
      break;
922
861
      free_plugin_list();
923
862
    }
924
863
  }
925
 
  
 
864
 
926
865
  /* Main loop while running plugins exist */
927
866
  while(plugin_list){
928
867
    fd_set rfds = rfds_all;
934
873
    }
935
874
    /* OK, now either a process completed, or something can be read
936
875
       from one of them */
937
 
    for(plugin *proc = plugin_list; proc != NULL;){
 
876
    for(plugin *proc = plugin_list; proc != NULL; proc = proc->next){
938
877
      /* Is this process completely done? */
939
878
      if(proc->eof and proc->completed){
940
879
        /* Only accept the plugin output if it exited cleanly */
967
906
            exitstatus = EXIT_FAILURE;
968
907
            goto fallback;
969
908
          }
970
 
          
971
 
          plugin *next_plugin = proc->next;
972
909
          free_plugin(proc);
973
 
          proc = next_plugin;
974
 
          
975
910
          /* We are done modifying process list, so unblock signal */
976
911
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
977
912
                             NULL);
984
919
          if(plugin_list == NULL){
985
920
            break;
986
921
          }
987
 
          
988
922
          continue;
989
923
        }
990
924
        
991
925
        /* This process exited nicely, so print its buffer */
992
 
        
 
926
 
993
927
        bool bret = print_out_password(proc->buffer,
994
928
                                       proc->buffer_length);
995
929
        if(not bret){
1002
936
      /* This process has not completed.  Does it have any output? */
1003
937
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
1004
938
        /* This process had nothing to say at this time */
1005
 
        proc = proc->next;
1006
939
        continue;
1007
940
      }
1008
941
      /* Before reading, make the process' data buffer large enough */
1021
954
                 BUFFER_SIZE);
1022
955
      if(ret < 0){
1023
956
        /* Read error from this process; ignore the error */
1024
 
        proc = proc->next;
1025
957
        continue;
1026
958
      }
1027
959
      if(ret == 0){
1042
974
    bool bret;
1043
975
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
1044
976
    char *passwordbuffer = getpass("Password: ");
1045
 
    size_t len = strlen(passwordbuffer);
1046
 
    /* Strip trailing newline */
1047
 
    if(len > 0 and passwordbuffer[len-1] == '\n'){
1048
 
      passwordbuffer[len-1] = '\0'; /* not strictly necessary */
1049
 
      len--;
1050
 
    }
1051
 
    bret = print_out_password(passwordbuffer, len);
 
977
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
1052
978
    if(not bret){
1053
979
      perror("print_out_password");
1054
980
      exitstatus = EXIT_FAILURE;
1061
987
    perror("sigaction");
1062
988
    exitstatus = EXIT_FAILURE;
1063
989
  }
1064
 
  
 
990
 
1065
991
  if(custom_argv != NULL){
1066
992
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
1067
993
      free(*arg);
1073
999
    closedir(dir);
1074
1000
  }
1075
1001
  
1076
 
  /* Kill the processes */
 
1002
  /* Free the process list and kill the processes */
1077
1003
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1078
1004
    if(p->pid != 0){
1079
1005
      close(p->fd);
1092
1018
  if(errno != ECHILD){
1093
1019
    perror("wait");
1094
1020
  }
1095
 
  
 
1021
 
1096
1022
  free_plugin_list();
1097
1023
  
1098
1024
  free(plugindir);