source: fedkit/fed-tun.pl @ 1b57352

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since 1b57352 was 0ea5050, checked in by Ted Faber <faber@…>, 16 years ago

Simplify the filehandle in the open call, so real data is read.

  • Property mode set to 100755
File size: 13.9 KB
RevLine 
[c9f5490]1#!/usr/bin/perl -w
2
3# Kevin Lahey, lahey@isi.edu
4# July 11, 2007
5
6# Set up ssh tunnel infrastructure for federation:
7#
[a098fab]8# * Parse the configuration file provided.
9#
10# * Figure out whether we're the initiator or the reciever;  if we're
11#   the receiver, we just need to set up ssh keys and exit.
12#
13# * Pick out the experimental interface, remove the IP address
[c9f5490]14#
[a098fab]15# * Create a layer 2 ssh tunnel, set up bridging, and hang loose.
[fd7a59b]16#
[c9f5490]17
18use strict;
19use Getopt::Std;
20use POSIX qw(strftime);
21use Sys::Hostname;
[a098fab]22use IO::File;
[7a8d667]23use File::Copy;
[c9f5490]24
[d501c38]25my $IFCONFIG = "/sbin/ifconfig";
[c9f5490]26my $TMCC = "/usr/local/etc/emulab/tmcc";
[01073f7]27# If a special version of ssh is required, it will be installed in
28# /usr/local/bin/ssh.  Otherwise use the usual one.
29my $SSH = -x "/usr/local/bin/ssh" ? "/usr/local/bin/ssh" : "/usr/bin/ssh";
[a098fab]30my $NC = "/usr/bin/nc";
31my $SSH_PORT = 22;
[fd7a59b]32my $ROUTE_GET = "/sbin/route get";  # XXX:  works on FreeBSD, but should
33                                    #       should be 'ip route get' for Linux
[7a8d667]34my $sshd_config = "/etc/ssh/sshd_config";    # Probably should be a param
[c9f5490]35
[f64fa81]36# Ports that are forwarded between testbeds
37my $TMCD_PORT = 7777;
38my $SMBFS_PORT = 139;
39my $PUBSUB_PORT = 16505;
[27b6aea]40my $SEER_PORT = 16606;
[f64fa81]41
[33e3537]42
43my $remote_pubsub_port = $PUBSUB_PORT - 1;  # There will be a local
44                                            # pubsubd running, so we
45                                            # dodge the port on the
46                                            # remote tunnel node.
[01073f7]47die "Cannot exec $SSH" unless -x $SSH;
48
[a098fab]49sub setup_bridging;
50sub setup_tunnel_cfg;
51sub parse_config;
[c9f5490]52
[a098fab]53# Option use is as follows:
54#    -f         filename containing config file
55#    -d         turn on debugging output
56#    -r         remotely invoked
57#               (if remotely invoked the last two args are the tun interface
58#               number and the remote address of the tunnel)
[c9f5490]59
[a098fab]60my $usage = "Usage: fed-tun.pl [-r] [-d] [-f config-filename] [count addr]\n";
[c9f5490]61
[fd7a59b]62my %opts;       # Note that this is used for both getops and the options file
[cd3eceb]63my @expected_opts = qw(active tunnelcfg bossname fsname type
64                       peer pubkeys privkeys);
[a098fab]65my $filename;
66my $remote;
67my $debug = 1;
[c9f5490]68my $count;
69my $addr;
[cd3eceb]70my $active;
71my $type;
72my $tunnelcfg;
[fe53e75]73my @ssh_port_fwds;              # Queue of ssh portforwarders to start.  The
74                                # -L or -R is in here.
[c8c45ee]75my $remote_script_dir;          # location of the other sides fed-tun.pl
[8034579]76my $event_repeater;             # The pathname of the event repeater
77my $remote_config_file;         # Config file for the other side
[c9f5490]78
[7a8d667]79if ($#ARGV != 0 && !getopts('df:rn', \%opts)) {
[c9f5490]80    die "$usage";
81}
82
[a098fab]83if (defined($opts{'d'})) {
84    $debug = 1;
85}
[c9f5490]86
[a098fab]87if (defined($opts{'f'})) {
88    $filename = $opts{'f'};
[c9f5490]89}
90
91if (defined($opts{'r'})) {
92    $remote = 1;
93    die "$usage" if ($#ARGV != 1);
94   
95    $count = pop @ARGV;
96    $addr = pop @ARGV;
97}
98
[a098fab]99die "$usage" if (!defined($remote) && !defined($filename));
[c9f5490]100
[a098fab]101if (defined($filename)) {
102    &parse_config("$filename", \%opts) || 
103        die "Cannot read config file $filename: $!\n";
[c9f5490]104
[cd3eceb]105    foreach my $opt (@expected_opts) {
106        warn "Missing $opt option\n" if (!defined($opts{$opt}));
107    }
108
109    $active = 1 if ($opts{'active'} =~ /true/i);
110    $tunnelcfg = 1 if ($opts{'tunnelcfg'} =~ /true/i);
111    $type = $opts{'type'};
112    $type =~ tr/A-Z/a-z/;
[c8c45ee]113    $remote_script_dir = $opts{'remotescriptdir'} || ".";
[8034579]114    $event_repeater = $opts{'eventrepeater'};
115    $remote_config_file = $opts{'remoteconfigfile'};
116    $remote_config_file = "-f $remote_config_file" if $remote_config_file;
[c9f5490]117
[cd3eceb]118    if (defined($opts{'fsname'})) {
[fe53e75]119        push(@ssh_port_fwds,"-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT");
[cd3eceb]120    }
[c9f5490]121
[cd3eceb]122    if (defined($opts{'bossname'})) {
[fe53e75]123        push(@ssh_port_fwds, "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT");
[33e3537]124    }
125
126    if (defined($opts{'eventservername'})) {
[fe53e75]127        push(@ssh_port_fwds,"-R ". 
128            ":$remote_pubsub_port:$opts{'eventservername'}:$PUBSUB_PORT");
[cd3eceb]129    }
[33e3537]130    if (defined($opts{'remoteeventservername'})) {
[fe53e75]131        push(@ssh_port_fwds,"-L :$remote_pubsub_port:" . 
132            "$opts{'remoteeventservername'}:$PUBSUB_PORT");
[33e3537]133    }
[c9f5490]134
[27b6aea]135    # Forward connections to seer from remote TBs to control in this TB
136    if (defined($opts{'seercontrol'})) {
137        push(@ssh_port_fwds,"-R :$SEER_PORT:$opts{seercontrol}:$SEER_PORT");
138    }
139
[7a8d667]140    # -n just starts the ssh tap tunnel
141    @ssh_port_fwds = () if ($opts{'type'} eq 'experiment' || $opts{'n'});
[c9f5490]142
[fe53e75]143    print "ssh_port_fwds = ", join("\n",@ssh_port_fwds), "\n" if ($debug);
[cd3eceb]144}
[c9f5490]145
[01073f7]146# Both sides need to have GatewayPorts and PermitTunnel set.  Copy the existing
147# sshd_config, making sure GatewayPorts and PermitTunnel are set to yes,
148# replace the original, and restart sshd.
[7a8d667]149my $ports_on = 0;
[01073f7]150my $tunnel_on = 0;
[7a8d667]151
152my $conf = new IO::File($sshd_config) || die "Can't open $sshd_config: $!\n";
153my $new_conf = new IO::File(">/tmp/sshd_config") || 
154    die "Can't open new ssh_config: $!\n";
155
156while(<$conf>) {
157    s/^\s*GatewayPorts.*/GatewayPorts yes/ && do {
158        print $new_conf $_ unless $ports_on++;
159        next;
160    };
[01073f7]161    s/^\s*PermitTunnel.*/PermitTunnel yes/ && do {
162        print $new_conf $_ unless $tunnel_on++;
163        next;
164    };
[7a8d667]165    print $new_conf $_;
166}
167print $new_conf "GatewayPorts yes\n" unless $ports_on;
[01073f7]168print $new_conf "PermitTunnel yes\n" unless $tunnel_on;
[7a8d667]169$conf->close();
170$new_conf->close();
171
172copy("/tmp/sshd_config", $sshd_config) || 
173    die "Cannot replace $sshd_config: $!\n";
174
175system("/etc/rc.d/sshd restart");
176
[a098fab]177# Need these to make the Ethernet tap and bridge to work...
[01073f7]178system("kldload /boot/kernel/bridgestp.ko") 
179    if -r "/boot/kernel/bridgestp.ko";
[a098fab]180system("kldload /boot/kernel/if_bridge.ko");
181system("kldload /boot/kernel/if_tap.ko");
[c9f5490]182
[cd3eceb]183if ($tunnelcfg && !$remote) {
[a098fab]184    # Most Emulab-like testbeds use globally-routable addresses on the
185    # control net;  at DETER, we isolate the control net from the Internet.
186    # On DETER-like testbeds, we need to create special tunneling nodes
187    # with external access.  Set up the external addresses as necessary.
188    &setup_tunnel_cfg(%opts);
[c9f5490]189}
190
191if (!$remote) {
[a098fab]192    system("umask 077 && cp $opts{'privkeys'} /root/.ssh/id_rsa");
193    system("umask 077 && cp $opts{'pubkeys'} /root/.ssh/id_rsa.pub");
194    system("umask 077 && cat $opts{'pubkeys'} >> /root/.ssh/authorized_keys");
195}
[c9f5490]196
[cd3eceb]197if ($active) {
[a098fab]198    # If we're the initiator, open up a separate tunnel to the remote
199    # host for each of the different experiment net interfaces on this
200    # machine.  Execute this startup script on the far end, but with
201    # the -r option to indicate that it's getting invoked remotely and
202    # we should just handle the remote-end tasks.
[c9f5490]203
[a098fab]204    # Set up synchronization, so that the various user machines won't try to
205    # contact boss before the tunnels are set up.  (Thanks jjh!)
[c9f5490]206
[a098fab]207    do {
208        system("$NC -z $opts{'peer'} $SSH_PORT");
209    } until (!$?);
[c9f5490]210
211    # XXX:  Do we need to clear out previously created bridge interfaces?
212
213    my $count = 0;
[a098fab]214    my @SSHCMD;
[c9f5490]215
[d501c38]216    # If we are just setting up a control net connection, just fire up
217    # ssh with the null command, and hang loose.
218
219    if ($type eq "control") {
[fe53e75]220        foreach my $fwd (@ssh_port_fwds) {
221            system("$SSH -N $fwd -Nno \"StrictHostKeyChecking no\" ". 
222                "$opts{'peer'} &"); #or die "Failed to run ssh";
223        }
[d501c38]224
225        exit;
226    }
227
[c9f5490]228    open(IFFILE, "/var/emulab/boot/ifmap") || die "couldn't open ifmap\n";
229    while (<IFFILE>) {
230        my @a = split(' ');
231        my $iface = $a[0];
232        my $addr = $a[1];
233        my $bridge = "bridge" . $count;
234        my $tun = "tap" . $count;
[fe53e75]235        my $cmd;
[c9f5490]236
237        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
238
[a098fab]239        # Note that we're going to fire off an ssh which will never return;
240        # we need the connection to stay up to keep the tunnel up.
241        # In order to check for problems, we open it this way and read
242        # the expected single line of output when the tunnel is connected.
[fe53e75]243        # To make debugging easier and to degrade more gracefully, I've split
244        # these out into multiple processes.
245       
246        foreach my $fwd (@ssh_port_fwds) {
247            $cmd = "$SSH -N $fwd -o \"StrictHostKeyChecking no\" ". 
248                "$opts{'peer'} &";
249
250            print "$cmd\n" if $debug;
251            system("$cmd"); # or die "Failed to run ssh";
252        }
[01073f7]253        # The Tunnel option specifies the level to tunnel at.  Ethernet creates
254        # a tap device rather than a tun device.  Strict host key checking
255        # avoids asking the user to OK a strange host key.
256        $cmd =  "$SSH -w $count:$count -o \"Tunnel ethernet\" " . 
257            "-o \"StrictHostKeyChecking no\" " . 
[fe53e75]258            "$opts{'peer'}  \"$remote_script_dir/fed-tun.pl " . 
259            "$remote_config_file -r $addr $count\" & |";
260
261        print "$cmd\n" if $debug;
[c9f5490]262
[0ea5050]263        open(SSHCMD, $cmd) 
[fe53e75]264           or die "Failed to run ssh";
[c9f5490]265
[0ea5050]266        my $check = <SSHCMD>;  # Make sure something ran...
[d501c38]267        print "Got line [$check] from remote side\n" if ($debug);
[c9f5490]268
[a098fab]269        &setup_bridging($tun, $bridge, $iface, $addr);
[c9f5490]270        $count++;
[fe53e75]271        @ssh_port_fwds = ();  # only do this on the first connection
[c9f5490]272    }
273    close(IFFILE);
[33e3537]274
275    # Start a local event repeater (unless we're missing parameters
276    die "Missing event repeater params (No config file ?)\n"
277        unless $event_repeater && $opts{'remoteexperiment'} && 
278        $opts{'localexperiment'};
279
280    print "Starting event repeater\n" if $debug;
281   
282    print("$event_repeater -M -P $remote_pubsub_port -S localhost " . 
283        "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}\n") 
284        if $debug;
285    # Connect to the forwarded pubsub port on this host to listen to the
286    # other experiment's events, and to the local experiment to forward
287    # events.
288    system("$event_repeater -M -P $remote_pubsub_port -S localhost " . 
289        "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}");
290    warn "Event repeater returned $?\n" if $?;
[a098fab]291} elsif ($remote) {
[fd7a59b]292    # We're on the remote system;  figure out which interface to
293    # tweak, based on the IP address passed in.
[c9f5490]294
295    my $iter = 0;
[fd7a59b]296    my $iface;
[c9f5490]297
[fd7a59b]298    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
299    while (<RTFILE>) {
300        if (/interface: (\w+)/) {
301            $iface = $1;
302        }
[c9f5490]303    }
[fd7a59b]304    close(RTFILE);
305
306    die "Couldn't find interface to use." if (!defined($iface));
307    my $bridge = "bridge" . $count;
308    my $tun = "tap" . $count;
[a098fab]309
[fd7a59b]310    &setup_bridging($tun, $bridge, $iface, $addr);
[a098fab]311    print "Remote connection all set up!\n";  # Trigger other end with output
[8034579]312
313    # If this is the first remote invocation on a control gateway, start the
314    # event repeater.
315
316    if ( $count == 0 && $type ne "experiment" ) {
317        my $remote_pubsub_port = $PUBSUB_PORT - 1;  # There will be a local
318                                                    # pubsubd running, so we
319                                                    # dodge the port on the
320                                                    # remote tunnel node.
321        # Make sure we have the relevant parameters
322        die "Missing event repeater params (No config file ?)\n"
323            unless $event_repeater && $opts{'remoteexperiment'} && 
324            $opts{'localexperiment'};
325
326        print "Starting event repeater\n" if $debug;
327       
328        # Connect to the forwarded pubsub port on this host to listen to the
329        # other experiment's events, and to the local experiment to forward
330        # events.
331        system("$event_repeater -P $remote_pubsub_port -S localhost " . 
332            "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}");
333        warn "Event repeater returned $?\n" if $?;
334    }
[a098fab]335} else {
336    print "inactive end of a connection, finishing" if ($debug);
[c9f5490]337}
338
339print "all done!\n" if ($debug);
340exit;
341
342
343# Set up the bridging for the new stuff...
344
[a098fab]345sub setup_bridging($; $; $; $) {
[c9f5490]346    my ($tun, $bridge, $iface, $addr) = @_;
347
[d501c38]348    print "Waiting to see if new iface $tun is up\n" if ($debug);
349
350    do {
351        sleep 1;
352        system("$IFCONFIG $tun");
353    } until (!$?);
354
[c9f5490]355    print "setting up $bridge with $iface and nuking $addr\n" if ($debug);
356
357    system("ifconfig $bridge create");
358    system("ifconfig $iface delete $addr");
359    system("ifconfig $bridge addm $iface up");
360    system("ifconfig $bridge addm $tun");
361}
[a098fab]362
363# Set up tunnel info for DETER-like testbeds.
364
365sub setup_tunnel_cfg {
366    my (%opts) = @_;
367    my $tunnel_iface = "em0";   # XXX
368    my $tunnel_ip;
369    my $tunnel_mask;
370    my $tunnel_mac;
371    my $tunnel_router;
372
373    print "Opening $TMCC tunnelip\n" if ($debug);
374
375    open(TMCD, "$TMCC tunnelip |") || die "tmcc failed\n";
376    print "Opened $TMCC tunnelip\n" if ($debug);
377    while (<TMCD>) {
378        print "got one line from tmcc\n" if ($debug);
379        print if ($debug);
380        if (/^TUNNELIP=([0-9.]*) TUNNELMASK=([0-9.]*) TUNNELMAC=(\w*) TUNNELROUTER=([0-9.]*)$/) {
381            $tunnel_ip = $1;
382            $tunnel_mask = $2;
383            $tunnel_mac = $3;
384            $tunnel_router = $4;
385        }
386    }
387    close(TMCD);
388
389    die "Unable to determine tunnel node configuration information"
390        if (!defined($tunnel_router));
391
392    print "tunnel options:  ip=$tunnel_ip mask=$tunnel_mask mac=$tunnel_mac router=$tunnel_router\n" if ($debug);
393
394    # Sadly, we ignore the tunnel mac for now -- we should eventually
395    # use it to determine which interface to use, just like the
396    # Emulab startup scripts.
397
398    system("ifconfig $tunnel_iface $tunnel_ip" .
[2aeb39e]399           ($tunnel_mask ? " netmask $tunnel_mask" : "") . " up");
[a098fab]400    warn "configuration of tunnel interface failed" if ($?);
[4abace9]401
402    # Sometimes the insertion of DNS names lags a bit.  Retry this
403    # configuration a few times to let DNS catch up.  Might want to really
404    # check the DNS name before we try this...
405    my $config_succeeded = 0;
406    my $tries = 0;
[2aeb39e]407    my $max_retries = 30;
[4abace9]408
409    do {
410        system("route add $opts{'peer'} $tunnel_router");
411        if ( $? ) {
412            warn "configuration routes via tunnel interface failed";
413            $tries++;
414            sleep(10);
415        }
416        else { $config_succeeded = 1; }
417    } until ( $config_succeeded || $tries > $max_retries );
[a098fab]418
419    print "setup_tunnel_cfg done\n" if ($debug);
420}
421
422# Trick config-file parsing code from Ted Faber:
423
424# Parse the config file.  The format is a colon-separated parameter name
425# followed by the value of that parameter to the end of the line.  This parses
426# that format and puts the parameters into the referenced hash.  Parameter
427# names are mapped to lower case, parameter values are unchanged.  Returns 0 on
428# failure (e.g. file open) and 1 on success.
429sub parse_config {
430    my($file, $href) = @_;
431    my($fh) = new IO::File($file);
432       
433    unless ($fh) {
434        warn "Can't open $file: $!\n";
435        return 0;
436    }
437
438    while (<$fh>) {
439        next if /^\s*#/ || /^\s*$/;     # Skip comments & blanks
440        chomp;
441        /^([^:]+):\s*(.*)/ && do {
442            my($key) = $1; 
443
444            $key =~ tr/A-Z/a-z/;
445            $href->{$key} = $2;
446            next;
447        };
448        warn "Unparasble line in $file: $_\n";
449    }
450    $fh->close();   # It will close when it goes out of scope, but...
451    return 1;
452}
Note: See TracBrowser for help on using the repository browser.