/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-09-01 16:19:32 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080901161932-ostp7tulh9aijulh
* plugin-runner.c (add_environment): Never insert existing environment
                                     variables.
  (main): Rename "--global-envs" to "--global-env" and "--envs-for" to
          "--env-for".

* plugin-runner.xml (SYNOPSIS): Rename "--global-envs" to
                                "--global-env" and "--envs-for" to
                                "--env-for".
  (OPTIONS): Added "--global-env" and "--env-for".
  (FALLBACK): Add id attribute.
  (EXIT STATUS): Add text.
  (ENVIRONMENT): New section.
  (FILES): Document configuration file.

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