File: sbox.c

package info (click to toggle)
sbox-dtc 1.07-8
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 232 kB
  • ctags: 99
  • sloc: ansic: 865; sh: 368; makefile: 88
file content (994 lines) | stat: -rw-r--r-- 28,403 bytes parent folder | download
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
#include "sbox.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/stat.h>
#if SET_LIMITS
#include <sys/resource.h>
#endif

/* DESCRIPTION
   sbox is designed to allow untrusted users to run CGI scripts without endangering
   the security of the site as a whole.
   $Revision: 1.2 $

   Call as "http://your.site.com/cgi-bin/sbox/path/to/end_user/script"

   1. sbox does a series of checks to confirm that it has been called in correct context
      a. user ID is WEB_USER
      b. group ID is WEB_GROUP
      c. neither of these is root
    2. sbox fetches the target script named in PATH_TRANSLATED
      a. actually, it walks down the path until it finds the first executable file
    3. sbox performs checks on the target script
      a. script is not SUID or SGID
      b. script is executable
      c. script is not writable by WEB_USER or WEB_GROUP
      d. directory that script lives in is not writable by WEB_USER or WEB_GROUP
    4. sbox determines user and group of owner of the script file or its enclosing directory
    5. sbox changes its uid and gid to match the script's file or directory
    6. sbox checks that the script is within the owner's home directory
    7. sbox chroots to the new root directory
    8. sbox fixes PATH_TRANSLATED and SCRIPT_NAME for chroot change
    9. sbox sets resource limits
    10. sbox logs everything
    11. sbox execs script
 */

/* Copyright info:
 * Copyright 1997, Lincoln D. Stein
 *
 *  Parts of this code are derived from suexec.c, Copyright 1995-1997 The Apache Group
 */

#ifndef MAXPATHLEN
  #ifdef PATH_MAX
     #define MAXPATHLEN PATH_MAX
  #else
     #define MAXPATHLEN 8192
  #endif
#endif

#ifndef NAME_MAX
#define NAME_MAX 512
#endif

#define AP_ENVBUF 256
extern char **environ; 

/* needed to compile with -ansi */
#ifndef strdup
extern char *strdup (const char *);
#endif

#ifndef chroot
extern int chroot (const char *path);
#endif

static char **cleanenv = NULL;
static FILE *log;

static void open_log();
static void log_error(const char* fmt, ...);
static void fatal_error(const char* fmt, ...);
static void check_consistency();
static char* fetch_target(char *root,char** additional_info,
			  struct stat* targ,struct stat* dir);
static char* to_abs(char* directory);
static char* document_root ();
static void check_target(const char* newroot,
			 const char* target,
			 const struct stat *file_stats,
			 const struct stat *dir_stats);
static char* fetch_newroot(char* docroot);
static char* shave(char* newroot,
		   char* target);
static void clean_env();
static void tweak_environment(char* newroot,
			      char* root,
			      char* target,
			      char* additional_info);
static int set_env(const char *name, 
		   const char *value, 
		   int overwrite);
static char* escape(const char* str);
static void chdir_fix(char* newroot, char* target);

#if SET_LIMITS
static void set_limits();
#endif

static char *safe_env_lst[] =
{
    "AUTH_TYPE",
    "CONTENT_LENGTH",
    "CONTENT_TYPE",
    "DATE_GMT",
    "DATE_LOCAL",
    "DOCUMENT_NAME",
    "DOCUMENT_PATH_INFO",
    "DOCUMENT_URI",
    "FILEPATH_INFO",
    "GATEWAY_INTERFACE",
    "LAST_MODIFIED",
    "QUERY_STRING",
    "QUERY_STRING_UNESCAPED",
    "REMOTE_ADDR",
    "REMOTE_HOST",
    "REMOTE_IDENT",
    "REMOTE_PORT",
    "REMOTE_USER",
    "REDIRECT_QUERY_STRING",
    "REDIRECT_STATUS",
    "REDIRECT_URL",
    "REQUEST_METHOD",
    "REQUEST_URI",
    "SCRIPT_URI",
    "SCRIPT_URL",
    "SERVER_ADMIN",
    "SERVER_NAME",
    "SERVER_PORT",
    "SERVER_PROTOCOL",
    "SERVER_SOFTWARE",
    "USER_NAME",
    "TZ",
#if !DO_CHROOT
    "SCRIPT_NAME",
    "PATH_INFO",
    "PATH_TRANSLATED",
    "DOCUMENT_ROOT",
    "SCRIPT_FILENAME",
#endif
    NULL
};

/*****************  START OF CODE ****************/

int main (int argc, char* argv[]) {
  struct stat target_stat,dir_stat;
  char *target,*newroot,*root,*additional_info,*cmd;
  int gid,uid,i,return_int;

  open_log();
  check_consistency();

  /* figure out the base of the user's HTML document tree */
  root = document_root();

  /* resolve the additional path information correctly */
  target = fetch_target(root,&additional_info,&target_stat,&dir_stat);

#if DO_CHROOT
  /* find the absolute path name of the root */
  to_abs(root);

  /* calculate the new root for chroot*/
  newroot = fetch_newroot(root);
#endif

  /* check that the target is OK */
  check_target(newroot,target,&target_stat,&dir_stat);

#if DO_CHROOT
  /* fix the environment */
  tweak_environment(newroot,root,target,additional_info);

#if !defined(DEBUG)
  /* change to the owner's root */
  if (chroot(newroot) < 0)
    fatal_error("couldn't chroot to %s (%s)\n",escape(newroot),strerror(errno));
#endif

#endif

#if DO_CHROOT && !defined(DEBUG)
  cmd = shave(newroot,target); 
#else
  cmd = target;
#endif

clean_env();

  /* set to the owner's uid and gid */
#if DO_SGID || DO_SUID
  gid = SID_MODE == DIRECTORY ? dir_stat.st_gid : target_stat.st_gid;
  uid = SID_MODE == DIRECTORY ? dir_stat.st_uid : target_stat.st_uid;
#if DO_SGID && !defined(DEBUG)
  if (setgid(gid) < 0) {
    fatal_error("couldn't setgid() to %d (%s)\n",dir_stat.st_gid,strerror(errno));
  }
#else
  /* give up our sgid privileges if any*/
  if (setgid(getgid()) < 0) {
    fatal_error("couldn't setgid() to %d (%s)\n",getgid(),strerror(errno));
  }
#endif

#if DO_SUID && !defined(DEBUG)
  if (setuid(uid) < 0) {
    fatal_error("couldn't setuid() to %d (%s)\n",dir_stat.st_uid,strerror(errno));
  }
#endif
#endif

  /* give up our root privileges now */
  if (setuid(getuid()) < 0) {
    fatal_error("couldn't setuid() to %d (%s)\n",getuid(),strerror(errno));
  }
  
#ifdef LOG_FILE
  log_error("executing %s for uid %d, gid %d\n",target,getuid(),getgid());
#endif

  /* set hard and soft limits on resource usage */
  /* important to do this after log is closed because otherwise the log file 
     size will be restricted by the LIMIT_FSIZE_SOFT value */
#if SET_LIMITS
  set_limits();
#endif

#ifdef LOG_FILE
  log_error("after set_limits() call\n");
#endif

  /* fix up argv[] array */
  argv[0] = cmd;

  /* chdir() to new directory */
  chdir_fix(newroot,target);
#ifdef LOG_FILE
  log_error("after chdir_fix() call\n");
  log_error("Going to try this: %s , %s, %s\n", cmd, argv[1], cleanenv[0]);
#endif
  
//if (log && log != stderr)
//    fclose(log);

  /* execute the target */
  return_int = execve(cmd,argv,cleanenv);

#ifdef LOG_FILE
  log_error("after execve() %d \n", return_int);
#endif

  /* if we get here, then something went wrong -- we won't be able to
     reopen the log file because we've given up privileges, logging
     to stderr causes an Apache "Premature end of script" error because
     it's expecting a Content-Type header, so disable logging via
     write_log entirely by setting log to NULL. */
  log = NULL;
  fatal_error("exec of %s failed (%s)\n",escape(cmd),strerror(errno));

  return -1;
}

/* Will error out if one of the consistency checks fails. */
void check_consistency() {
  struct passwd *pass;
  struct group *grp;
  int uid,gid;

#if !defined(DEBUG)

  /* get our group and user ids */
  uid = getuid();
  if ((pass = getpwuid(uid)) == NULL)
    fatal_error("invalid uid: (%ld)\n", uid);

  gid = getgid();
  if ((grp = getgrgid(gid)) == NULL)
    fatal_error("invalid gid: (%ld)\n", gid);
  
  /* exit if either the uid or gid are zero */
  if (uid == 0)
    fatal_error("cannot be run as root\n");

  if (gid == 0)
    fatal_error("cannot be run as the root group\n");

  /* Make sure that we were invoked by the Web user and group */
  if (strcmp(WEB_USER,pass->pw_name))
    fatal_error("invoked by %s, but must be run by %s\n",escape(pass->pw_name),escape(WEB_USER));

  if (strcmp(WEB_GROUP,grp->gr_name))
    fatal_error("invoked by group %s, but must be run by group %s\n",escape(grp->gr_name),escape(WEB_GROUP));

#endif
}

void open_log () {
#ifdef LOG_FILE
  if (strlen(LOG_FILE) > 0) {
   if ((log = fopen(LOG_FILE, "a")) == NULL) {
      fprintf(stderr, "sbox failed to open log file.  Falling back to stderr.\n");
      log = stderr;
    }
  } else {
    log = stderr;
  }
#else
  log = NULL;
#endif
}

static void write_log(const char* fmt, va_list ap) {
  time_t    timevar;
  char*     timestr;
  
  if (log == NULL) return;

  timevar = time(NULL);
  timestr = ctime(&timevar);
  timestr[strlen(timestr)-1]='\0';
  
  fprintf(log,"[%s] sbox: ",timestr);
  vfprintf(log, fmt, ap);
  fflush(log);

  return;
}

void log_error(const char* fmt, ...) {
  va_list ap;

  va_start(ap, fmt);
  write_log(fmt,ap);
  va_end(ap);
}

void fatal_error(const char* fmt, ...) {
  va_list ap;
  char* webmaster;

  va_start(ap, fmt);
  write_log(fmt,ap);

#if ECHO_FAILURES
  webmaster = (char*)getenv("SERVER_ADMIN");

  fprintf(stdout,"Content-type: text/html\n\n");
  fprintf(stdout,webmaster ? "%s (<a href=\"mailto:%s\">%s</a>).": "%s",
	  CANNED_ERROR_TOP,webmaster,webmaster);
  fprintf(stdout,"<BLOCKQUOTE><STRONG>");
  vprintf(fmt, ap);
  fprintf(stdout,"</STRONG></BLOCKQUOTE>%s",CANNED_ERROR_BOTTOM);
  fprintf(stdout,"<P><I>sbox version %3.2f</I><BR><I>%s</I></P><HR></BODY></HTML>",VERSION,"$Id: sbox.c,v 1.2 2005/02/03 02:39:13 thomas Exp $");
#else
  fprintf(stdout,"Content-type: text/html\n\n%s",CANNED_ERROR);
#endif
  fflush(stdout);
  va_end(ap);
  exit(-1);
}

/* Find the physical path of a directory, following symbolic and 
   hard links. This transforms the argument in place, so it must
   be at least MAXPATHLEN in size! */
static char* to_abs(char* directory) {
  if (chdir(directory) < 0)
    fatal_error("Can't chdir() to %s: %s\n",escape(directory),strerror(errno));
  if (!getcwd(directory,MAXPATHLEN))
    fatal_error("Error during getcwd(): %s\n",strerror(errno));
  return directory;
}
#ifdef USE_ABSOLUTE_ROOT
char* document_root () {
  char *document_root;
  int pathlen;
  if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1)))
    fatal_error("out of memory while allocating space for document root string\n");
  pathlen = strlen(USE_ABSOLUTE_ROOT);
  strncpy(document_root,USE_ABSOLUTE_ROOT, pathlen+1);
  document_root[pathlen+1] = '\0';
  return document_root;
}
#else
/* Find the document root by subtracting PATH_INFO from PATH_TRANSLATED */
char* document_root () {
  char *path_info,*path_translated,*document_root;
  int p,v,common;
    
  /* fetch the PATH_TRANSLATED environment variable */
  /* should print out usage information, actually */
  path_translated = (char*) getenv("PATH_TRANSLATED");
  if (path_translated == NULL)
    fatal_error("Please specify the script to run with the format: \"%s/script/to/run\".\n",
		escape((char*)getenv("SCRIPT_NAME")));

  /* fetch the PATH_TRANSLATED environment variable */
  /* should print out usage information, actually */
  path_info = (char*) getenv("PATH_INFO");
  if (path_info == NULL)
    fatal_error("please specify the script to run \"%s/script/to/run\"\n",
		escape((char*)getenv("SCRIPT_NAME")));
  
  /* find the document root by proceeding from right to left */
  for (common=p=strlen(path_translated),v=strlen(path_info);
       p>=0 && v>=0;
       p--,v--) {
    if (path_translated[p] != path_info[v])
      break;
    if (path_translated[p] == '/') 
      common = p;
  }
  if (path_translated[common] == '/')
    common--;

  /* now common points to the end of the document root */
  if (common+2 > MAXPATHLEN)
    fatal_error("path translated is larger than MAXPATHLEN: \"%s\"",path_translated);

  /* at this point, common points to the end of the document root */
  
  if (!(document_root = (char*) calloc(sizeof(char),MAXPATHLEN+1)))
    fatal_error("out of memory while allocating space for document root string\n");

  strncpy(document_root,path_translated,common+1);
  document_root[common+1] = '\0';
  return document_root;
}
#endif

/* Find the path to the target script and return it, along
 * with the additional path info, if any.  Also returns stat
 * structures for the target and its directory.
 * A side-effect is that the target's directory is made the current
 * working directory.
 */
char* fetch_target(char* root,char** additional,struct stat* starg,struct stat* sdir) {

  char *path_info,*path_translated,*dir=NULL,*path,*p;
  char *raw,*shaved,target[MAXPATHLEN+1],directory[MAXPATHLEN+1];
  int valid = 0;
  int additional_length,max;

  /* fetch the PATH_{TRANSLATED,INFO} environment variables */
  /* we will have errored out before this if these are undefined 
     or zero length */
  path_translated = (char*) getenv("PATH_TRANSLATED");
  path_info = (char*) getenv("PATH_INFO");

  if (path_info[0] != '/')
    fatal_error("PATH_INFO does not begin with a '/'\n");

  /* if this is the /~user type of path info, then the translated path is
     the root, appended to CGI_BIN, appended to the shaved path */
  if (path_info[1] == '~')
    shaved = shave(root,path_translated);
  else
    shaved = path_info;

  if (strlen(root)+1+strlen(CGI_BIN) > MAXPATHLEN)
    fatal_error("Script directory path larger than MAXPATHLEN\n");
  strncpy(directory,root,MAXPATHLEN);
  directory[MAXPATHLEN] = '\0';
  strncat(directory,"/",1);
  strncat(directory,CGI_BIN,strlen(CGI_BIN));

  /* resolve symbolic links and relative paths */
  to_abs(directory);
  
  max = strlen(directory) + strlen(shaved) + 1;
  if (!(raw = (char*)calloc(sizeof(char),max)))
    fatal_error("Unable to allocate memory for path to CGI script: %s\n",strerror(errno));
  strncpy(raw,directory,max);
  strncat(raw,shaved,strlen(shaved));
  raw[max-1] = '\0';

  /* step down the path until we find the directory and the executable */
  p = raw+1;
  while ((p = strchr(p,'/'))) {
    if ( (p-raw) >  MAXPATHLEN)
      fatal_error("path_info too long\n");

    strncpy(target,raw,p-raw);
    target[p-raw] = '\0';

    /* make sure there are no ".." path components!!!! */
    if (strncmp(p,"/..",3) == 0)
      fatal_error("path to CGI script (%s) must not contain relative path components\n",escape(raw));

    if (stat(target,starg) < 0)
      fatal_error("Stat failed. %s: %s\n",escape(target),strerror(errno));

    /* if it's a directory, then copy it into dir for safe keeping */
    if (S_ISDIR(starg->st_mode))
      memcpy((void*)sdir,(void*)starg,sizeof(struct stat));
    else 
      if ((valid = S_ISREG(starg->st_mode)) == TRUE )
	break;
    dir = p;
    p++;
  }
  /* If the executable is the last item on the path, then we will not
     have found a valid partial path.  Stat the whole thing. */
  if (!valid) {
    if (stat(raw,starg) < 0)
      fatal_error("Stat failed. %s: %s\n",escape(raw),strerror(errno));

    if (!S_ISREG(starg->st_mode))
      fatal_error("Couldn't find a valid script to execute in %s\n",escape(raw));

    p = raw + strlen(raw);
    strncpy(target,raw,MAXPATHLEN);
    target[MAXPATHLEN] = '\0';
  }

  /* Everything to the right of the end of target is additional path info */
  additional_length = strlen(raw) - strlen(target);
  if (!(*additional = (char*) calloc(sizeof(char),additional_length+1)))
    fatal_error("Unable to allocate memory for additional path info.\n");

  strncpy(*additional,raw+strlen(target),additional_length);
  (*additional)[additional_length] = '\0';

  /* turn the directory part of the target into a real directory, resolving
     symbolic paths */
  strncpy(directory,target,dir-raw);
  directory[dir-raw]='\0';

  to_abs(directory);

  max = strlen(directory)+(p-dir)+1;
  if (!(path = (char*)calloc(sizeof(char),max)))
    fatal_error("unable to allocate memory during calloc() of physical path: %s\n",strerror(errno));

  strncpy(path,directory,max);
  strncat(path,dir,p-dir);
  path[max-1] = '\0';
  if (raw != NULL)
    free((void*)raw);
  return path;
}

/* implement a variety of checks on the script before executing it */
void check_target(const char* newroot,
		  const char* target,
		  const struct stat *file_stats,
		  const struct stat *dir_stats) {
  struct passwd *pass;
  struct group *grp;

#if !defined(DEBUG)
  /* 1) script must not be SUID or SGID*/
  if (file_stats->st_mode & S_ISUID)
    fatal_error("cannot run suid scripts (%s)\n",escape(target));

  if (file_stats->st_mode & S_ISGID)
    fatal_error("cannot run sgid scripts (%s)\n",escape(target));

  /* 2) script must be executable by other */
  if (!( (file_stats->st_mode & S_IXOTH)))
    fatal_error("%s not world executable\n",escape(target));

  /* 3) script is not owned by WEB_USER or WEB_GROUP */
  if ((pass = getpwuid(file_stats->st_uid)) == NULL)
    fatal_error("%s is owned by an unknown user (%ld)\n",escape(target),file_stats->st_uid);

#if !defined(ALLOW_WEB_OWNED_SCRIPTS)
  if (!(strcmp(pass->pw_name,WEB_USER)))
    fatal_error("%s is owned by the Web user (%s)\n",escape(target),WEB_USER);
#endif
	

  if ((grp = getgrgid(file_stats->st_gid)) == NULL) 
    fatal_error("%s is owned by an unknown group (%ld)\n",escape(target),file_stats->st_gid);

#if !defined(ALLOW_WEB_OWNED_SCRIPTS)
  if (!(strcmp(grp->gr_name,WEB_GROUP)))
    fatal_error("%s is owned by the Web group (%s)\n",escape(target),WEB_GROUP);
#endif
  
  /* 4) directory is not owned by WEB_USER or WEB_GROUP */
  if ((pass = getpwuid(dir_stats->st_uid)) == NULL)
    fatal_error("the directory containing %s is owned by an unknown user (%ld)\n",
      escape(target),dir_stats->st_uid);

#if !defined(ALLOW_WEB_OWNED_SCRIPTS)
  if (!(strcmp(pass->pw_name,WEB_USER)))
    fatal_error("the directory containing %s is owned by the Web user (%s)\n",escape(target),WEB_USER);
#endif

  if ((grp = getgrgid(dir_stats->st_gid)) == NULL) 
    fatal_error("the directory containing %s is owned by an unknown group (%ld)\n",
      escape(target),dir_stats->st_gid);

#if !defined(ALLOW_WEB_OWNED_SCRIPTS)
  if (!(strcmp(grp->gr_name,WEB_GROUP)))
    fatal_error("the directory containing %s is owned by the Web group (%s)\n",escape(target),WEB_GROUP);
#endif

  /* 5) Neither file nor the directory are writable by other */
  if (file_stats->st_mode & S_IWOTH)
    fatal_error("%s is world writable\n",escape(target));

  if (dir_stats->st_mode & S_IWOTH)
    fatal_error("the directory containing %s is world writable\n",escape(target));
  
#if DO_CHROOT
  /* 6) target must be located within the new root */
  if (strstr(target,newroot) != target)
    fatal_error("%s is not contained within the chroot directory %s\n",escape(target),newroot);
#endif

  /* 7) owner and group must not be less than UID_MIN, GID_MIN */
#if DO_SUID
#if SID_MODE == DIRECTORY
  if (dir_stats->st_uid < UID_MIN)
    fatal_error("the directory containing %s must not be owned by a UID less than %d\n",escape(target),UID_MIN);
#else
  if (file_stats->st_uid < UID_MIN)
    fatal_error("the file containing %s must not be owned by a UID less than %d\n",escape(target),UID_MIN);
#endif
#endif

#if DO_SGID
#if SID_MODE == DIRECTORY
  if (dir_stats->st_gid < GID_MIN)
    fatal_error("the directory containing %s must not be owned by a GID less than %d\n",escape(target),GID_MIN);
#else
  if (file_stats->st_gid < GID_MIN)
    fatal_error("the file containing %s must not be owned by a GID less than %d\n",escape(target),GID_MIN);
#endif
#endif

  /* 8) owner and group must not be greater than UID_MAX, GID_MAX */
#if DO_SUID
#if SID_MODE == DIRECTORY
  if (dir_stats->st_uid > UID_MAX)
    fatal_error("the directory containing %s must not be owned by a UID greater than %d\n",escape(target),UID_MAX);
#else
  if (file_stats->st_uid > UID_MAX)
    fatal_error("the file containing %s must not be owned by a UID greater than %d\n",escape(target),UID_MAX);
#endif
#endif

#if DO_SGID
#if SID_MODE == DIRECTORY
  if (dir_stats->st_gid > GID_MAX)
    fatal_error("the directory containing %s must not be owned by a GID greater than %d\n",escape(target),GID_MAX);
#else
  if (file_stats->st_gid > GID_MAX)
    fatal_error("the file containing %s must not be owned by a GID greater than %d\n",escape(target),GID_MAX);
#endif
#endif

#endif

}

char* fetch_newroot(char* docroot) {
  char newd[MAXPATHLEN+1],*newroot;
  int max;

  max = strlen(docroot) + 1 + strlen(ROOT);
  if ( max > MAXPATHLEN)
    fatal_error("document root is too large: \"%s\"",docroot);
  
  strncpy(newd,docroot,max);
  strncat(newd,"/",1);
  strncat(newd,ROOT,strlen(ROOT)); /* tack on the new root component */
  newd[MAXPATHLEN] = '\0';
  if ((newroot = strdup(to_abs(newd))) == NULL)
    fatal_error("unable to allocate memory while making copy of new root directory path: %s\n",
		strerror(errno));
  return newroot;
}

char* shave(char* newroot,
	    char* target) {

  char* shaved = target;
  char* h = newroot;

  if (!newroot) return target;
  if (!target) return "";

  while (*shaved && *h) {
     if (*shaved++ != *h++)
       break;
  }
  if (*h) return "/";
  return shaved;
}

/* modify the environment in the following ways: 
 * DOCUMENT_ROOT => shave(DOCUMENT_ROOT)
 * PATH_INFO => path_info
 * PATH_TRANSLATED => "DOCUMENT_ROOT/path_info"
 * SCRIPT_FILENAME => shave(target)
 * SCRIPT_NAME => "$SCRIPT_NAME/shave(target)"
 */
static void tweak_environment(char* newroot,
			      char* root,
			      char* target,
			      char* additional_info) {
  char *s,*t,*path_info,*script_name;
  int r,max;

  /* the SCRIPT_NAME needs to be the URL that we invoke to get at the
   script again.  */
  path_info = (char*) getenv("PATH_INFO");
  script_name = (char*) getenv("SCRIPT_NAME");
  if (script_name == NULL)
    fatal_error("expect SCRIPT_NAME environment variable to be set, but null found\n");

  /* set the script name -- it should be existing SCRIPT_NAME concatenated
     to the path info, less the additional info.  SCRIPT_NAME can be used to
     reinvoke the script in virtual name space*/
  max = strlen(script_name) +  strlen(path_info) -  strlen(additional_info) +  1;

    s = (char*) calloc(sizeof(char),max);
    if (s == NULL)
      fatal_error("failed to allocate memory for SCRIPT_NAME: %s\n",strerror(errno));

    strncpy(s,script_name,max);
    strncat(s,path_info,strlen(path_info)-strlen(additional_info));
    s[max-1] = '\0';

    r = set_env("SCRIPT_NAME",s,1);
    if (r < 0) 
      fatal_error("no room for SCRIPT_NAME environment variable");

    free((void*)s);

    if (*additional_info) {
      /* set the path info */
      r = set_env("PATH_INFO",additional_info,1);
      if (r < 0) 
	fatal_error("no room for PATH_INFO environment variable");

      t = shave(newroot,root);

      max = strlen(t)+strlen(additional_info)+1;
      if (!(s = (char*) calloc(sizeof(char),max)))
	fatal_error("unable to allocate string for path translated: %s\n",strerror(errno));

      /* set the path translated */
      strncpy(s,t,max);
      if (t[strlen(t)-1] == '/')
	strncat(s,additional_info+1,strlen(additional_info)-1);
      else
	strncat(s,additional_info,strlen(additional_info));
      s[max-1] = '\0';
      r = set_env("PATH_TRANSLATED",s,1);
      if (r < 0) 
	fatal_error("no room for PATH_TRANSLATED environment variable");

      free((void*)s);
    }

  /* Shave the chroot directory off the target.  Will error out
     if the target is not contained within the new root. */
  s = shave(newroot,target);
  r = set_env("SCRIPT_FILENAME",s,1);
  if (r < 0) 
    fatal_error("no room for SCRIPT_FILENAME environment variable");

  s = shave(newroot,root);
  r = set_env("DOCUMENT_ROOT",s,1);
  if (r < 0) 
    fatal_error("no room for DOCUMENT_ROOT environment variable");
}

/* set_env() is a replacement for the BSD setenv() function. */
static int set_env(const char *name, const char *value, int overwrite) {
  char **ep,**var,*d;

  /* initialize cleanenv global if necessary */
  if (cleanenv == NULL) {
    if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL)
      return -1;
  }
  
  /* search for the string in the existing environment */
  ep = cleanenv;
  while (((var = ep++) != NULL) && *var) {
    d = (char*) strchr(*var,'=');  /* look for the "=" sign */
    if (!d) continue;             /* malformed entry */
    if ((int)strlen(name) != abs(d-*var)) continue;
    if (0 != strncmp(*var,name,d-*var)) /* compare to target string */
	continue;

    /* if we get here, we found the environment variable */
    if (!overwrite) return 0; /* not allowed to overwrite the variable */

    /* clear out the previous value */
    free((void*) *var);
    *var = NULL;
  }
  /* when we get here var points to the place in the environment string
     for the new value */
  /* First make sure we haven't run off the end of the buffer.  Must be a terminal
     NULL in the array */
  if (var - cleanenv >= AP_ENVBUF - 1)
    return -1;

  if ( (*var = (char*)calloc(strlen(name)+1+strlen(value)+1,sizeof(char))) == NULL)
    return -1; /* out of space */
  
  /* copy */
  if (sprintf(*var,"%s=%s",name,value) <= 0)
    return -1; /* don't know when this would happen */

  return 0;
}

/* clean_env() is derived from similar routine in suexec.c, 
   part of the Apache distribution */
void clean_env() 
{
  char pathbuf[NAME_MAX];
  char **ep;
  int cidx = 0;
  int idx;
  

  /* initialize cleanenv global if necessary */
  if (cleanenv == NULL) {
    if ((cleanenv = (char **)calloc(AP_ENVBUF, sizeof(char *))) == NULL)
      fatal_error("failed to malloc env mem\n");
  }

  /* position to first NULL entry in cleanenv */
  for (cidx = 0; cleanenv[cidx] && cidx < AP_ENVBUF; cidx++)
    ;

  /* copy the environment */
  for (ep = environ; *ep && cidx < AP_ENVBUF; ep++) {
    if (!strncmp(*ep, "HTTP_", 5)) {
      cleanenv[cidx] = *ep;
      cidx++;
    }
    else {
      for (idx = 0; safe_env_lst[idx]; idx++) {
	if (!strncmp(*ep, safe_env_lst[idx], strlen(safe_env_lst[idx]))) {
	  cleanenv[cidx] = *ep;
	  cidx++;
	  break;
	}
      }
    }
  }
  
  if (strlen(SAFE_PATH)+strlen("PATH=")+1 > NAME_MAX)
    fatal_error("value of SAFE_PATH (%s) is too large (max %d bytes)\n",escape(SAFE_PATH),NAME_MAX);

  sprintf(pathbuf, "PATH=%s", SAFE_PATH);
  cleanenv[cidx] = strdup(pathbuf);
  cleanenv[++cidx] = NULL;
}

char* escape (const char* str) {
  char *escaped,*s,c;
  int count = 0;

  if (str == NULL)
    return NULL;

#if ECHO_FAILURES

  s = (char*) str;
  count = strlen(str);

  while (c = *s++) {
    if (c == '<' || c == '>') {
      count += 4;
    } else if (c == '&') {
      count += 5;
    }
  }

  escaped = (char*) calloc(sizeof(char),count+1);
  s = escaped;
  while (c = *str++) {
    if (c == '<') {
      strcat(s,"&lt;");
      s+=4;
    }
    else if (c == '>') {
      strcat(s,"&gt;");
      s+=4;
    }
    else if (c== '&') {
      strcat(s,"&amp;");
      s+=5;
    }
    else {
      *s++ = c;
    }
  }
  return escaped;
#else
  return (char*) str;
#endif
}

/* chdir() to the directory where CGI script is located so that
   most e.g. Perl scripts that use relative paths work. the function
   gets the the full path to the chroot() directory (newroot) and full
   path (target) to the CGI script and extracts the correct subdirectory
   where the script resides on and does chdir() there. */
static void chdir_fix(char* newroot, char* target) {

  char *chdir_path;
  int i,j;
  int start=0;
  int end=0;

  chdir_path = (char*) calloc(sizeof(char),MAXPATHLEN);
  if (chdir_path == NULL)
    fatal_error("failed to allocate memory for chdir path: %s\n",strerror(errno));

  for (i=0; target[i]!='\0' && newroot[i]!='\0'; i++) {
    if (target[i] == newroot[i])
      start++;
    else
      continue;
  }

  for (i=0; target[i]!='\0'; i++)
    if (target[i] == '/')
      end=i;

  j = 0;
  if (start>0 && end>0 && start<end) {
    for (i=start; i<end; i++) {
      chdir_path[j] = target[i];
      j++;
    }

    if (chdir(chdir_path) < 0)
      fatal_error("Can't chdir() to %s: %s\n",chdir_path,strerror(errno));
                                
  }
}

#if SET_LIMITS
void set_limits() {
  struct rlimit limit;

#ifdef RLIMIT_CPU
  SETLIMIT(CPU);
#endif

#ifdef RLIMIT_FSIZE
  SETLIMIT(FSIZE);
#endif

#ifdef RLIMIT_DATA
  SETLIMIT(DATA);
#endif

#ifdef RLIMIT_STACK
  SETLIMIT(STACK);
#endif

#ifdef RLIMIT_CORE
  SETLIMIT(CORE);
#endif

#ifdef RLIMIT_NOFILE
  SETLIMIT(NOFILE);
#endif

#ifdef RLIMIT_RSS
  SETLIMIT(RSS);
#endif
#ifdef RLIMIT_NPROC
  SETLIMIT(NPROC);
#endif
  setpriority(PRIO_PROCESS,0,PRIORITY);
}
#endif