mkjail.pl 26.8 KB
Newer Older
1
2
3
#!/usr/bin/perl -w
#
# EMULAB-COPYRIGHT
4
# Copyright (c) 2000-2003 University of Utah and the Flux Group.
5
6
# All rights reserved.
#
7
8
# Kernel, jail, netstat, route, ifconfig, ipfw, header files.
# 
9
10
11
12
13
use English;
use Getopt::Std;
use Fcntl;
use IO::Handle;
use Socket;
14
use Fcntl ':flock';
15

16
17
18
# Drag in path stuff so we can find emulab stuff. Also untaints path.
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }

19
use libsetup qw(JailedMounts REMOTE LOCALROOTFS TMPASSDB TMGROUPDB);
20

21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Questions:
#
# * Whats the hostname for the jail? Perhaps vnodename.emulab.net
# * What should /etc/resolv.conf look like?
# 

#
# Create a jailed environment. There are some stub files stored in
# /etc/jail that copied into the jail.
#
sub usage()
{
34
    print("Usage: mkjail.pl [-V] [-s] [-i <ipaddr>] [-p <pid>] ".
35
	  "[-h <hostname>] <vnodeid>\n");
36
37
    exit(-1);
}
38
my  $optlist = "Vi:p:e:sh:";
39
40
41
42
43
44
45

#
# Only real root can run this script.
#
if ($UID) {
    die("Must be root to run this script!\n");
}
46
system("sysctl jail.set_hostname_allowed=0 >/dev/null 2>&1");
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

#
# Catch ^C and exit with error. 
#
my $leaveme = 0;
sub handler ($) {
    my ($signame) = @_;
    
    $SIG{INT}  = 'IGNORE';
    $SIG{USR1} = 'IGNORE';
    $SIG{TERM} = 'IGNORE';
    $SIG{HUP}  = 'IGNORE';

    if ($signame eq 'USR1') {
	$leaveme = 1;
    }
    fatal("Caught a SIG${signame}! Killing the jail ...");
}
$SIG{INT}  = \&handler;
$SIG{USR1} = \&handler;
$SIG{HUP}  = \&handler;
$SIG{TERM} = 'IGNORE';

#
# Turn off line buffering on output
#
STDOUT->autoflush(1);
STDERR->autoflush(1);

76
77
78
79
# XXX
my $JAILCNET	   = "172.16.0.0";
my $JAILCNETMASK   = "255.240.0.0";

80
81
82
83
#
# Locals
#
my $JAILPATH	= "/var/emulab/jails";
84
my $ETCJAIL     = "/etc/jail";
85
my $LOCALFS	= LOCALROOTFS();
86
87
88
my $LOCALMNTPNT = "/local";
my $TMCC	= "$BINDIR/tmcc";
my $JAILCONFIG  = "jailconfig";
89
my @ROOTCPDIRS	= ("etc", "root");
90
91
92
my @ROOTMKDIRS  = ("dev", "tmp", "var", "usr", "proc", "users", 
		   "bin", "sbin", "home", $LOCALMNTPNT);
my @ROOTMNTDIRS = ("bin", "sbin", "usr");
93
my @EMUVARDIRS	= ("logs", "db", "jails", "boot", "lock");
94
my $VNFILESECT  = 64 * ((1024 * 1024) / 512); # 64MB in 512b sectors.
95
my $MAXVNDEVS	= 100;
96
my $IP;
97
98
my $IPALIAS;
my $IPMASK;
99
my $PID;
100
my $jailhostname;
101
102
103
104
my $debug	= 1;
my $cleaning	= 0;
my $vndevice;
my @mntpoints   = ();
105
my $nfsmounts = 0;
106
107
108
my $jailpid;
my $tmccpid;
my $interactive = 0;
109
my $USEVCNETROUTES = 0;
110
111
112

# This stuff is passed from tmcd, which we parse into a config string
# and an option set.
113
my %jailconfig  = ();
114
my $jailoptions = "";
115
my $sshdport    = 50000;	# Bogus default, good for testing.
116
my $routetabid;			# Default to main routing table.
117
my $jailflags   = 0;
118
119
120
my @jailips     = ();		# List of jail IPs (for routing table).
my $JAIL_DEVMEM = 0x01;		# We need to know if these options given.
my $JAIL_ROUTING= 0x02;
121
122
123
124
125
126
127
128
129
130
131
132

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}
if (@ARGV != 1) {
    usage();
}
133
my $vnodeid = $ARGV[0];
134
135
136
137

#
# Untaint the arguments.
#
138
139
140
if ($vnodeid =~ /^([-\w\/\.]+)$/) {
    $vnodeid = $1;
    $jailhostname = $1;
141
142
}
else {
143
    die("Tainted argument $vnodeid!\n");
144
145
146
147
148
149
}

if (defined($options{'s'})) {
    $interactive = 1;
}

150
151
152
153
if (defined($options{'V'})) {
    $USEVCNETROUTES = 1;
}

154
155
156
157
158
159
160
161
162
163
164
165
166
167
#
# Get the parent IP.
# 
my $hostname = `hostname`;
my $hostip;

# Untaint and strip newline.
if ($hostname =~ /^([-\w\.]+)$/) {
    $hostname = $1;

    my (undef,undef,undef,undef,@ipaddrs) = gethostbyname($hostname);
    $hostip = inet_ntoa($ipaddrs[0]);
}

168
#
169
170
# If no IP, then it defaults to our hostname's IP, *if* none is provided
# by the jail configuration file. That check is later. 
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# 
if (defined($options{'i'})) {
    $IP = $options{'i'};

    if ($IP =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/) {
	$IP = $1;
    }
    else {
	die("Tainted argument $IP!\n");
    }
}

if (defined($options{'p'})) {
    $PID = $options{'p'};

    if ($PID =~ /^([-\@\w]+)$/) {
	$PID = $1;
    }
    else {
	die("Tainted argument $PID.");
    }
}

194
195
196
197
198
199
200
201
202
203
204
if (defined($options{'h'})) {
    $jailhostname = $options{'h'};

    if ($jailhostname =~ /^([-\w\.]+)$/) {
	$jailhostname = $1;
    }
    else {
	die("Tainted argument $jailhostname.");
    }
}

205
#
206
# In most cases, the $vnodeid directory will have been created by the caller,
207
208
# and a config file possibly dropped in.
# When debugging, we have to create it here. 
209
210
211
212
# 
chdir($JAILPATH) or
    die("Could not chdir to $JAILPATH: $!\n");

213
214
215
if (! -e $vnodeid) {
    mkdir($vnodeid, 0770) or
	fatal("Could not mkdir $vnodeid in $JAILPATH: $!");
216
}
217
else {
218
    getjailconfig("$JAILPATH/$vnodeid");
219
220
}

221
222
223
my $phys_cnet_if = `control_interface`;
chomp($phys_cnet_if);

224
225
226
227
#
# See if special options supported, and if so setup args as directed.
#
setjailoptions();
228

229
230
231
232
233
234
235
236
237
238
#
# If no IP set in the jail config, then use hostip.
#
if (!defined($IP)) {
    $IP = $hostip;
}

print("Setting up jail for $vnodeid using $IP\n")
    if ($debug);

239
240
241
#
# Create the "disk";
#
242
if (-e "$vnodeid/root") {
243
244
245
    #
    # Try to pick up where we left off.
    # 
246
    restorerootfs("$JAILPATH/$vnodeid");
247
248
249
250
251
}
else {
    #
    # Create the root filesystem.
    #
252
    mkrootfs("$JAILPATH/$vnodeid");
253
254
}

255
256
#
# If the jail has its own IP, must insert the control network alias.
257
258
# We use a 255.255.255.255 netmask since there might be multiple
# virtual nodes from the same subnet on this node. 
259
260
#
if (defined($IPALIAS)) {
261
    setcnethostalias($IPALIAS);
262
263
264
265
266
267
268
269
270
}

#
# Set up jail interfaces. We pass it the rtabid as well, and the script
# does all the right stuff. 
#
mysystem("ifsetup -i -j $vnodeid ".
	 (($jailflags & $JAIL_ROUTING) ? "-r $routetabid" : ""));

271
272
273
274
#
# Start the tmcc proxy. This path will be valid in both the outer
# environment and in the jail!
#
275
startproxy("$JAILPATH/$vnodeid");
276
277
278
279
280
281
282
283
284
285
286
287
288
289

#
# Start the jail. We do it in a child so we can send a signal to the
# jailed process to force it to shutdown. The jail has to shut itself
# down.
#
$jailpid = fork();
if ($jailpid) {
    # We do not really care about the exit status of the jail.
    waitpid($jailpid, 0);
    undef($jailpid);
}
else {
    $SIG{TERM} = 'DEFAULT';
290
    $ENV{'TMCCVNODEID'} = $vnodeid;
291

292
293
    my $cmd = "jail $jailoptions $JAILPATH/$vnodeid/root $jailhostname $IP ".
	"/etc/jail/injail -v $vnodeid";
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    if ($interactive) {
	$cmd .= " /bin/csh";
    }
    exec($cmd);
    die("*** $0:\n".
	"    exec failed to start the jail!\n");
}
	 
#
# Once we exit, cleanup the mess.
#
cleanup();
exit(0);

#
# Create a file for a vnode device, vnconfig it, newfs, and then
# mount it on the "root" directory.
#
sub mkrootfs($)
{
    my ($path) = @_;
315
    my $vnsize = $VNFILESECT;
316
317
318
319
320
321
322
323

    chdir($path) or
	fatal("Could not chdir to $path: $!");

    mkdir("root", 0770) or
	fatal("Could not mkdir 'root' in $path: $!");
    
    #
324
    # Lots of zeros. Note we oseek to create a big hole.
325
    # 
326
    mysystem("dd if=/dev/zero of=root.vnode bs=512 oseek=$vnsize count=1");
327
328
329
330
331

    #
    # Find a free vndevice.
    #
    for (my $i = 0; $i < $MAXVNDEVS; $i++) {
332
333
334
335
	# Make sure the dev entries exist!
	mysystem("(cd /dev; ./MAKEDEV vn${i})");
	
	system("vnconfig -c vn${i} root.vnode");
336
337
338
339
340
341
342
	if (! $?) {
	    $vndevice = $i;
	    last;
	}
    }
    fatal("Could not find a free vn device!") 
	if (!defined($vndevice));
343
344
    print("Using vn${vndevice}\n")
 	if ($debug);
345

346
    mysystem("vnconfig -s labels vn${vndevice} root.vnode");
347
348
    mysystem("disklabel -r -w vn${vndevice} auto");
    mysystem("newfs -b 8192 -f 1024 -i 4096 -c 15 /dev/vn${vndevice}c");
349
    mysystem("tunefs -m 2 -o space /dev/vn${vndevice}c");
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
    mysystem("mount /dev/vn${vndevice}c root");
    push(@mntpoints, "$path/root");

    #
    # Okay, copy in the top level directories. 
    #
    foreach my $dir (@ROOTCPDIRS) {
	mysystem("hier -f -FN cp /$dir root/$dir");
    }

    #
    # Make some other directories that are nice to have!
    #
    foreach my $dir (@ROOTMKDIRS) {
	mkdir("root/$dir", 0755) or
	    fatal("Could not mkdir '$dir' in $path/root: $!");
    }

    #
    # Okay, mount some other directories to save space.
    #
    foreach my $dir (@ROOTMNTDIRS) {
372
373
374
375
376
	if ($nfsmounts) {
	    mysystem("mount -r localhost:/$dir $path/root/$dir");
	} else {
	    mysystem("mount -r -t null /$dir $path/root/$dir");
	}
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
	push(@mntpoints, "$path/root/$dir");
    }

    #
    # The proc FS in the jail is per-jail of course.
    # 
    mysystem("mount -t procfs proc $path/root/proc");
    push(@mntpoints, "$path/root/proc");

    #
    # /tmp is special of course
    #
    mysystem("chmod 1777 root/tmp");

    #
    # /dev is also special. It gets a very restricted set of entries.
393
    # Note that we create some BPF devices since they work in our jails.
394
    #
395
396
397
398
399
400
401
402
    my $makedevs = "bpf31";
    if ($jailflags & $JAIL_DEVMEM) {
	$makedevs .= " std pty0";
    }
    else {
	$makedevs .= " jail";
    }
    mysystem("cd $path/root/dev; cp -p /dev/MAKEDEV .; ./MAKEDEV $makedevs");
403
404
405
406

    # Remove some extraneous devices.
    mysystem("cd $path/root/dev; rm -f pci io klog console; ".
	     "ln -sf null console");
407
408
409
410
411
412
413
414
415
416
    
    #
    # Create stub /var and create the necessary log files.
    #
    # NOTE: I stole this little diddy from /etc/rc.diskless2.
    #
    mysystem("mtree -nqdeU -f /etc/mtree/BSD.var.dist ".
	     "-p $path/root/var >/dev/null 2>&1");
    mysystem("mkdir -p $path/root/$path");

417
418
419
420
421
422
423
424
425
426
427
428
429
430
    #
    # Make the emulab directories since they are not in the mtree file.
    #
    if (! -e "$path/root/var/emulab") {
	mkdir("$path/root/var/emulab", 0755) or
	    fatal("Could not mkdir 'emulab' in $path/root/var: $!");
    }
    foreach my $dir (@EMUVARDIRS) {
	if (! -e "$path/root/var/emulab/$dir") {
	    mkdir("$path/root/var/emulab/$dir", 0755) or
		fatal("Could not mkdir 'dir' in $path/root/var/emulab: $!");
	}
    }

431
432
433
434
435
436
437
    #
    # Stash the control net IP if not the same as the host IP
    #
    if ($IP ne $hostip) {
	mysystem("echo $IP >> $path/root/var/emulab/boot/myip");
    }

438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
    #
    # Get a list of all the plain files and create zero length versions
    # in the new var.
    #
    opendir(DIR, "/var/log") or
	fatal("Cannot opendir /var/log: $!");
    my @logs = grep { -f "/var/log/$_" } readdir(DIR);
    closedir(DIR);

    foreach my $log (@logs) {
	mysystem("touch $path/root/var/log/$log");
    }

    #
    # Now a bunch of stuff to set up a nice environment in the jail.
    #
454
455
456
    mysystem("cp -p $ETCJAIL/rc.conf $path/root/etc");
    mysystem("rm -f $path/root/etc/rc.conf.local");
    mysystem("cp -p $ETCJAIL/rc.local $path/root/etc");
457
    mysystem("cp -p $ETCJAIL/crontab $path/root/etc");
458
    mysystem("cp /dev/null $path/root/etc/fstab");
459
    mysystem("ln -s /usr/compat $path/root/compat");
460
461
462
463
464
465

    # No X11 forwarding. 
    mysystem("cat $path/root/etc/ssh/sshd_config | ".
	     "sed -e 's/^X11Forwarding.*yes/X11Forwarding no/' > ".
	     "$path/root/tmp/sshd_foo");
    mysystem("cp -f $path/root/tmp/sshd_foo $path/root/etc/ssh/sshd_config");
466
467
468
469
470
471
472
473
474
475
    
    # Port/Address for sshd.
    if ($IP ne $hostip) {
	mysystem("echo 'ListenAddress $IP' >> ".
		 "$path/root/etc/ssh/sshd_config");
    }
    else {
	mysystem("echo 'sshd_flags=\"\$sshd_flags -p $sshdport\"' >> ".
		 "$path/root/etc/rc.conf");
    }
476
477
478
479
480
481

    # In the jail, 127.0.0.1 refers to the jail, but we want to use the
    # nameserver running *outside* the jail.
    mysystem("cat /etc/resolv.conf | ".
	     "sed -e 's/127\.0\.0\.1/$hostip/' > ".
	     "$path/root/etc/resolv.conf");
482

483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
    #
    # Password/group file stuff. If remote the jail picks them up. Locally
    # we start with current set of accounts on the physnode, since this is
    # more efficient (less tmcd work), and besides, the physnode starts with
    # exactly the same accounts.
    #
    if (REMOTE()) {
	mysystem("cp -p $ETCJAIL/group $path/root/etc");
	mysystem("cp -p $ETCJAIL/master.passwd $path/root/etc");
	mysystem("pwd_mkdb -p -d $path/root/etc $path/root/etc/master.passwd");
    }
    else {
	mysystem("cp -p /etc/group $path/root/etc");
	mysystem("cp -p /etc/master.passwd $path/root/etc");
	mysystem("pwd_mkdb -p -d $path/root/etc $path/root/etc/master.passwd");
	mysystem("cp -p " . TMPASSDB() . ".db $path/root/$DBDIR");
	mysystem("cp -p " . TMGROUPDB() . ".db $path/root/$DBDIR");
    }
    
502
503
    #
    # If the jail gets its own routing table, must arrange for it to
504
    # be populated with some extras when it boots up.
505
506
    # 
    if ($jailflags & $JAIL_ROUTING) {
507
	addroutestorc("$path/root/etc/rc.conf.routes");
508
    }
509

510
511
512
513
    #
    # Give the jail an NFS mount of the local project directory. This one
    # is read-write.
    #
514
515
    if (defined($PID) && -e $LOCALFS && -e "$LOCALFS/$PID") {
	mysystem("mkdir -p $path/root/$LOCALMNTPNT/$PID");
516
517
518
519
520
521
522
	if ($nfsmounts) {
	    mysystem("mount localhost:$LOCALFS/$PID ".
		     "      $path/root/$LOCALMNTPNT/$PID");
	} else {
	    mysystem("mount -t null $LOCALFS/$PID ".
		     "      $path/root/$LOCALMNTPNT/$PID");
	}
523
	push(@mntpoints, "$path/root/$LOCALMNTPNT/$PID");
524

525
	mysystem("ln -s $LOCALMNTPNT/$PID/$vnodeid $path/root/opt");
526
527
528
    }
    else {
	mkdir("$path/root/opt", 0775);
529
530
    }

531
532
533
534
535
536
    #
    # Ug. Until we have SFS working the way I want it, NFS mount the
    # usual directories inside the jail. This duplicates a lot of mounts,
    # but not sure what to do about that. 
    #
    if (! REMOTE()) {
537
	foreach my $dir ( JailedMounts($vnodeid, "$path/root", $nfsmounts) ) {
538
539
540
541
	    push(@mntpoints, "$path/root/$dir");
	}
    }

542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    cleanmess($path);
    return 0;
}

#
# Restore a jail after a crash.
#
sub restorerootfs($)
{
    my ($path) = @_;

    chdir($path) or
	fatal("Could not chdir to $path: $!");

    #
    # Find a free vndevice.
    #
    for (my $i = 0; $i < $MAXVNDEVS; $i++) {
560
561
562
563
	# Make sure the dev entries exist!
	mysystem("(cd /dev; ./MAKEDEV vn${i})");
	
	system("vnconfig -c vn${i} root.vnode");
564
565
566
567
568
569
570
	if (! $?) {
	    $vndevice = $i;
	    last;
	}
    }
    fatal("Could not find a free vn device!") 
	if (!defined($vndevice));
571
572
    print("Using vn${vndevice}\n")
 	if ($debug);
573

574
    mysystem("vnconfig -s labels vn${vndevice} root.vnode");
575
576
577
578
579
580
581
582
    mysystem("fsck -y /dev/vn${vndevice}c");
    mysystem("mount /dev/vn${vndevice}c root");
    push(@mntpoints, "$path/root");

    #
    # Okay, mount some other directories to save space.
    #
    foreach my $dir (@ROOTMNTDIRS) {
583
584
585
586
587
	if ($nfsmounts) {
	    mysystem("mount -r localhost:/$dir $path/root/$dir");
	} else {
	    mysystem("mount -r -t null /$dir $path/root/$dir");
	}
588
589
590
591
592
593
594
595
596
	push(@mntpoints, "$path/root/$dir");
    }

    #
    # The proc FS in the jail is per-jail of course.
    # 
    mysystem("mount -t procfs proc $path/root/proc");
    push(@mntpoints, "$path/root/proc");

597
598
599
600
601
602
603
    #
    # Must rebuild the routes list cause of swapmodify.
    #
    if ($jailflags & $JAIL_ROUTING) {
	addroutestorc("$path/root/etc/rc.conf.routes");
    }

604
605
606
607
    #
    # Give the jail an NFS mount of the local project directory. This one
    # is read-write.
    #
608
609
    if (defined($PID) && -e $LOCALFS && -e "$LOCALFS/$PID") {
	mysystem("mkdir -p $path/root/$LOCALMNTPNT/$PID");
610
611
612
613
614
615
616
	if ($nfsmounts) {
	    mysystem("mount localhost:$LOCALFS/$PID ".
		     "      $path/root/$LOCALMNTPNT/$PID");
	} else {
	    mysystem("mount -t null $LOCALFS/$PID ".
		     "      $path/root/$LOCALMNTPNT/$PID");
	}
617
	push(@mntpoints, "$path/root/$LOCALMNTPNT/$PID");
618
    }
619
620
621
622
623
624
625

    #
    # Ug. Until we have SFS working the way I want it, NFS mount the
    # usual directories inside the jail. This duplicates a lot of mounts,
    # but not sure what to do about that. 
    #
    if (! REMOTE()) {
626
	foreach my $dir ( JailedMounts($vnodeid, "$path/root", $nfsmounts) ) {
627
628
629
	    push(@mntpoints, "$path/root/$dir");
	}
    }
630
631
632
633
    return 0;
}

#
634
635
# Okay, we clean up some of what is in /etc and /etc/emulab so that the
# jail cannot see that stuff. 
636
637
638
639
640
641
642
643
644
645
646
#
sub cleanmess($) {
    my ($path) = @_;

    #
    # And, some security stuff. We want to remove bits of stuff from the
    # jail that would enable it to talk to tmcd directly. 
    #
    mysystem("rm -f $path/root/etc/emulab.cdkey");
    mysystem("rm -f $path/root/etc/emulab.pkey");

647
    # This is /etc/emulab inside the jail.
648
649
650
651
    mysystem("rm -f  $path/root/$ETCDIR/*.pem");
    mysystem("rm -f  $path/root/$ETCDIR/cvsup.auth");
    mysystem("rm -rf $path/root/$ETCDIR/.cvsup");
    mysystem("rm -f  $path/root/$ETCDIR/master.passwd");
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

    #
    # Copy in emulabman if it exists.
    #
    if (my (undef,undef,undef,undef,undef,undef,undef,$dir) =
	getpwnam("emulabman")) {
	mysystem("hier cp $dir $path/root/home/emulabman");
    }
}

#
# Start the tmcc proxy and insert the unix path into the environment
# for the jail to pick up.
#
sub startproxy($)
{
    my ($dir) = @_;
    my $log   = "$dir/tmcc.log";

    #
    # The point of these paths is so that there is a comman path to
    # the socket both outside and inside the jail. Yuck!
    #
    my $insidepath  = "$dir/tmcc";
    my $outsidepath = "$dir/root/$insidepath";

    $tmccpid = fork();
    if ($tmccpid) {
	#
	# So tmcc will work nicely inside the jail without needing the
	# -l option specified all over.
	#
	$ENV{'TMCCUNIXPATH'} = $insidepath;
	
	select(undef, undef, undef, 0.2);
	return 0;
    }
    $SIG{TERM} = 'DEFAULT';

    # The -o option will cause the proxy to detach but not fork!
    # Eventually change this to standard pid file kill.
693
    exec("$TMCC -d -x $outsidepath -n $vnodeid -o $log");
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
    die("Exec of $TMCC failed! $!\n");
}

#
# Cleanup at exit.
#
sub cleanup()
{
    if ($cleaning) {
	die("*** $0:\n".
	    "    Oops, already cleaning!\n");
    }
    $cleaning = 1;
    
    #
    # Note that the unmounts will fail unless all the processes inside
    # the jail exit!
    # 
    if (defined($tmccpid)) {
	kill('TERM', $tmccpid);
	waitpid($tmccpid, 0);
    }

    if (defined($jailpid)) {
718
	kill('USR1', $jailpid);
719
720
721
	waitpid($jailpid, 0);
    }

722
723
724
725
726
    # Clean up interfaces we might have setup
    system("ifsetup -u -j $vnodeid");

    # If the jail has its own IP, clean the alias.
    if (defined($IPALIAS)) {
727
	clearcnethostalias($IPALIAS);
728
729
    }

730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
    while (@mntpoints) {
	my $mntpoint = pop(@mntpoints);

	# If the umounts fail, we do want to continue. Dangerous!
	system("umount $mntpoint");
	if ($?) {
	    # Avoid recursive calls to cleanup; do not use fatal.
	    die("*** $0:\n".
		"    umount '$mntpoint' failed: $!\n");
	}
    }
    if (defined($vndevice)) {
	system("vnconfig -u vn${vndevice}");
    }
    if (!$leaveme) {
745
746
747
        #
        # Ug, with NFS mounts inside the jail, we need to be really careful.
        #
748
749
	if (-d "$JAILPATH/$vnodeid/root" &&
	    !rmdir("$JAILPATH/$vnodeid/root")) {
750
	    die("*** $0:\n".
751
		"    $JAILPATH/$vnodeid/root is not empty! This is bad!\n");
752
	}
753
	system("rm -rf $JAILPATH/$vnodeid");
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
    }
}

#
# Print error and exit.
#
sub fatal($)
{
    my ($msg) = @_;

    cleanup();
    die("*** $0:\n".
	"    $msg\n");
}

#
# Run a command string, redirecting output to a logfile.
#
sub mysystem($)
{
    my ($command) = @_;

    system($command);
    if ($?) {
	fatal("Command failed: $? - $command");
    }
}
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

#
# Read in the jail config file. 
#
sub getjailconfig($)
{
    my ($path) = @_;

    $path .= "/$JAILCONFIG";

    if (! -e $path) {
	return 0;
    }
    
    if (! open(CONFIG, $path)) {
	print("$path could not be opened for reading: $!\n");
	return -1;
    }
    while (<CONFIG>) {
	if ($_ =~ /^(.*)="(.+)"$/ ||
	    $_ =~ /^(.*)=(.+)$/) {
	    $jailconfig{$1} = $2;
	}
    }
    close(CONFIG);
    return 0;
}

#
# See if special jail opts supported.
#
sub setjailoptions() {
813
814
    my $portrange;
    
815
816
817
818
819
820
821
    #
    # Do this all the time, so that we can figure out the sshd port.
    # 
    foreach my $key (keys(%jailconfig)) {
	my $val = $jailconfig{$key};

        SWITCH: for ($key) {
822
823
824
825
826
827
828
829
830
831
832
833
	    /^JAILIP$/ && do {
		if ($val =~ /([\d\.]+),([\d\.]+)/) {
		    # Set the jail IP, but do not override one on the 
		    # command line.
		    if (!defined($IP)) {
			$IP      = $1;
			$IPALIAS = $1;
			$IPMASK  = $2;
		    }
		}
		last SWITCH;
	    };
834
835
	    /^PORTRANGE$/ && do {
		if ($val =~ /(\d+),(\d+)/) {
836
		    $portrange = "$1:$2";
837
838
839
840
841
		}
		last SWITCH;
	    };
	    /^SSHDPORT$/ && do {
		if ($val =~ /(\d+)/) {
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
		    $sshdport     = $1;
		}
		last SWITCH;
	    };
	    /^SYSVIPC$/ && do {
		if ($val) {
		    $jailoptions .= " -o sysvipc";
		}
		else {
		    $jailoptions .= " -o nosysvipc";
		}
		last SWITCH;
	    };
	    /^INETRAW$/ && do {
		if ($val) {
		    $jailoptions .= " -o inetraw";
		}
		else {
		    $jailoptions .= " -o noinetraw";
		}
		last SWITCH;
	    };
	    /^BPFRO$/ && do {
		if ($val) {
		    $jailoptions .= " -o bpfro";
		}
		else {
		    $jailoptions .= " -o nobpfro";
		}
		last SWITCH;
	    };
873
874
875
876
877
878
879
880
881
882
883
	    /^INADDRANY$/ && do {
		if ($val) {
		    $jailoptions .= " -o inaddrany";
		}
		else {
		    $jailoptions .= " -o noinaddrany";
		}
		last SWITCH;
	    };
	    /^ROUTING$/ && do {
		if ($val) {
884
		    $jailoptions .= " -o routing -i 127.0.0.1 ";
885
886
887
888

		    $jailflags |= $JAIL_ROUTING;
		    #
		    # If the jail gets routing privs, then it must get
889
		    # its own routing table. 
890
891
892
893
894
895
896
897
898
899
		    #
		    $routetabid   = getnextrtabid();
		    $jailoptions .= " -r $routetabid";
		}
		last SWITCH;
	    };
	    /^DEVMEM$/ && do {
		$jailflags |= $JAIL_DEVMEM;
		last SWITCH;
	    };
Leigh B. Stoller's avatar
Leigh B. Stoller committed
900
 	    /^IPADDRS$/ && do {
901
902
903
904
905
906
		# Comma separated list of IPs
		my @iplist = split(",", $val);

		foreach my $ip (@iplist) {
		    if ($ip =~ /(\d+\.\d+\.\d+\.\d+)/) {
			$jailoptions .= " -i $1";
907
			push(@jailips, $1);
908
909
910
911
		    }
		}
 		last SWITCH;
 	    };
912
913
	}
    }
914
915
916
917
    #
    # If there is no IP for the jail, must restrict the port range of
    # it. Otherwise it has it own IP, and there is no need to.
    # 
918
919
920
921
922
923
924
925
926
    if (! defined($IPALIAS)) {
	if (defined($portrange)) {
	    $jailoptions .= " -p $portrange";
	}
	else {
	    fatal("Must have a port range if jail ip equals host ip!");
	}
	print("SSHD port is $sshdport\n");
    }
927
928
929

    system("sysctl jail.inetraw_allowed=1 >/dev/null 2>&1");
    system("sysctl jail.bpf_allowed=1 >/dev/null 2>&1");
930
931
932
933
    system("sysctl jail.inaddrany_allowed=1 >/dev/null 2>&1");
    system("sysctl jail.multiip_allowed=1 >/dev/null 2>&1");
    system("sysctl net.link.ether.inet.useloopback=0 >/dev/null 2>&1");

934
935
936
    if ($?) {
	print("Special jail options are NOT supported!\n");
	$jailoptions = "";
937
	$jailflags   = 0;
938
939
940
	return 0;
    }
    print("Special jail options are supported: '$jailoptions'\n");
941
942
943
944
945

    return 0;
}

#
946
947
# Append a list of static routes to the rc.conf file. This basically
# augments the list of static routes that tmcd tells us to install. 
948
949
950
951
952
953
#
sub addroutestorc($rc)
{
    my ($rc)   = @_;
    my $count  = 0;

954
    open(RC, ">$rc") or
955
956
	fatal("Could not open $rc to append static routes");

957
    my $routerip  = getcnetrouter();
958
    my $hostip    = `cat $BOOTDIR/myip`;
959
960
    chomp($hostip);

961
962
963
964
    #
    # First the set of routes that all jails get. 
    # 
    print RC "static_routes=\"default lo0 host\"\n";
965
    print RC "route_default=\"default $routerip\"\n";
966
967
    print RC "route_lo0=\"localhost -interface lo0\"\n";
    print RC "route_host=\"$hostip localhost\"\n";
968
    if ($IP ne $hostip) {
969
970
971
972
973
	# Setup a route for all jails on this node, to the loopback.
	print RC "static_routes=\"\$static_routes jailnet\"\n";
	print RC "route_jailnet=\"-net $IP -interface lo0 255.255.255.0\"\n";

	print RC "static_routes=\"\$static_routes privnet\"\n";
974
	print RC "route_privnet=\"-net $IP -interface $phys_cnet_if $IPMASK\"\n";
975
    }
976
977

    #
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    # XXX I don't think this is really a virtual control net issue, but
    # rather a gated issue.  However, this is the only hook I have right now.
    #
    # This just in!  It looks like whatever the gated problem was, it went
    # away after fixing numerous other bugs.  But I'll leave the conditional
    # here for a little while just in case...
    #
    if (1 || !$USEVCNETROUTES) {
	#
	# Now a list of routes for each of the IPs the jail has access
	# to. The idea here is to override the interface route such that
	# traffic to the local interface goes through lo0 instead. This
	# avoids going through traffic shaping when, say, pinging your own
	# interface!
	# 
	foreach my $ip (@jailips) {
	    print RC "static_routes=\"ip${count} \$static_routes\"\n";
	    print RC "route_ip${count}=\"$ip -interface lo0\"\n";
	    $count++;
	}
998
999
    }
    close(RC);
1000
    return 0;