File: fuzz.c

package info (click to toggle)
fuzz 0.6-14
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 380 kB
  • ctags: 145
  • sloc: ansic: 2,826; sh: 330; makefile: 9
file content (1253 lines) | stat: -rw-r--r-- 34,176 bytes parent folder | download | duplicates (2)
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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
/* fuzz version 0.5 11/16/1999
   Copyright Ben Woodard <ben@valinux.com> & VA Linux Systems.
   All rights reserved.
   Licence: GPL

   The purpose of this program is to generate random garbage and 
   pass that random garbage into a program to see if it can be 
   made to crash or hang. It will pass this garbage into the 
   program in one of two ways. The first is on the command line 
   and the second is on through standard in. It runs the victim
   program a specified number of times dumping any output out to 
   /dev/null. If it manages to get the program to crash, it stops.
   The reason for this is debatable but reasonable. I figured that
   once we have discovered one exploit it is best to stop and fix
   it rather than discovering literally hundreds of ways of 
   triggering the same bug.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <ctype.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <pwd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>


#ifdef HAVE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#else
// Little replacement for readline if it is not available
char *chomp(char *str);
char *readline(const char *prompt){
  char *retval;
  
  printf("%s",prompt);
  retval=malloc(10240);
  retval[10239]=0;
  fgets(retval,10239,stdin);
  return chomp(retval);
}
#endif

#define BADOPS_EXIT 1
#define CANT_CHROOT_EXIT 2
#define CANT_EXEC_EXIT 3
#define NORAND_EXIT 4
#define ARGFILE_EXIT 5
#define NOMEM_EXIT 6
#define CANT_FORK_EXIT 7
#define CHILDFD_EXIT 8
#define NORCFILE_EXIT 9
#define NOREPORT_EXIT 10

#define RESULT_PASSED 1
#define RESULT_FAILED 0

/* borrowed this from vixie-cron 
 -Fx	 = set full-name of sender
 -odi	 = Option Deliverymode Interactive
 -oem	 = Option Errors Mailedtosender
 -or0s = Option Readtimeout -- don't time out (which doesn't seem
         to work for fuzz)
*/
#define SENDMAILARGS "-odi -oem -Ffuzz"
#define DESTADDR "fuzzmonster@zgp.org"

/* Probably the best way to do this is to make the RAND_DEVICE
   /dev/random however this requires user input and so it it 
   really won't work when you need a large amount of data.  It 
   will literally take a couple of seconds for each couple of 
   bytes.  
*/
#define RAND_DEVICE "/dev/urandom"
// #define RAND_DEVICE "/dev/random"

#define DEFRUNS 10000
#define DEFLEN 100000
#define DEFTIMEOUT 120

#define MAXPATH 10240
#define MAXARGS 256
#define MAXARGLEN 256

/* global variables
   These are either needed by the signal handlers or send_report 
   which is called by the signal handlers */
unsigned long runs=DEFRUNS; 
char progname[MAXPATH];      
char outfilename[MAXPATH];   
pid_t newpid;                
char rundone=0;              
unsigned long max_args=0; 
char *argfilename;        
int g_argc;
char **g_argv;
int report;
char sendmail[MAXPATH];
char distribution[MAXPATH];
char dontask=0;

void print_arglist(FILE*,char **,char,char);
int setup_user(char *distribution, char *sendmail);
void handle_sigalrm(int dummy);
void handle_sigchld(int dummy);
void do_child(int *progpipe, char **argv, char *execute_filename, 
	      unsigned long max_arglen,char printable_only,int nullfd,
	      int randfd);
void send_report(char result, char report, char *sendmail, char *distribution);

char *chomp(char * str){
  int i=strlen(str);
  if(str[i-1]=='\n')
    str[i-1]=0;
  return str;
}

void usage(){
  fprintf(stderr,"usage: fuzz [-p] [-r runcount] [-p] [-n linemod] [-l length] [-m maxlinelen]\n            [-t timeout] [-c] [-u user] [-x maxargs] [-y maxarglen] [-e number]\n            command [arg...]\n");
  exit(BADOPS_EXIT); 
}

int main(int argc, char **argv){
  char binfound=0;
  unsigned long max_arglen=MAXARGLEN;
  char *execute_filename=NULL;
  char printable_only=0;
  int curarg;
  unsigned long len=DEFLEN;
  unsigned long timeout=DEFTIMEOUT;
  unsigned long maxline=0;
  unsigned long linemod=0;
  char print_bytes=0;
  char omit_data=0;
  char chr=0;
  int prio;
  static const struct option longopts[]={
    {"args",      no_argument,      NULL,'a'},
    {"bytes",     no_argument,      NULL,'b'},
    {"chroot",    no_argument,      NULL,'c'},
    {"dontask",   no_argument,      NULL,'d'},
    {"execute",   required_argument,NULL,'e'},
    {"priority",  required_argument,NULL,'i'},
    {"length",    required_argument,NULL,'l'},
    {"maxline",   required_argument,NULL,'m'},
    {"newlines",  required_argument,NULL,'n'},
    {"omitdata",  no_argument,      NULL,'o'},
    {"printable", no_argument,      NULL,'p'},
    {"runcount",  required_argument,NULL,'r'},
    {"timeout",   required_argument,NULL,'t'},
    {"user",      required_argument,NULL,'u'},
    {"version",   no_argument,      NULL,'V'},
    {"maxargs",   required_argument,NULL,'x'},
    {"maxarglen", required_argument,NULL,'y'},
    NULL
  };
  char *path;
  char bin_found=0;
  FILE *outfile;
  FILE *infile;
  struct sigaction act; 
  struct passwd *userinfo=NULL;
  int nullfd;
  int randfd;

  g_argc=argc;
  g_argv=argv;
  while((curarg=getopt_long(argc,argv,"+a::bcde:i:l:m:n:opr:t:u:Vx:y:",
			    longopts,NULL))!=EOF){
    switch(curarg){
    case 'r':
      if(sscanf(optarg,"%ul",&runs)!=1){
	fprintf(stderr,"Bad number of runs.\n");
	usage();
      }
      break;
    case 'l':
      if(sscanf(optarg,"%ul",&len)!=1){
	fprintf(stderr,"Bad length of data stream.\n");
	usage();
      }
      break;
    case 'p':
      printable_only=1;
      break;
    case 'n':
      if(sscanf(optarg,"%ul",&linemod)!=1){
	fprintf(stderr,"Bad line length modifier.\n");
	usage();
      }
      break;
    case 'm':
      if(sscanf(optarg,"%ul",&maxline)!=1){
	fprintf(stderr,"Bad max line length.\n");
	usage();
      }      
      break;
    case 't':
      if(sscanf(optarg,"%ul",&timeout)!=1){
	fprintf(stderr,"Bad max line length.\n");
	usage();
      }      
      break;
    case 'b':
      print_bytes=1;
      break;
    case 'c':
      chr=1;
      break;
    case 'u':
      if((userinfo=getpwnam(optarg))==NULL){
	fprintf(stderr,"Can't look up user id.\n");
	perror(argv[0]);
	exit(BADOPS_EXIT);
      }
      break;
    case 'o':
      omit_data=0;
      break;
    case 'a':
      max_args=MAXARGS;
      break;
    case 'x':
      if(sscanf(optarg,"%ul",&max_args)!=1){
	fprintf(stderr,"Bad max number of args.\n");
	usage();
      }
      break;
    case 'y':
      if(sscanf(optarg,"%ul",&max_arglen)!=1){
	fprintf(stderr,"Bad max argument length.\n");
	usage();
      }
      break;
    case 'e':
      execute_filename=optarg;
      runs=1;
      break;
    case 'i':
      if(sscanf(optarg,"%i",&prio)!=1){
	fprintf(stderr,"Bad priority argument.\n");
	usage();
      }
      if (setpriority(PRIO_PROCESS,0,prio)) {
	fprintf(stderr,"Error setting nice priority.\n");
	perror(argv[0]);
	}
      break;
    case 'V':
      printf("full %s\n",VERSION);
      exit(0);
    case 'd':
      dontask=1;
      break;
    default:
      fprintf(stderr,"Bad argument.\n");
      // intentionally falls through
    case '?':
      usage();
    }
  }

  /* these need to be before the chroot and before the user swap
     so that it can get at the configuration file. This is 
     probably a security bug. */
  report=setup_user(distribution,sendmail);

  if(execute_filename){
    if((infile=fopen(execute_filename,"r"))==NULL){
      fprintf(stderr,"Can't seem to open file to read from.\n");
      perror(argv[0]);
      exit(BADOPS_EXIT);
    }
  }else{
    //open up /dev/random
    if((randfd=open(RAND_DEVICE,O_RDONLY))==-1){
      fprintf(stderr,"Cannot open %s.\n",execute_filename);
      exit(NORAND_EXIT);
    }

    if((infile=fdopen(randfd,"r"))==NULL){
      fprintf(stderr,"Can't open /dev/random for reading\n");
      exit(NORAND_EXIT);
    }
  }

  if((nullfd=open("/dev/null",O_WRONLY))==-1){
    perror("fuzz");
    fprintf(stderr,"Can't open /dev/null.\n");
    exit(CHILDFD_EXIT);
  }

  // end of stuff that must before chroot

  if(chr){
    char curpath[MAXPATH];
    if(getcwd(curpath,MAXPATH)==NULL){
      fprintf(stderr,"Can't get current path name to chroot to.\n");
      perror(argv[0]);
      usage();
    }
    if(chroot(curpath)==-1){
      fprintf(stderr,"Can't chroot.\n");
      perror(argv[0]);
      exit(CANT_CHROOT_EXIT);
    }
  }

  if(userinfo && setreuid(userinfo->pw_uid,userinfo->pw_uid)==-1){
    fprintf(stderr,"Can't change to user: %s\n",optarg);
    perror(argv[0]);
    exit(BADOPS_EXIT);
  }

  //make sure this isn't being run as root.
  if(getuid()==0){
    fprintf(stderr,"*** Don't run this program as root! ***\n");
    if (chr)
	fprintf(stderr,"    Need option --user USER with --chroot\n");
    usage();
  }

  //check that the program exists
  if(optind==argc) //They didn't tell me what program to run
    usage();
  if(!(argv[optind][0]=='/' || argv[optind][0]=='.')){
    //if we don't know the full path already.
    char *modpath,*tok;
    if(getenv("PATH")==NULL){
      fprintf(stderr,"Warning: no path set using /bin:/usr/bin\n");
      path="/bin:/usr/bin";
    }else
      path=getenv("PATH");
    modpath=strdup(path);
    for(tok=strtok(modpath,":");tok!=NULL;tok=strtok(NULL,":")){
      struct stat statbuf;

      *progname=0;
      strncpy(progname,tok,MAXPATH);
      strncat(progname,"/",MAXPATH);
      strncat(progname,argv[optind],MAXPATH);
      if(stat(progname,&statbuf)==0){
	binfound=1;
	break;
      }
    }
  }else{
    // check that the binary is there
    struct stat statbuf;
    strcpy(progname,argv[optind]);
    if(stat(progname,&statbuf)==0)
      binfound=1;
  }
  if(!binfound){
    fprintf(stderr,"Program not found.\n");
    usage();
  }

  // setup the signals
  act.sa_handler=handle_sigalrm;
  if(sigemptyset(&act.sa_mask)==-1){
    fprintf(stderr,"can't clear signal mask.\n");
    abort();
  }
  act.sa_flags=0;
  sigaction(SIGALRM,&act,NULL);

  act.sa_handler=handle_sigchld;
  if(sigaddset(&act.sa_mask,SIGALRM)==-1){
    fprintf(stderr,"Can't add SIGALRM to signal mask.\n");
    abort();
  }
  sigaction(SIGCHLD,&act,NULL);

  // clearerr(infile);

  // run the program on the data sets
  for(;runs;runs--){
    int progpipe[2],status;
    char sendnewline=0;
    unsigned long curchar=0,linelen=0;

    // finish setting up files
    if(!execute_filename){
      snprintf(outfilename,MAXPATH,"/tmp%s.%lu",strrchr(progname,'/'),runs);
      if((outfile=fopen(outfilename,"w"))==NULL){
	fprintf(stderr,"Can't fopen outfile.\n");
	abort();
      }
      if((argfilename=strdup(outfilename))==NULL){
	fprintf(stderr,"Failed to strdup outfilename.\n");
	exit(ARGFILE_EXIT);
      }
      
      if((argfilename=realloc(argfilename,strlen(argfilename)+5))==0){
	fprintf(stderr,"Failed to realloc outfilename.\n");
	exit(ARGFILE_EXIT);
      }
      strcat(argfilename,".arg");
    }

    printf("Run: %u         %c",runs,print_bytes?'\n':'\r');
    if(pipe(progpipe)==-1){
      fprintf(stderr,"Can't pipe.\n");
      abort();
    }

    rundone=omit_data?1:0; // this implements the omit data feature

    if((newpid=fork())==-1){
      fprintf(stderr,"Can't fork.\n");
      abort();
    } else if(newpid==0){ //childproc
      do_child(progpipe,argv+optind,execute_filename,max_arglen,
	       printable_only,nullfd,randfd);
    }

    /**** handle main process */
    //start timer
    alarm(timeout);

    //feed chars down the pipe 
#ifdef HAVE_SENDFILE
    if(!print_bytes && !printable_only && !execute_filename && !linemod &&
       !rundone){
      off_t offset=0;
      if(sendfile(progpipe[1],randfd,&offset,len)==-1){
	fprintf(stderr,"sendfile failed\n");
	perror("fuzz");
	exit(NORAND_EXIT);
      }
    }else{
#endif
      for(curchar=0,linelen=0; !rundone && curchar<len; curchar++){
	char byte;
	
	if(print_bytes)
	  printf("\t%ld\r",curchar);
	if(!sendnewline){
	  do{
	    byte=fgetc(infile);
	    if(feof(infile)){
	      if(execute_filename){
		break; //we're done -- no problem
	      }else{
		fprintf(stderr,"Ran out of random data.\n");
		exit(NORAND_EXIT);
	      }
	    }
	  }while(printable_only && !isprint(byte));
	} else {
	  sendnewline=0;
	  byte='\n';
	}

	// make the race condition a bit harder to hit.
	if(rundone){
	  // fputs("lost race\n",stderr);
	  break;
	}
	if(write(progpipe[1],&byte,1)==-1){
	  if(errno==EINTR)
	    break;
	  else{
	    fprintf(stderr,"Write failed on pipe.\n");
	    perror(argv[0]);
	  }
	}
	if(!execute_filename)
	  fputc(byte,outfile);
	linelen++;
	if(byte=='\n')
	linelen=0;
	if((maxline!=0 && linelen==maxline) || 
	   (linemod!=0 && random()%linemod==0))
	  sendnewline=1;
      }
#ifdef HAVE_SENDFILE
    }
#endif

    //fputs("done with run\n",stderr);
    //clean up
    alarm(0); //cancle the alarm
    if(close(progpipe[0])==-1 ||close(progpipe[1])==-1){
      fprintf(stderr,"Warning: Can't close pipe ends.\n");
      perror(argv[0]);
    }
    kill(newpid,2);
    //    wait(&status);
    if(!execute_filename)
      fclose(outfile);
    if(unlink(outfilename)==-1){
      fprintf(stderr,"Can't unlink data file.\n");
      perror(argv[0]);
    }
    if(max_args && unlink(argfilename)==-1){
      fprintf(stderr,"Can't unlink arguments file.\n");
      perror(argv[0]);
    }
    fflush(stdout); 
/*     if(runs%10==0) */
/*       sleep(1); */
  }
  printf("Testing %s done -- No faults found.\n",progname);

  send_report(RESULT_PASSED, report, sendmail, distribution);
  exit(0);
}

/* this is for debugging use only */
void print_arglist(FILE* errs,char **argv,char expand_args, char hex){
  unsigned int i;
  fprintf(errs,"argv=0x%x\n",argv);
  for(i=0;argv[i]!=NULL;i++){
    fprintf(errs,"\targv[%u]=0x%x\n",i,argv[i]);
    if(expand_args){
      if(hex){
	unsigned int j;
	fprintf(errs,"argv[%u]: ",i);
	for(j=0;argv[i][j]!=0;j++){
	  fprintf(errs,"%0.2x ",argv[i][j]);
	}
	fputc('\n',errs);
      }else{
	fprintf(errs,"argv[%u]: %s\n",i,argv[i]);
      }// hex
    }// expand_args
  }// foreach arg
} // print_arglist


void handle_sigalrm(int dummy){
  int status;

  printf("\nProgram killed by signal.\n");
  signal(SIGCHLD,SIG_DFL);
  kill(newpid,9);
  wait(&status);
  printf("\n");
  exit(0);
}

void handle_sigchld(int dummy){
  int status,termsig;
  //  fputs("Program quit.\n",stderr);
  rundone=1;
  alarm(0);
  wait(&status);
  if(WIFSIGNALED(status) && ((termsig=WTERMSIG(status))==SIGILL || 
			     termsig==SIGSEGV || termsig==SIGBUS || 
			     termsig==SIGKILL)){
    printf("Program: %s\n\tProblem: CRASH\tSignal: %d\tRun: %lu\tDatafile: %s\n",
	   progname,termsig,runs,outfilename);
    send_report(RESULT_FAILED, report, sendmail, distribution);
    printf("\n");
    exit(0);
  }
  //  fputs("handler done\n",stderr);
}

void do_child(int *progpipe, char **argv,char *execute_filename,
	      unsigned long max_arglen,char printable_only,int nullfd,
	      int randfd){
  int cpy_stderr;
  char buf[80];
  unsigned int buflen;
  char **arguments=argv;
  
  //  fputs("child started\n",stderr);
  if(chdir("/tmp")==-1){
    perror("fuzz");
    fprintf(stderr,"Can't change working dir to /tmp.\n");
    exit(CHILDFD_EXIT);
  }
  // redo stdin
  if(dup2(progpipe[0],0)==-1){
    perror("fuzz");
    fprintf(stderr,"Can't dup2 stdin to pipe.\n");
    exit(CHILDFD_EXIT);
  }
  close(progpipe[0]);
  close(progpipe[1]);
  
  //redo stdout
  if(dup2(nullfd,1)==-1){
    perror("fuzz");
    fprintf(stderr,"Can't dup2 stdout to /dev/null.\n");
    exit(CHILDFD_EXIT);
  }
  
  // redo stderr
  //Make a copy of stderr so that I can report errors after I 
  // get rid or real stderr 
  if((cpy_stderr=dup(2))==-1){
    perror("fuzz");
    fprintf(stderr,"Can't dup stderr.\n");
    exit(CHILDFD_EXIT);
  }

  if(fcntl(cpy_stderr,F_SETFD)==-1){
    perror("fuzz");
    fprintf(stderr,"can't close on exec cpy_stderr\n");
    exit(CHILDFD_EXIT);
  }

  if(dup2(nullfd,2)==-1){
    perror("fuzz");
    write(cpy_stderr,"Can't dup2 stderr to /dev/null.\n",
	  strlen("Can't dup2 stderr to /dev/null.\n"));
    exit(CHILDFD_EXIT);
  }
  close(nullfd);
      
  // buflen=snprintf(buf,80,"checking args - max_args=%u\n",max_args);
  // write(cpy_stderr,buf,buflen);
  if(max_args){
    unsigned int numoldargs=0;
    unsigned int numargs=random()%max_args;
    unsigned int totalargs;
    size_t dummy;
    char **curarg;
    int argfilefd;
    FILE *errs;
    // write(cpy_stderr,"1\n",2);

    if((errs=fdopen(cpy_stderr,"w"))==NULL){
      write(cpy_stderr,"fdopen fails\n",strlen("fdopen fails\n"));
      exit(CHILDFD_EXIT);
    }
    
    // write(cpy_stderr,"2\n",2);
    if(execute_filename){
      unsigned int i;

      if(execute_filename=realloc(execute_filename,
				  strlen(execute_filename)+5)){
	fprintf(errs,"Can't realloc execute_filename.\n");
	exit(NOMEM_EXIT);
      }

      strcat(execute_filename,".arg");

      // write(cpy_stderr,"3\n",2);
      if((dummy=read(randfd,&totalargs,sizeof(totalargs)))==-1 || 
	 dummy!=sizeof(totalargs)){
	fprintf(errs,"Failed to read number of arguments.\n");
	exit(ARGFILE_EXIT);
      }

      if((arguments=curarg=argv=malloc((1+totalargs)*sizeof(char*)))==NULL){
	fprintf(errs,"Failed to malloc space for args.\n");
	exit(NOMEM_EXIT);
      }
      argv[totalargs]=NULL;

      for(i=0;i<totalargs;i++,curarg++){
	unsigned int paramlen;
	if((dummy=read(randfd,&paramlen,sizeof(paramlen)))==-1 || 
	   dummy!=sizeof(paramlen)){
	  fprintf(errs,"Failed to read number of arguments.\n");
	  exit(ARGFILE_EXIT);
	}
	if(((*curarg)=malloc(paramlen+1))==NULL){
	  fprintf(errs,"Failed to malloc space for arg.\n");
	  exit(NOMEM_EXIT);
	}
	(*curarg)[paramlen]=0;

	if((dummy=read(randfd,*curarg,paramlen))==-1 || dummy!=paramlen){
	  fprintf(errs,"Failed to read parameter.\n");
	  exit(ARGFILE_EXIT);
	}
      }
      close(randfd);
    }else{
      if((argfilefd=open(argfilename,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|
			 S_IWUSR|S_IRGRP|S_IROTH))==-1){
	fprintf(errs,"Can't open argument file.\n");
	exit(ARGFILE_EXIT);
      }

      // count the number of arguments already in argv
      for(curarg=argv+1;(*curarg)!=NULL;curarg++){
	numoldargs++;

	// ***
	fprintf(errs,"counting - %s\n",*curarg);
	// fflush(errs);
      }

      // sleep(20);
      totalargs=numoldargs+numargs;

      // ***
      // fprintf(errs,"numargs = %u\nnumoldargs = %u\ntotargs = %u\n",numargs,
      // numoldargs,totalargs);

      if((arguments=curarg=malloc((totalargs+1)*sizeof(char*)))==NULL){
	fprintf(errs,"Not enough memory to allocate random args.\n");
	exit(NOMEM_EXIT);
      }

      // print_arglist(errs,arguments,0,0); // ***
      for(dummy=0;dummy<=totalargs;dummy++)
	arguments[dummy]=NULL;
      // print_arglist(errs,arguments,0,0); // ***
      

      if((dummy=write(argfilefd,&totalargs,sizeof(totalargs)))==-1 || 
	 dummy!=sizeof(totalargs)){
	fprintf(errs,"Can't write number of args.\n");
	exit(ARGFILE_EXIT);
      }

      // generate random arguments

      //copy the previous args.
      // fprintf(errs,"copying args\n"); // ***

      for(argv++;(*argv)!=NULL;curarg++,argv++){ 
	size_t arglen=strlen(*argv);

	
	// fprintf(errs,"copying arg\n"); // ***

	(*curarg)=(*argv);
	if((dummy=write(argfilefd,&arglen,sizeof(arglen)))==-1 || 
	   dummy!=sizeof(arglen)){
	  fprintf(errs,"Can't write old arg length.\n");
	  exit(ARGFILE_EXIT);
	}
	if((dummy=write(argfilefd,*curarg,arglen))==-1 || dummy!=arglen){
	  fprintf(errs,"Can't write old arg.\n");
	  exit(ARGFILE_EXIT);
	}

	// print_arglist(errs,arguments,0,0); // ***
      }

      // fprintf(errs,"generating new args\n"); // ***


      for(;numargs;numargs--,curarg++){
	unsigned long curarglen=random()%max_arglen;
	unsigned int i;

	// ***
	// print_arglist(errs,arguments,0,0); // ***
	// fprintf(errs,"-%x\n",curarg);
	// fprintf(errs,"--%x\n",curarg[0]);
	curarg[0]=malloc(curarglen+1);
	// fprintf(errs,"---%x\n",curarg[0]);

	if(curarg[0]==NULL){
	  fprintf(errs,"Not enough memory to allocate parameters.\n");
	  exit(NOMEM_EXIT);
	}
	// fputc('x',errs);
	// print_arglist(errs,arguments,0,0); // ***
	// fputc('x',errs);

	(*curarg)[curarglen]=0;

	if(read(randfd,(*curarg),curarglen)!=curarglen){
	  fprintf(errs,"Failed read on /dev/random. - %s\n",strerror(errno));
	  exit(NORAND_EXIT);
	}

	if(printable_only){
	  FILE *randfile=fopen(RAND_DEVICE,"r");
	  for(i=0;i<curarglen;i++){
	    while(!isprint((*curarg)[i])){
	      (*curarg)[i]=fgetc(randfile);
	    }
	  }
	  fclose(randfile);
	}

	// print_arglist(errs,arguments,0,0); // ***

	if((dummy=write(argfilefd,&curarglen,sizeof(curarglen)))==-1 || 
	   dummy!=sizeof(curarglen)){
	  fprintf(errs,"Can't write arg length.\n");
	  exit(ARGFILE_EXIT);
	}
	if((dummy=write(argfilefd,(*curarg),curarglen))==-1 || 
	   dummy!=curarglen){
	  fprintf(errs,"Can't write arg.\n");
	  exit(ARGFILE_EXIT);
	}
      }
    }
    if(fcntl(randfd,F_SETFD)==-1){
      fprintf(errs,"Cant set close on exec for randfd.\n");
      exit(CHILDFD_EXIT);
    }
    close(argfilefd);
    close(randfd);
  }

  //write(cpy_stderr,"execing test program\n",
  //      strlen("execing test program\n"));

  execv(progname,arguments);
  write(cpy_stderr,"Exec failed.\n",strlen("Exec failed.\n"));
  write(cpy_stderr,sys_errlist[errno],strlen(sys_errlist[errno]));
  exit(CANT_FORK_EXIT);
}

int setup_user(char *distribution, char *sendmail){
  char strbuf[MAXPATH];
  char *tmpbuf;
  int rcf;
  int fd;
  int tmp;
  struct stat statbuf;
  int report;
  
  snprintf(strbuf,MAXPATH-1,"%s/.fuzzrc",
	   (tmpbuf=getenv("HOME"))!=NULL?tmpbuf:".");
  if((rcf=open(strbuf,O_RDWR|O_CREAT,0644))==-1){
    perror("fuzz");
    exit(NORCFILE_EXIT);
  }
  switch(lseek(rcf,0,SEEK_END)){
  case 0: // no file existed
    // 1) prompt the user to see if we may report results
    report=0;
    printf("To make it possible to better coordinate the debugging of Linux, can fuzz \n"
	   "report results back to the master fuzz site using email? EVERY EFFORT WILL BE\n"
	   "MADE TO KEEP INFORMATION ANONYMOUS. Your email address will not be recorded or\n"
	   "disclosed to anyone including the fuzz developers. The email will contain only\nthe following information:\n"
	   "\t1. The operating system you are running.\n"
	   "\t2. The distribution that you are running.\n"
	   "\t3. Whether fuzz was able to automatically determine the distribution\n"
	   "\t   you were running.\n"	   
	   "\t4. The version of fuzz you are running.\n"
	   "\t5. The command line options passed to fuzz.\n"
	   "\t6. The name of the program being tested.\n"
	   "\t7. The version of the program being tested.\n"
	   "\t8. The dynamic libraries that it is linked against.\n"
	   "\t9. The results of the test.\n"
	   "If the program is part of an RPM or dpkg based distribuion:\n"
	   "\t10. The package that the program belogs to.\n"
	   "In the case where a program fails the fuzz test, then:\n"
	   "\t11. The data set which caused it to fail.\n");

    
    while(!report){
      printf("Allow fuzz to report findings? (Y/n) ");
      switch(getchar()){
      case '\n':
      case 'y':
      case 'Y':
	report=1;
	break;
      case 'n':
      case 'N':
	report=2;
	break;
      default:
	printf("\007\nDidn't understand that. ");
      }
    }
    // 2) figure out the distribution or ask
    /* Distribution:
       R read error on reading /etc/redhat-release
       S read error on reading /etc/debian_version
       K known redhat release
       D known debian release
       N unknown RPM based release
       O unknown dbkg based release
       U unknown distribution
       C known rpm based release changed by user
       B known dpkg based release changed by user
    */
    if(report!=1){
      report=0;
      if(write(rcf,"report=0\n",9)==-1){
	fprintf(stderr,"Can't write to .fuzzrc\n");
	perror("fuzz");
	exit(NORCFILE_EXIT);
      }
      if(write(rcf,"sendmail=0\n",9)==-1){
       fprintf(stderr,"Can't write to .fuzzrc\n");
       perror("fuzz");
       exit(NORCFILE_EXIT);
      }
    }else{
      if(write(rcf,"report=1\n",9)==-1){
	fprintf(stderr,"Can't write to .fuzzrc\n");
	perror("fuzz");
	exit(NORCFILE_EXIT);	
      }
      if(stat("/bin/rpm",&statbuf)!=-1){
	// rpm based release
	if((fd=open("/etc/redhat-release",O_RDONLY))!=-1){
	  if((tmp=read(fd,distribution+1,MAXPATH-1))==-1){
	    strcpy(distribution,"Runknown RPM based release");
	  }else{
	    char *cur;
	    distribution[0]='K';
	    chomp(distribution);
	  }
	  close(fd);
	}else{
	  strcpy(distribution,"Nunknown RPM based release");
	}
      }else if(stat("/bin/dpkg",&statbuf)==-1){
        if((fd=open("/etc/debian_version",O_RDONLY))!=-1){
          if((tmp=read(fd,distribution+1,MAXPATH-1))==-1){
            strcpy(distribution,"Sunknown dpkg based release");
          }else{
            char *cur;
            distribution[0]='D';
            chomp(distribution);
          }
          close(fd);
        }else{
          strcpy(distribution,"Ounknown dpkg based release");
        }
      }else{
	distribution[0]='U';
	distribution[1]='?';
      }
      snprintf(strbuf,MAXPATH-1,"\n\nDistribution? [%s] ",distribution+1);
      tmpbuf=readline(strbuf);
      if(tmpbuf!=NULL){
	if(tmpbuf[0]!=0){
	  if(distribution[0]='K' && strncmp(distribution+1,tmpbuf,MAXPATH))
            distribution[0]='C';
	  if(distribution[0]='D' && strncmp(distribution+1,tmpbuf,MAXPATH))
            distribution[0]='B';
	  strncpy(distribution+1,tmpbuf,MAXPATH-2);
	}
	free(tmpbuf);
      }
      tmp=snprintf(strbuf,MAXPATH-1,"dist_certainty=%c\ndist=%s\n",
		   distribution[0],distribution+1);
      if(write(rcf,strbuf,tmp)==-1){
	fprintf(stderr,"Can't write to .fuzzrc\n");
	perror("fuzz");
	exit(NORCFILE_EXIT);
      }
      // 3) Try to figure out what sendmail they can use
      if(stat(sendmail="/usr/lib/sendmail",&statbuf)==-1 &&
	 stat(sendmail="/usr/sbin/sendmail",&statbuf)==-1){
	do{
	  sendmail=readline("Where is sendmail? ");
	}while(stat(sendmail,&statbuf) && printf("Didn't understand that. "));
      }
      tmp=snprintf(strbuf,MAXPATH-1,"sendmail=%s\n",sendmail);
      if(write(rcf,strbuf,tmp)==-1){
	fprintf(stderr,"Can't write to .fuzzrc\n");
	perror("fuzz");
	exit(NORCFILE_EXIT);
      }
    }
    close(rcf);
    break;
  case -1: // bad things
    perror("fuzz");
    exit(NORCFILE_EXIT);
    break;
  default:
    // read the stuff from the file
    // hokey processing scheme
    lseek(rcf,0,SEEK_SET);
    if(read(rcf,strbuf,MAXPATH)==-1){
      fprintf(stderr,"Read failed on .fuzzrc\n");
      perror("fuzz");
      exit(NORCFILE_EXIT);
    }
    for(tmpbuf=strtok(strbuf,"\n");tmpbuf!=NULL;tmpbuf=strtok(NULL,"\n")){
      if(!strncmp(tmpbuf,"report=",7)){
	if(sscanf(tmpbuf,"report=%d",&report)!=1){
	  fprintf(stderr,"Can't read report from .fuzzrc\n");
	  exit(NORCFILE_EXIT);
	}else if ( report == 0 ) 
	  break;
      }else if(!strncmp(tmpbuf,"dist_certainty=",15)){
	if(sscanf(tmpbuf,"dist_certainty=%c",distribution)!=1){
	  fprintf(stderr,"Can't read dist_certainty from .fuzzrc\n");
	  exit(NORCFILE_EXIT);
	}
      }else if(!strncmp(tmpbuf,"dist=",5)){
	strcpy(distribution+1,tmpbuf+5);
      }else if(!strncmp(tmpbuf,"sendmail=",9)){
	if(sscanf(tmpbuf,"sendmail=%s",sendmail)!=1){
	  fprintf(stderr,"Can't read sendmail from .fuzzrc\n");
	  exit(NORCFILE_EXIT);
	}
      }else{
	fprintf(stderr,"Corrupt .fuzzrc\n");
	exit(NORCFILE_EXIT);
      }
    }
    if(report){
      if((*distribution!='R' && *distribution!='K' && *distribution!='N' && 
	  *distribution!='D' && *distribution!='U' && *distribution!='C') || 
	 strlen(distribution+1)==0 || strlen(sendmail)==0){
	fprintf(stderr,"Not all required variables are present in .fuzzrc\n"); 
	exit(NORCFILE_EXIT);
      }
    }
  } // end of case where we get info from rcfile or from user
  return report;
}

void send_report(char result, char report, char *sendmail, char *distribution){
  if(report){
    FILE *mail,*version;
    int i;
    char strbuf[MAXPATH],*tmp;
    time_t tm;

    if(dontask)
      tmp=strdup("NULL");
    else
      tmp=readline("Version of program tested? ");

    fputs("Sending report",stdout);
    fflush(stdout);
    snprintf(strbuf,MAXPATH-1,"%s %s %s",sendmail,SENDMAILARGS,DESTADDR);
    
    if((mail=popen(strbuf,"w"))==NULL){
      fprintf(stderr,"can't send report\n");
      exit(NOREPORT_EXIT);
    }

    time(&tm);
    fprintf(mail,"From: fuzz program\nTo: %s\n"
	    "Subject: results\nDate: %s\n",DESTADDR,ctime(&tm));

    // item 1 the OS
    fputs(" 1",stdout);
    fflush(stdout);
    if((version=popen("uname -a","r"))==NULL){
      fprintf(stderr,"Can't figure out system type with uname -a.\n");
      perror("fuzz");
      exit(NOREPORT_EXIT);
    }
    fgets(strbuf,MAXPATH-1,version);
    //consume remaining data
    while(!feof(version)){
      fgets(strbuf,MAXPATH-1,version);
    }
    pclose(version);
    fprintf(mail,"os=%s",strbuf);

    // item 2-4 the distribution and version of fuzz
    fputs(" 2 3 4",stdout);
    fflush(stdout);
    fprintf(mail,"distribution=%s\nfuzz_version=%s\n",distribution,VERSION);

    // item 5 the command line options passed to fuzz
    fputs(" 5",stdout);
    fflush(stdout);
    fprintf(mail,"num_args=%d\n",g_argc);
    for(i=0;i<g_argc;i++){
      fprintf(mail,"arg[%d]=\"%s\"\n",i,g_argv[i]);
    }
    
    // item 6-7 the program that is being tested
    fputs(" 6 7",stdout);
    fflush(stdout);
    fprintf(mail,"program_name=%s\nprogram_version=%s\n",progname,tmp);
    free(tmp);

    // item 8 the libraries that the program is linked against
    fputs(" 8",stdout);
    fflush(stdout);
    snprintf(strbuf,MAXPATH-1,"ldd %s",progname);
    if((version=popen(strbuf,"r"))==NULL){
      fprintf(stderr,"Can't run ldd.\n");
      perror("fuzz");
      exit(NOREPORT_EXIT);
    }
    for(i=0;!feof(version);i++){
      char *cur;
      struct stat statbuf;

      fgets(strbuf,MAXPATH-1,version);
      if(!strstr(strbuf,"not a dynamic executable"))
	break;
      if(feof(version))
	break;
      if((cur=strstr(strbuf," => "))==NULL){
	fprintf(stderr,"Error processing ldd output -- can't find =>\n");
	exit(NOREPORT_EXIT);
      }
      cur+=4;
      if(strtok(cur," ")==NULL){
	fprintf(stderr,"Error processing ldd output -- can't find space\n");
	exit(NOREPORT_EXIT);
      }

      if(lstat(cur,&statbuf)==-1){
	fprintf(stderr,"Can't stat library %s.\n",cur);
	exit(NOREPORT_EXIT);
      }
      if(S_ISLNK(statbuf.st_mode)){
	char tmpbuf[MAXPATH];
	memset(tmpbuf,0,MAXPATH);
	if(readlink(cur,tmpbuf,MAXPATH-1)==-1){
	  fprintf(stderr,"Can't readlink library %s\n",cur);
	  perror("fuzz");
	  exit(NOREPORT_EXIT);
	}
	fprintf(mail,"library[%d]=%s\n",i,tmpbuf);
      }else{
	fprintf(mail,"library[%d]=%s\n",i,cur);
      }
    }
    pclose(version);

    // item 9 the results of the test
    fputs(" 9",stdout);
    fflush(stdout);
    fprintf(mail,"results=%s\n", result==RESULT_PASSED?"pass":"fail");

    // item 10 the packaging info
    fputs(" 10",stdout);
    fflush(stdout);
    strbuf[0]=0;
    fprintf(mail,"version=");
    if(distribution[0]=='K' || distribution[0]=='N' || distribution[0]=='C' || 
       distribution[0]=='R'){
      snprintf(strbuf,MAXPATH-1,"rpm -qf %s",progname);
      if((version=popen(strbuf,"r"))==NULL){
        fprintf(stderr,"Can't execute %s\n",strbuf);
	fprintf(mail,"UNK1\n.\n");
	exit(NOREPORT_EXIT);
      }
      if(fgets(strbuf,MAXPATH-1,version)==NULL){
	fprintf(stderr,"strange output from rpm -qf\n");
	fprintf(mail,"UNK2\n.\n");
	exit(NOREPORT_EXIT);
      }
      fputs(strbuf,mail);
      //consume remaining data
      while(!feof(version)){
	fgets(strbuf,MAXPATH-1,version);
      }
      pclose(version);
    } else if(distribution[0]=='S' || distribution[0]=='O' || 
              distribution[0]=='B' || distribution[0]=='D'){
      snprintf(strbuf,MAXPATH-1,"dpkg -S %s",progname);
      if((version=popen(strbuf,"r"))==NULL){
        fprintf(stderr,"Can't execute %s\n",strbuf);
	fprintf(mail,"UNK\n.\n");
	exit(NOREPORT_EXIT);
      }
      if(fgets(strbuf,MAXPATH-1,version)==NULL){
        fprintf(stderr,"Can't read dpkg -S output.\n");
        fprintf(mail,"UNK2\n.\n");
        exit(NOREPORT_EXIT);
      }
      //consume remaining data
      while(!feof(version)){
	fgets(strbuf,MAXPATH-1,version);
      }
      pclose(version);
      if(strtok(strbuf,":")==NULL){
        fprintf(stderr,"Strange output from dpkg -S.\n");
        fprintf(mail,"UNK3\n.\n");
        exit(NOREPORT_EXIT);
      }
      tmp=strdup(strbuf);
      fprintf(mail,"%s-",tmp);
      snprintf(strbuf,MAXPATH-1,"dpkg -s %s",tmp);
      free(tmp);
      if((version=popen(strbuf,"r"))==NULL){
        fprintf(stderr,"Can't execute %s\n",strbuf);
	fprintf(mail,"UNK4\n.\n");
	exit(NOREPORT_EXIT);
      }
      while(!feof(version)){
	fgets(strbuf,MAXPATH-1,version);
	if(feof(version))
	  break;
        if(!strncmp(strbuf,"Version: ",9))
          fputs(strbuf+9,mail);
      }
      pclose(version);      
    }

    // item 11 the data set which caused the crash
    fputs(" 11",stdout);
    fflush(stdout);
    if(result==RESULT_PASSED){
      fputs(".\n",mail); // end the mail
      fputs(" done\n",stdout);
      fflush(stdout);
    }else{
      // send all the pertinent data
      int fd,len,i;
      
      fprintf(mail,"data\n");
      if((fd=open(outfilename,O_RDONLY))==-1){
	// this should never happen
	fprintf(stderr,"can't reopen outfile.\n");
	perror("fuzz");
	pclose(mail);
	exit(NOREPORT_EXIT);
      }
      while((len=read(fd,strbuf,MAXPATH))!=-1 && len!=0){
	for(i=0;i<len;i++){
	  fprintf(mail,"%2.2x ",strbuf[i]&0xff);
	  if(i%25==0)
	    fputc('\n',mail);
	}
      }
      close(fd);
      fputs("\nend\n",mail);

      if(max_args){
	fprintf(mail,"args\n");
	
	if((fd=open(argfilename,O_RDONLY))==-1){
	  // this should never happen
	  fprintf(stderr,"can't reopen argfilename.\n");
	  perror("fuzz");
	  pclose(mail);
	  exit(NOREPORT_EXIT);
	}
	while((len=read(fd,strbuf,MAXPATH))!=-1 && len!=0){
	  for(i=0;i<len;i++){
	    fprintf(mail,"%x ",strbuf[i]);
	    if(i%25==0)
	      fputc('\n',mail);
	  }
	}
	close(fd);
	fputs("\nend\n",mail);
      }
      pclose(mail);
      fputs(" done\n",stdout);
      fflush(stdout);
    }
  }
}