source: fedkit/fed-tun.pl @ 6679c122

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since 6679c122 was 2aeb39e, checked in by Ted Faber <faber@…>, 17 years ago

demo done

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