source: fedkit/fed-tun.pl @ e26c240

axis_examplecompt_changesinfo-opsversion-2.00version-3.01version-3.02
Last change on this file since e26c240 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
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}
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}
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
121die "$usage" if (!defined($remote) && !defined($filename));
122
123if (defined($filename)) {
124    &parse_config("$filename", \%opts) || 
125        die "Cannot read config file $filename: $!\n";
126
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/;
135    $remote_script_dir = $opts{'remotescriptdir'} || ".";
136    $event_repeater = $opts{'eventrepeater'};
137    $remote_config_file = $opts{'remoteconfigfile'};
138    $remote_config_file = "-f $remote_config_file" if $remote_config_file;
139
140    if (defined($opts{'fsname'})) {
141        push(@ssh_port_fwds,"-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT");
142    }
143
144    if (defined($opts{'bossname'})) {
145        push(@ssh_port_fwds, "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT");
146    }
147
148    if (defined($opts{'eventservername'})) {
149        push(@ssh_port_fwds,"-R ". 
150            ":$remote_pubsub_port:$opts{'eventservername'}:$PUBSUB_PORT");
151    }
152    if (defined($opts{'remoteeventservername'})) {
153        push(@ssh_port_fwds,"-L :$remote_pubsub_port:" . 
154            "$opts{'remoteeventservername'}:$PUBSUB_PORT");
155    }
156
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
162    # -n just starts the ssh tap tunnel
163    @ssh_port_fwds = () if ($opts{'type'} eq 'experiment' || $opts{'n'});
164
165    print "ssh_port_fwds = ", join("\n",@ssh_port_fwds), "\n" if ($debug);
166}
167
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.
171my $ports_on = 0;
172my $tunnel_on = 0;
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    };
183    s/^\s*PermitTunnel.*/PermitTunnel yes/ && do {
184        print $new_conf $_ unless $tunnel_on++;
185        next;
186    };
187    print $new_conf $_;
188}
189print $new_conf "GatewayPorts yes\n" unless $ports_on;
190print $new_conf "PermitTunnel yes\n" unless $tunnel_on;
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
199# Need these to make the Ethernet tap and bridge to work...
200system("kldload /boot/kernel/bridgestp.ko") 
201    if -r "/boot/kernel/bridgestp.ko";
202system("kldload /boot/kernel/if_bridge.ko");
203system("kldload /boot/kernel/if_tap.ko");
204
205if ($tunnelcfg && !$remote) {
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);
211}
212
213if (!$remote) {
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}
218
219if ($active) {
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.
225
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!)
228
229    do {
230        system("$NC -z $opts{'peer'} $SSH_PORT");
231    } until (!$?);
232
233    # XXX:  Do we need to clear out previously created bridge interfaces?
234
235    my $count = 0;
236    my @SSHCMD;
237
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") {
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        }
246
247        exit;
248    }
249
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;
257        my $cmd;
258
259        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
260
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.
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        }
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\" " . 
280            "$opts{'peer'}  \"$remote_script_dir/fed-tun.pl " . 
281            "$remote_config_file -r $addr $count\" & |";
282
283        print "$cmd\n" if $debug;
284
285        open(SSHCMD, $cmd) 
286           or die "Failed to run ssh";
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...
290
291        while ($check = <SSHCMD>) {
292            last if $check =~ /^Remote connection all/;
293        }
294        print "Got line [$check] from remote side\n" if ($debug);
295
296        &setup_bridging($tun, $bridge, $iface, $addr);
297        $count++;
298        @ssh_port_fwds = ();  # only do this on the first connection
299    }
300    close(IFFILE);
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 $?;
318} elsif ($remote) {
319    # We're on the remote system;  figure out which interface to
320    # tweak, based on the IP address passed in.
321
322    my $iter = 0;
323    my $iface;
324
325    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
326    while (<RTFILE>) {
327        if (/interface: (\w+)/) {
328            $iface = $1;
329        }
330    }
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;
336
337    &setup_bridging($tun, $bridge, $iface, $addr);
338    print "Remote connection all set up!\n";  # Trigger other end with output
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    }
362} else {
363    print "inactive end of a connection, finishing" if ($debug);
364}
365
366print "all done!\n" if ($debug);
367exit;
368
369
370# Set up the bridging for the new stuff...
371
372sub setup_bridging($; $; $; $) {
373    my ($tun, $bridge, $iface, $addr) = @_;
374
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
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}
389
390# Set up tunnel info for DETER-like testbeds.
391
392sub setup_tunnel_cfg {
393    my (%opts) = @_;
394    #my $tunnel_iface = "em0";   # XXX
395    my $tunnel_iface = $opts{'interface'} || "em0";
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"
418        if (!defined($tunnel_router) || !$tunnel_router);
419
420    print "tunnel options:  ip=$tunnel_ip mask=$tunnel_mask mac=$tunnel_mac router=$tunnel_router\n" if ($debug);
421
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    }
430
431    system("ifconfig $tunnel_iface $tunnel_ip" .
432           ($tunnel_mask ? " netmask $tunnel_mask" : "") . " up");
433    warn "configuration of tunnel interface failed" if ($?);
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;
440    my $max_retries = 300;
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 );
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.