source: fedkit/fed-tun.pl @ ae0f69a

axis_examplecompt_changesinfo-opsversion-2.00version-3.01version-3.02
Last change on this file since ae0f69a was 157ac77, checked in by Ted Faber <faber@…>, 15 years ago

duh; avoid embedded newline

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