source: fedkit/fed-tun.pl @ c8c2c64

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

report correct error when tunnelrouter is missing

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