/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/*  -*- coding: utf-8 -*- */
/*
 * Mandos plugin runner - Run Mandos plugins
 *
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 * 
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 */

#define _GNU_SOURCE		/* TEMP_FAILURE_RETRY() */

#include <stdio.h>		/* popen(), fileno(), fprintf(),
				   stderr, STDOUT_FILENO */
#include <iso646.h>		/* and, or, not */
#include <sys/types.h>	        /* DIR, opendir(), stat(),
				   struct stat, waitpid(),
				   WIFEXITED(), WEXITSTATUS(),
				   wait() */
#include <sys/wait.h>		/* wait() */
#include <dirent.h>		/* DIR, struct dirent, opendir(),
				   readdir(), closedir() */
#include <sys/stat.h>		/* struct stat, stat(), S_ISREG() */
#include <unistd.h>		/* struct stat, stat(), S_ISREG(),
				   fcntl() */
#include <fcntl.h>		/* fcntl() */
#include <stddef.h>		/* NULL */
#include <stdlib.h>		/* EXIT_FAILURE */
#include <sys/select.h>		/* fd_set, select(), FD_ZERO(),
				   FD_SET(), FD_ISSET() */
#include <string.h>		/* strlen(), strcpy(), strcat() */
#include <stdbool.h>		/* true */
#include <sys/wait.h>		/* waitpid(), WIFEXITED(),
				   WEXITSTATUS() */
#include <errno.h>		/* errno */
#include <argp.h>		/* struct argp_option,
				   struct argp_state, struct argp,
				   argp_parse() */

struct process;

typedef struct process{
  pid_t pid;
  int fd;
  char *buffer;
  size_t buffer_size;
  size_t buffer_length;
  bool eof;
  bool completed;
  int status;
  struct process *next;
} process;

typedef struct plugin{
  char *name;			/* can be NULL or any plugin name */
  char **argv;
  int argc;
  bool disabled;
  struct plugin *next;
} plugin;

plugin *getplugin(char *name, plugin **plugin_list){
  for (plugin *p = *plugin_list; p != NULL; p = p->next){
    if ((p->name == name)
	or (p->name and name and (strcmp(p->name, name) == 0))){
      return p;
    }
  }
  /* Create a new plugin */
  plugin *new_plugin = malloc(sizeof(plugin));
  if (new_plugin == NULL){
    perror("malloc");
    exit(EXIT_FAILURE);
  }
  new_plugin->name = name;
  new_plugin->argv = malloc(sizeof(char *) * 2);
  if (new_plugin->argv == NULL){
    perror("malloc");
    exit(EXIT_FAILURE);
  }
  new_plugin->argv[0] = name;
  new_plugin->argv[1] = NULL;
  new_plugin->argc = 1;
  new_plugin->disabled = false;
  new_plugin->next = *plugin_list;
  /* Append the new plugin to the list */
  *plugin_list = new_plugin;
  return new_plugin;
}

void addargument(plugin *p, char *arg){
  p->argv[p->argc] = arg;
  p->argv = realloc(p->argv, sizeof(char *) * (size_t)(p->argc + 2));
  if (p->argv == NULL){
    perror("malloc");
    exit(EXIT_FAILURE);
  }
  p->argc++;
  p->argv[p->argc] = NULL;
}

/*
 * Based on the example in the GNU LibC manual chapter 13.13 "File
 * Descriptor Flags".
 * *Note File Descriptor Flags:(libc)Descriptor Flags.
 */
int set_cloexec_flag(int fd)
{
  int ret = fcntl(fd, F_GETFD, 0);
  /* If reading the flags failed, return error indication now. */
  if(ret < 0){
    return ret;
  }
  /* Store modified flag word in the descriptor. */
  return fcntl(fd, F_SETFD, ret | FD_CLOEXEC);
}

#define BUFFER_SIZE 256

const char *argp_program_version = "plugbasedclient 0.9";
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";

process *process_list = NULL;

/* Mark a process as completed when it exits, and save its exit
   status. */
void handle_sigchld(__attribute__((unused)) int sig){
  process *proc = process_list;
  int status;
  pid_t pid = wait(&status);
  while(proc != NULL and proc->pid != pid){
    proc = proc->next;    
  }
  if(proc == NULL){
    /* Process not found in process list */
    return;
  }
  proc->status = status;
  proc->completed = true;
}

int main(int argc, char *argv[]){
  const char *plugindir = "/conf/conf.d/mandos/plugins.d";
  size_t d_name_len;
  DIR *dir = NULL;
  struct dirent *dirst;
  struct stat st;
  fd_set rfds_all;
  int ret, maxfd = 0;
  uid_t uid = 65534;
  gid_t gid = 65534;
  bool debug = false;
  int exitstatus = EXIT_SUCCESS;
  struct sigaction old_sigchld_action;
  struct sigaction sigchld_action = { .sa_handler = handle_sigchld,
				      .sa_flags = SA_NOCLDSTOP };

  /* Establish a signal handler */
  sigemptyset(&sigchld_action.sa_mask);
  ret = sigaddset(&sigchld_action.sa_mask, SIGCHLD);
  if(ret < 0){
    perror("sigaddset");
    exit(EXIT_FAILURE);
  }
  ret = sigaction(SIGCHLD, &sigchld_action, &old_sigchld_action);
  if(ret < 0){
    perror("sigaction");
    exit(EXIT_FAILURE);
  }
  
  /* The options we understand. */
  struct argp_option options[] = {
    { .name = "global-options", .key = 'g',
      .arg = "OPTION[,OPTION[,...]]",
      .doc = "Options passed to all plugins" },
    { .name = "options-for", .key = 'o',
      .arg = "PLUGIN:OPTION[,OPTION[,...]]",
      .doc = "Options passed only to specified plugin" },
    { .name = "disable", .key = 'd',
      .arg = "PLUGIN",
      .doc = "Disable a specific plugin", .group = 1 },
    { .name = "plugin-dir", .key = 128,
      .arg = "DIRECTORY",
      .doc = "Specify a different plugin directory", .group = 2 },
    { .name = "userid", .key = 129,
      .arg = "ID", .flags = 0,
      .doc = "User ID the plugins will run as", .group = 2 },
    { .name = "groupid", .key = 130,
      .arg = "ID", .flags = 0,
      .doc = "Group ID the plugins will run as", .group = 2 },
    { .name = "debug", .key = 131,
      .doc = "Debug mode", .group = 3 },
    { .name = NULL }
  };
  
  error_t parse_opt (int key, char *arg, struct argp_state *state) {
    /* Get the INPUT argument from `argp_parse', which we know is a
       pointer to our plugin list pointer. */
    plugin **plugins = state->input;
    switch (key) {
    case 'g':
      if (arg != NULL){
	char *p = strtok(arg, ",");
	do{
	  addargument(getplugin(NULL, plugins), p);
	  p = strtok(NULL, ",");
	} while (p);
      }
      break;
    case 'o':
      if (arg != NULL){
	char *name = strtok(arg, ":");
	char *p = strtok(NULL, ":");
	if(p){
	  p = strtok(p, ",");
	  do{
	    addargument(getplugin(name, plugins), p);
	    p = strtok(NULL, ",");
	  } while (p);
	}
      }
      break;
    case 'd':
      if (arg != NULL){
	getplugin(arg, plugins)->disabled = true;
      }
      break;
    case 128:
      plugindir = arg;
      break;
    case 129:
      uid = (uid_t)strtol(arg, NULL, 10);
      break;
    case 130:
      gid = (gid_t)strtol(arg, NULL, 10);
      break;
    case 131:
      debug = true;
      break;
    case ARGP_KEY_ARG:
      argp_usage (state);
      break;
    case ARGP_KEY_END:
      break;
    default:
      return ARGP_ERR_UNKNOWN;
    }
    return 0;
  }
  
  plugin *plugin_list = NULL;
  
  struct argp argp = { .options = options, .parser = parse_opt,
		       .args_doc = "",
		       .doc = "Mandos plugin runner -- Run plugins" };
  
  argp_parse (&argp, argc, argv, 0, 0, &plugin_list);  

  if(debug){
    for(plugin *p = plugin_list; p != NULL; p=p->next){
      fprintf(stderr, "Plugin: %s has %d arguments\n",
	      p->name ? p->name : "Global", p->argc - 1);
      for(char **a = p->argv; *a != NULL; a++){
	fprintf(stderr, "\tArg: %s\n", *a);
      }
    }
  }

  ret = setuid(uid);
  if (ret == -1){
    perror("setuid");
  }
  
  setgid(gid);
  if (ret == -1){
    perror("setuid");
  }
  
  dir = opendir(plugindir);
  if(dir == NULL){
    perror("Could not open plugin dir");
    exitstatus = EXIT_FAILURE;
    goto end;
  }
  
  /* Set the FD_CLOEXEC flag on the directory, if possible */
  {
    int dir_fd = dirfd(dir);
    if(dir_fd >= 0){
      ret = set_cloexec_flag(dir_fd);
      if(ret < 0){
	perror("set_cloexec_flag");
	exitstatus = EXIT_FAILURE;
	goto end;
      }
    }
  }
  
  FD_ZERO(&rfds_all);
  
  while(true){
    dirst = readdir(dir);
    
    // All directory entries have been processed
    if(dirst == NULL){
      break;
    }
    
    d_name_len = strlen(dirst->d_name);
    
    // Ignore dotfiles, backup files and other junk
    {
      bool bad_name = false;
      
      const char const *bad_prefixes[] = { ".", "#", NULL };
      
      const char const *bad_suffixes[] = { "~", "#", ".dpkg-new",
					   ".dpkg-old",
					   ".dpkg-divert", NULL };
      for(const char **pre = bad_prefixes; *pre != NULL; pre++){
	size_t pre_len = strlen(*pre);
	if((d_name_len >= pre_len)
	   and strncmp((dirst->d_name), *pre, pre_len) == 0){
	  if(debug){
	    fprintf(stderr, "Ignoring plugin dir entry \"%s\""
		    " with bad prefix %s\n", dirst->d_name, *pre);
	  }
	  bad_name = true;
	  break;
	}
      }
      
      if(bad_name){
	continue;
      }
      
      for(const char **suf = bad_suffixes; *suf != NULL; suf++){
	size_t suf_len = strlen(*suf);
	if((d_name_len >= suf_len)
	   and (strcmp((dirst->d_name)+d_name_len-suf_len, *suf)
		== 0)){
	  if(debug){
	    fprintf(stderr, "Ignoring plugin dir entry \"%s\""
		    " with bad suffix %s\n", dirst->d_name, *suf);
	  }
	  bad_name = true;
	  break;
	}
      }
      
      if(bad_name){
	continue;
      }
    }
    
    char *filename = malloc(d_name_len + strlen(plugindir) + 2);
    if (filename == NULL){
      perror("malloc");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    strcpy(filename, plugindir); /* Spurious warning */
    strcat(filename, "/");	/* Spurious warning */
    strcat(filename, dirst->d_name); /* Spurious warning */
    
    stat(filename, &st);
    
    if (not S_ISREG(st.st_mode)	or (access(filename, X_OK) != 0)){
      if(debug){
	fprintf(stderr, "Ignoring plugin dir entry \"%s\""
		" with bad type or mode\n", filename);
      }
      free(filename);
      continue;
    }
    if(getplugin(dirst->d_name, &plugin_list)->disabled){
      if(debug){
	fprintf(stderr, "Ignoring disabled plugin \"%s\"\n",
		dirst->d_name);
      }
      free(filename);
      continue;
    }
    plugin *p = getplugin(dirst->d_name, &plugin_list);
    {
      /* Add global arguments to argument list for this plugin */
      plugin *g = getplugin(NULL, &plugin_list);
      for(char **a = g->argv + 1; *a != NULL; a++){
	addargument(p, *a);
      }
    }
    int pipefd[2]; 
    ret = pipe(pipefd);
    if (ret == -1){
      perror("pipe");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    ret = set_cloexec_flag(pipefd[0]);
    if(ret < 0){
      perror("set_cloexec_flag");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    ret = set_cloexec_flag(pipefd[1]);
    if(ret < 0){
      perror("set_cloexec_flag");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    /* Block SIGCHLD until process is safely in process list */
    ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
    if(ret < 0){
      perror("sigprocmask");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    // Starting a new process to be watched
    pid_t pid = fork();
    if(pid == 0){
      /* this is the child process */
      ret = sigaction(SIGCHLD, &old_sigchld_action, NULL);
      if(ret < 0){
	perror("sigaction");
	_exit(EXIT_FAILURE);
      }
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
      if(ret < 0){
	perror("sigprocmask");
	_exit(EXIT_FAILURE);
      }
      dup2(pipefd[1], STDOUT_FILENO); /* replace our stdout */
      
      if(dirfd(dir) < 0){
	/* If dir has no file descriptor, we could not set FD_CLOEXEC
	   above and must now close it manually here. */
	closedir(dir);
      }
      if(execv(filename, p->argv) < 0){
	perror("execv");
	_exit(EXIT_FAILURE);
      }
      /* no return */
    }
    /* parent process */
    free(filename);
    close(pipefd[1]);		/* close unused write end of pipe */
    process *new_process = malloc(sizeof(process));
    if (new_process == NULL){
      perror("malloc");
      ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
      if(ret < 0){
	perror("sigprocmask");
      }
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    
    *new_process = (struct process){ .pid = pid,
				     .fd = pipefd[0],
				     .next = process_list };
    // List handling
    process_list = new_process;
    /* Unblock SIGCHLD so signal handler can be run if this process
       has already completed */
    ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask, NULL);
    if(ret < 0){
      perror("sigprocmask");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    
    FD_SET(new_process->fd, &rfds_all);
    
    if (maxfd < new_process->fd){
      maxfd = new_process->fd;
    }
    
  }
  
  /* Free the plugin list */
  for(plugin *next; plugin_list != NULL; plugin_list = next){
    next = plugin_list->next;
    free(plugin_list->argv);
    free(plugin_list);
  }
  
  closedir(dir);
  dir = NULL;
  
  if (process_list == NULL){
    fprintf(stderr, "No plugin processes started, exiting\n");
    exitstatus = EXIT_FAILURE;
    goto end;
  }
  while(process_list){
    fd_set rfds = rfds_all;
    int select_ret = select(maxfd+1, &rfds, NULL, NULL, NULL);
    if (select_ret == -1){
      perror("select");
      exitstatus = EXIT_FAILURE;
      goto end;
    }
    /* OK, now either a process completed, or something can be read
       from one of them */
    for(process *proc = process_list; proc ; proc = proc->next){
      /* Is this process completely done? */
      if(proc->eof and proc->completed){
	/* Only accept the plugin output if it exited cleanly */
	if(not WIFEXITED(proc->status)
	   or WEXITSTATUS(proc->status) != 0){
	  /* Bad exit by plugin */
	  if(debug){
	    if(WIFEXITED(proc->status)){
	      fprintf(stderr, "Plugin %d exited with status %d\n",
		      proc->pid, WEXITSTATUS(proc->status));
	    } else if(WIFSIGNALED(proc->status)) {
	      fprintf(stderr, "Plugin %d killed by signal %d\n",
		      proc->pid, WTERMSIG(proc->status));
	    } else if(WCOREDUMP(proc->status)){
	      fprintf(stderr, "Plugin %d dumped core\n", proc->pid);
	    }
	  }
	  /* Remove the plugin */
	  FD_CLR(proc->fd, &rfds_all);
	  /* Block signal while modifying process_list */
	  ret = sigprocmask (SIG_BLOCK, &sigchld_action.sa_mask, NULL);
	  if(ret < 0){
	    perror("sigprocmask");
	    exitstatus = EXIT_FAILURE;
	    goto end;
	  }
	  /* Delete this process entry from the list */
	  if(process_list == proc){
	    /* First one - simple */
	    process_list = proc->next;
	  } else {
	    /* Second one or later */
	    for(process *p = process_list; p != NULL; p = p->next){
	      if(p->next == proc){
		p->next = proc->next;
		break;
	      }
	    }
	  }
	  /* We are done modifying process list, so unblock signal */
	  ret = sigprocmask (SIG_UNBLOCK, &sigchld_action.sa_mask,
			     NULL);
	  if(ret < 0){
	    perror("sigprocmask");
	  }
	  free(proc->buffer);
	  free(proc);
	  /* We deleted this process from the list, so we can't go
	     proc->next.  Therefore, start over from the beginning of
	     the process list */
	  break;
	}
	/* This process exited nicely, so print its buffer */
	for(size_t written = 0; written < proc->buffer_length;
	    written += (size_t)ret){
	  ret = TEMP_FAILURE_RETRY(write(STDOUT_FILENO,
					 proc->buffer + written,
					 proc->buffer_length
					 - written));
	  if(ret < 0){
	    perror("write");
	    exitstatus = EXIT_FAILURE;
	    goto end;
	  }
	}
	goto end;
      }
      /* This process has not completed.  Does it have any output? */
      if(proc->eof or not FD_ISSET(proc->fd, &rfds)){
	/* This process had nothing to say at this time */
	continue;
      }
      /* Before reading, make the process' data buffer large enough */
      if(proc->buffer_length + BUFFER_SIZE > proc->buffer_size){
	proc->buffer = realloc(proc->buffer, proc->buffer_size
			       + (size_t) BUFFER_SIZE);
	if (proc->buffer == NULL){
	  perror("malloc");
	  exitstatus = EXIT_FAILURE;
	  goto end;
	}
	proc->buffer_size += BUFFER_SIZE;
      }
      /* Read from the process */
      ret = read(proc->fd, proc->buffer + proc->buffer_length,
		 BUFFER_SIZE);
      if(ret < 0){
	/* Read error from this process; ignore the error */
	continue;
      }
      if(ret == 0){
	/* got EOF */
	proc->eof = true;
      } else {
	proc->buffer_length += (size_t) ret;
      }
    }
  }
  if(process_list == NULL){
    fprintf(stderr, "All plugin processes failed, exiting\n");
    exitstatus = EXIT_FAILURE;
  }
  
 end:
  /* Restore old signal handler */
  sigaction(SIGCHLD, &old_sigchld_action, NULL);
  
  /* Free the plugin list */
  for(plugin *next; plugin_list != NULL; plugin_list = next){
    next = plugin_list->next;
    free(plugin_list->argv);
    free(plugin_list);
  }
  
  if(dir != NULL){
    closedir(dir);
  }
  
  /* Free the process list and kill the processes */
  for(process *next; process_list != NULL; process_list = next){
    next = process_list->next;
    close(process_list->fd);
    kill(process_list->pid, SIGTERM);
    free(process_list->buffer);
    free(process_list);
  }
  
  /* Wait for any remaining child processes to terminate */
  do{
    ret = wait(NULL);
  } while(ret >= 0);
  if(errno != ECHILD){
    perror("wait");
  }
  
  return exitstatus;
}