/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-10-01 15:29:01 UTC
  • Revision ID: teddy@fukt.bsnet.se-20081001152901-fh30whl3m4vb7m24
* debian/changelog: New Debian revision.

* debian/mandos-client.lintian-overrides: Added comments.
* debian/mandos.lintian-overrides: - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
/*
3
3
 * Mandos plugin runner - Run Mandos plugins
4
4
 *
5
 
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
5
 * Copyright © 2008 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, popen(), fileno(),
31
 
                                   fprintf(), stderr, STDOUT_FILENO */
 
30
#include <stdio.h>              /* perror, fileno(), fprintf(),
 
31
                                   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 1.0";
 
72
const char *argp_program_version = "plugin-runner " VERSION;
73
73
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
74
74
 
75
 
struct plugin;
76
 
 
77
75
typedef struct plugin{
78
76
  char *name;                   /* can be NULL or any plugin name */
79
77
  char **argv;
96
94
 
97
95
static plugin *plugin_list = NULL;
98
96
 
99
 
/* Gets a existing plugin based on name,
 
97
/* Gets an existing plugin based on name,
100
98
   or if none is found, creates a new one */
101
99
static plugin *getplugin(char *name){
102
100
  /* Check for exiting plugin with that name */
118
116
      return NULL;
119
117
    }
120
118
  }
121
 
 
 
119
  
122
120
  *new_plugin = (plugin) { .name = copy_name,
123
121
                           .argc = 1,
124
122
                           .disabled = false,
179
177
}
180
178
 
181
179
/* Add to a plugin's environment */
182
 
static bool add_environment(plugin *p, const char *def){
 
180
static bool add_environment(plugin *p, const char *def, bool replace){
183
181
  if(p == NULL){
184
182
    return false;
185
183
  }
187
185
  size_t namelen = (size_t)(strchrnul(def, '=') - def);
188
186
  /* Search for this environment variable */
189
187
  for(char **e = p->environ; *e != NULL; e++){
190
 
    if(strncmp(*e, def, namelen+1) == 0){
191
 
      /* Refuse to add an existing variable */
 
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
      }
192
198
      return true;
193
199
    }
194
200
  }
200
206
 * Descriptor Flags".
201
207
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
202
208
 */
203
 
static int set_cloexec_flag(int fd)
204
 
{
 
209
static int set_cloexec_flag(int fd){
205
210
  int ret = fcntl(fd, F_GETFD, 0);
206
211
  /* If reading the flags failed, return error indication now. */
207
212
  if(ret < 0){
214
219
 
215
220
/* Mark processes as completed when they exit, and save their exit
216
221
   status. */
217
 
void handle_sigchld(__attribute__((unused)) int sig){
 
222
static void handle_sigchld(__attribute__((unused)) int sig){
218
223
  while(true){
219
224
    plugin *proc = plugin_list;
220
225
    int status;
230
235
      /* No child processes */
231
236
      break;
232
237
    }
233
 
 
 
238
    
234
239
    /* A child exited, find it in process_list */
235
240
    while(proc != NULL and proc->pid != pid){
236
241
      proc = proc->next;
245
250
}
246
251
 
247
252
/* Prints out a password to stdout */
248
 
bool print_out_password(const char *buffer, size_t length){
 
253
static bool print_out_password(const char *buffer, size_t length){
249
254
  ssize_t ret;
250
 
  if(length>0 and buffer[length-1] == '\n'){
251
 
    length--;
252
 
  }
253
255
  for(size_t written = 0; written < length; written += (size_t)ret){
254
256
    ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO, buffer + written,
255
257
                                   length - written));
336
338
    { .name = "global-options", .key = 'g',
337
339
      .arg = "OPTION[,OPTION[,...]]",
338
340
      .doc = "Options passed to all plugins" },
339
 
    { .name = "global-env", .key = 'e',
 
341
    { .name = "global-env", .key = 'G',
340
342
      .arg = "VAR=value",
341
343
      .doc = "Environment variable passed to all plugins" },
342
344
    { .name = "options-for", .key = 'o',
343
345
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
344
346
      .doc = "Options passed only to specified plugin" },
345
 
    { .name = "env-for", .key = 'f',
 
347
    { .name = "env-for", .key = 'E',
346
348
      .arg = "PLUGIN:ENV=value",
347
349
      .doc = "Environment variable passed to specified plugin" },
348
350
    { .name = "disable", .key = 'd',
349
351
      .arg = "PLUGIN",
350
352
      .doc = "Disable a specific plugin", .group = 1 },
 
353
    { .name = "enable", .key = 'e',
 
354
      .arg = "PLUGIN",
 
355
      .doc = "Enable a specific plugin", .group = 1 },
351
356
    { .name = "plugin-dir", .key = 128,
352
357
      .arg = "DIRECTORY",
353
358
      .doc = "Specify a different plugin directory", .group = 2 },
367
372
  
368
373
  error_t parse_opt (int key, char *arg, __attribute__((unused))
369
374
                     struct argp_state *state) {
370
 
    /* Get the INPUT argument from `argp_parse', which we know is a
371
 
       pointer to our plugin list pointer. */
372
375
    switch (key) {
373
376
    case 'g':                   /* --global-options */
374
377
      if (arg != NULL){
384
387
        }
385
388
      }
386
389
      break;
387
 
    case 'e':                   /* --global-env */
 
390
    case 'G':                   /* --global-env */
388
391
      if(arg == NULL){
389
392
        break;
390
393
      }
391
 
      {
392
 
        char *envdef = strdup(arg);
393
 
        if(envdef == NULL){
394
 
          break;
395
 
        }
396
 
        if(not add_environment(getplugin(NULL), envdef)){
397
 
          perror("add_environment");
398
 
        }
 
394
      if(not add_environment(getplugin(NULL), arg, true)){
 
395
        perror("add_environment");
399
396
      }
400
397
      break;
401
398
    case 'o':                   /* --options-for */
402
399
      if (arg != NULL){
403
400
        char *p_name = strsep(&arg, ":");
404
 
        if(p_name[0] == '\0'){
 
401
        if(p_name[0] == '\0' or arg == NULL){
405
402
          break;
406
403
        }
407
404
        char *opt = strsep(&arg, ":");
408
 
        if(opt[0] == '\0'){
 
405
        if(opt[0] == '\0' or opt == NULL){
409
406
          break;
410
407
        }
411
 
        if(opt != NULL){
412
 
          char *p;
413
 
          while((p = strsep(&opt, ",")) != NULL){
414
 
            if(p[0] == '\0'){
415
 
              continue;
416
 
            }
417
 
            if(not add_argument(getplugin(p_name), p)){
418
 
              perror("add_argument");
419
 
              return ARGP_ERR_UNKNOWN;
420
 
            }
 
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;
421
416
          }
422
417
        }
423
418
      }
424
419
      break;
425
 
    case 'f':                   /* --env-for */
 
420
    case 'E':                   /* --env-for */
426
421
      if(arg == NULL){
427
422
        break;
428
423
      }
431
426
        if(envdef == NULL){
432
427
          break;
433
428
        }
434
 
        char *p_name = strndup(arg, (size_t) (envdef-arg));
435
 
        if(p_name == NULL){
436
 
          break;
437
 
        }
438
 
        envdef++;
439
 
        if(not add_environment(getplugin(p_name), envdef)){
 
429
        *envdef = '\0';
 
430
        if(not add_environment(getplugin(arg), envdef+1, true)){
440
431
          perror("add_environment");
441
432
        }
442
433
      }
450
441
        p->disabled = true;
451
442
      }
452
443
      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
453
    case 128:                   /* --plugin-dir */
 
454
      free(plugindir);
454
455
      plugindir = strdup(arg);
455
456
      if(plugindir == NULL){
456
457
        perror("strdup");
457
458
      }      
458
459
      break;
459
460
    case 129:                   /* --config-file */
 
461
      /* This is already done by parse_opt_config_file() */
 
462
      break;
 
463
    case 130:                   /* --userid */
 
464
      uid = (uid_t)strtol(arg, NULL, 10);
 
465
      break;
 
466
    case 131:                   /* --groupid */
 
467
      gid = (gid_t)strtol(arg, NULL, 10);
 
468
      break;
 
469
    case 132:                   /* --debug */
 
470
      debug = true;
 
471
      break;
 
472
    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);
460
504
      argfile = strdup(arg);
461
505
      if(argfile == NULL){
462
506
        perror("strdup");
463
507
      }
464
508
      break;      
465
509
    case 130:                   /* --userid */
466
 
      uid = (uid_t)strtol(arg, NULL, 10);
467
 
      break;
468
510
    case 131:                   /* --groupid */
469
 
      gid = (gid_t)strtol(arg, NULL, 10);
470
 
      break;
471
511
    case 132:                   /* --debug */
472
 
      debug = true;
473
 
      break;
474
512
    case ARGP_KEY_ARG:
475
 
      fprintf(stderr, "Ignoring unknown argument \"%s\"\n", arg);
476
 
      break;
477
513
    case ARGP_KEY_END:
478
514
      break;
479
515
    default:
482
518
    return 0;
483
519
  }
484
520
  
485
 
  struct argp argp = { .options = options, .parser = parse_opt,
486
 
                       .args_doc = "[+PLUS_SEPARATED_OPTIONS]",
 
521
  struct argp argp = { .options = options,
 
522
                       .parser = parse_opt_config_file,
 
523
                       .args_doc = "",
487
524
                       .doc = "Mandos plugin runner -- Run plugins" };
488
525
  
489
 
  ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
 
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);
490
529
  if (ret == ARGP_ERR_UNKNOWN){
491
530
    fprintf(stderr, "Unknown error while parsing arguments\n");
492
531
    exitstatus = EXIT_FAILURE;
493
532
    goto fallback;
494
533
  }
495
 
 
496
 
  /* Opens the configfile if aviable */
 
534
  
 
535
  /* Reset to the normal argument parser */
 
536
  argp.parser = parse_opt;
 
537
  
 
538
  /* Open the configfile if available */
497
539
  if (argfile == NULL){
498
540
    conffp = fopen(AFILE, "r");
499
541
  } else {
553
595
      }
554
596
    }
555
597
    free(org_line);
556
 
  } else{
 
598
  } else {
557
599
    /* Check for harmful errors and go to fallback. Other errors might
558
600
       not affect opening plugins */
559
601
    if (errno == EMFILE or errno == ENFILE or errno == ENOMEM){
565
607
  /* If there was any arguments from configuration file,
566
608
     pass them to parser as command arguments */
567
609
  if(custom_argv != NULL){
568
 
    ret = argp_parse (&argp, custom_argc, custom_argv, 0, 0, NULL);
 
610
    ret = argp_parse (&argp, custom_argc, custom_argv, ARGP_IN_ORDER,
 
611
                      0, NULL);
569
612
    if (ret == ARGP_ERR_UNKNOWN){
570
613
      fprintf(stderr, "Unknown error while parsing arguments\n");
571
614
      exitstatus = EXIT_FAILURE;
573
616
    }
574
617
  }
575
618
  
 
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
  
576
628
  if(debug){
577
629
    for(plugin *p = plugin_list; p != NULL; p=p->next){
578
630
      fprintf(stderr, "Plugin: %s has %d arguments\n",
586
638
      }
587
639
    }
588
640
  }
589
 
 
 
641
  
590
642
  /* Strip permissions down to nobody */
591
643
  ret = setuid(uid);
592
644
  if (ret == -1){
596
648
  if (ret == -1){
597
649
    perror("setgid");
598
650
  }
599
 
 
 
651
  
600
652
  if (plugindir == NULL){
601
653
    dir = opendir(PDIR);
602
654
  } else {
623
675
  }
624
676
  
625
677
  FD_ZERO(&rfds_all);
626
 
 
 
678
  
627
679
  /* Read and execute any executable in the plugin directory*/
628
680
  while(true){
629
681
    dirst = readdir(dir);
630
682
    
631
 
    // All directory entries have been processed
 
683
    /* All directory entries have been processed */
632
684
    if(dirst == NULL){
633
685
      if (errno == EBADF){
634
686
        perror("readdir");
640
692
    
641
693
    d_name_len = strlen(dirst->d_name);
642
694
    
643
 
    // Ignore dotfiles, backup files and other junk
 
695
    /* Ignore dotfiles, backup files and other junk */
644
696
    {
645
697
      bool bad_name = false;
646
698
      
684
736
    }
685
737
 
686
738
    char *filename;
687
 
    ret = asprintf(&filename, "%s/%s", plugindir, dirst->d_name);
 
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
    }
688
744
    if(ret < 0){
689
745
      perror("asprintf");
690
746
      continue;
732
788
        }
733
789
        /* Add global environment variables */
734
790
        for(char **e = g->environ; *e != NULL; e++){
735
 
          if(not add_environment(p, *e)){
 
791
          if(not add_environment(p, *e, false)){
736
792
            perror("add_environment");
737
793
          }
738
794
        }
743
799
       process, too. */
744
800
    if(p->environ[0] != NULL){
745
801
      for(char **e = environ; *e != NULL; e++){
746
 
        char *copy = strdup(*e);
747
 
        if(copy == NULL){
748
 
          perror("strdup");
749
 
          continue;
750
 
        }
751
 
        if(not add_environment(p, copy)){
 
802
        if(not add_environment(p, *e, false)){
752
803
          perror("add_environment");
753
804
        }
754
805
      }
781
832
      exitstatus = EXIT_FAILURE;
782
833
      goto fallback;
783
834
    }
784
 
    // Starting a new process to be watched
 
835
    /* Starting a new process to be watched */
785
836
    pid_t pid = fork();
786
837
    if(pid == -1){
787
838
      perror("fork");
795
846
        perror("sigaction");
796
847
        _exit(EXIT_FAILURE);
797
848
      }
798
 
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
 
849
      ret = sigprocmask(SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
799
850
      if(ret < 0){
800
851
        perror("sigprocmask");
801
852
        _exit(EXIT_FAILURE);
802
853
      }
803
 
 
 
854
      
804
855
      ret = dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
805
856
      if(ret == -1){
806
857
        perror("dup2");
856
907
    if (maxfd < new_plugin->fd){
857
908
      maxfd = new_plugin->fd;
858
909
    }
859
 
    
860
910
  }
861
911
  
862
912
  closedir(dir);
863
913
  dir = NULL;
864
 
 
 
914
  
865
915
  for(plugin *p = plugin_list; p != NULL; p = p->next){
866
916
    if(p->pid != 0){
867
917
      break;
872
922
      free_plugin_list();
873
923
    }
874
924
  }
875
 
 
 
925
  
876
926
  /* Main loop while running plugins exist */
877
927
  while(plugin_list){
878
928
    fd_set rfds = rfds_all;
884
934
    }
885
935
    /* OK, now either a process completed, or something can be read
886
936
       from one of them */
887
 
    for(plugin *proc = plugin_list; proc != NULL; proc = proc->next){
 
937
    for(plugin *proc = plugin_list; proc != NULL;){
888
938
      /* Is this process completely done? */
889
939
      if(proc->eof and proc->completed){
890
940
        /* Only accept the plugin output if it exited cleanly */
917
967
            exitstatus = EXIT_FAILURE;
918
968
            goto fallback;
919
969
          }
 
970
          
 
971
          plugin *next_plugin = proc->next;
920
972
          free_plugin(proc);
 
973
          proc = next_plugin;
 
974
          
921
975
          /* We are done modifying process list, so unblock signal */
922
976
          ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
923
977
                             NULL);
930
984
          if(plugin_list == NULL){
931
985
            break;
932
986
          }
 
987
          
933
988
          continue;
934
989
        }
935
990
        
936
991
        /* This process exited nicely, so print its buffer */
937
 
 
 
992
        
938
993
        bool bret = print_out_password(proc->buffer,
939
994
                                       proc->buffer_length);
940
995
        if(not bret){
947
1002
      /* This process has not completed.  Does it have any output? */
948
1003
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
949
1004
        /* This process had nothing to say at this time */
 
1005
        proc = proc->next;
950
1006
        continue;
951
1007
      }
952
1008
      /* Before reading, make the process' data buffer large enough */
965
1021
                 BUFFER_SIZE);
966
1022
      if(ret < 0){
967
1023
        /* Read error from this process; ignore the error */
 
1024
        proc = proc->next;
968
1025
        continue;
969
1026
      }
970
1027
      if(ret == 0){
985
1042
    bool bret;
986
1043
    fprintf(stderr, "Going to fallback mode using getpass(3)\n");
987
1044
    char *passwordbuffer = getpass("Password: ");
988
 
    bret = print_out_password(passwordbuffer, strlen(passwordbuffer));
 
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);
989
1052
    if(not bret){
990
1053
      perror("print_out_password");
991
1054
      exitstatus = EXIT_FAILURE;
998
1061
    perror("sigaction");
999
1062
    exitstatus = EXIT_FAILURE;
1000
1063
  }
1001
 
 
 
1064
  
1002
1065
  if(custom_argv != NULL){
1003
1066
    for(char **arg = custom_argv+1; *arg != NULL; arg++){
1004
1067
      free(*arg);
1010
1073
    closedir(dir);
1011
1074
  }
1012
1075
  
1013
 
  /* Free the process list and kill the processes */
 
1076
  /* Kill the processes */
1014
1077
  for(plugin *p = plugin_list; p != NULL; p = p->next){
1015
1078
    if(p->pid != 0){
1016
1079
      close(p->fd);
1029
1092
  if(errno != ECHILD){
1030
1093
    perror("wait");
1031
1094
  }
1032
 
 
 
1095
  
1033
1096
  free_plugin_list();
1034
1097
  
1035
1098
  free(plugindir);