source: fedkit/fed-tun.pl @ 7583a62

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

FreeBSD 7.0 compatibility

  • Property mode set to 100755
File size: 13.9 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";
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";
30my $NC = "/usr/bin/nc";
31my $SSH_PORT = 22;
32my $ROUTE_GET = "/sbin/route get";  # XXX:  works on FreeBSD, but should
33                                    #       should be 'ip route get' for Linux
34my $sshd_config = "/etc/ssh/sshd_config";    # Probably should be a param
35
36# Ports that are forwarded between testbeds
37my $TMCD_PORT = 7777;
38my $SMBFS_PORT = 139;
39my $PUBSUB_PORT = 16505;
40my $SEER_PORT = 16606;
41
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.
47die "Cannot exec $SSH" unless -x $SSH;
48
49sub setup_bridging;
50sub setup_tunnel_cfg;
51sub parse_config;
52
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)
59
60my $usage = "Usage: fed-tun.pl [-r] [-d] [-f config-filename] [count addr]\n";
61
62my %opts;       # Note that this is used for both getops and the options file
63my @expected_opts = qw(active tunnelcfg bossname fsname type
64                       peer pubkeys privkeys);
65my $filename;
66my $remote;
67my $debug = 1;
68my $count;
69my $addr;
70my $active;
71my $type;
72my $tunnelcfg;
73my @ssh_port_fwds;              # Queue of ssh portforwarders to start.  The
74                                # -L or -R is in here.
75my $remote_script_dir;          # location of the other sides fed-tun.pl
76my $event_repeater;             # The pathname of the event repeater
77my $remote_config_file;         # Config file for the other side
78
79if ($#ARGV != 0 && !getopts('df:rn', \%opts)) {
80    die "$usage";
81}
82
83if (defined($opts{'d'})) {
84    $debug = 1;
85}
86
87if (defined($opts{'f'})) {
88    $filename = $opts{'f'};
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
99die "$usage" if (!defined($remote) && !defined($filename));
100
101if (defined($filename)) {
102    &parse_config("$filename", \%opts) || 
103        die "Cannot read config file $filename: $!\n";
104
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/;
113    $remote_script_dir = $opts{'remotescriptdir'} || ".";
114    $event_repeater = $opts{'eventrepeater'};
115    $remote_config_file = $opts{'remoteconfigfile'};
116    $remote_config_file = "-f $remote_config_file" if $remote_config_file;
117
118    if (defined($opts{'fsname'})) {
119        push(@ssh_port_fwds,"-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT");
120    }
121
122    if (defined($opts{'bossname'})) {
123        push(@ssh_port_fwds, "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT");
124    }
125
126    if (defined($opts{'eventservername'})) {
127        push(@ssh_port_fwds,"-R ". 
128            ":$remote_pubsub_port:$opts{'eventservername'}:$PUBSUB_PORT");
129    }
130    if (defined($opts{'remoteeventservername'})) {
131        push(@ssh_port_fwds,"-L :$remote_pubsub_port:" . 
132            "$opts{'remoteeventservername'}:$PUBSUB_PORT");
133    }
134
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
140    # -n just starts the ssh tap tunnel
141    @ssh_port_fwds = () if ($opts{'type'} eq 'experiment' || $opts{'n'});
142
143    print "ssh_port_fwds = ", join("\n",@ssh_port_fwds), "\n" if ($debug);
144}
145
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.
149my $ports_on = 0;
150my $tunnel_on = 0;
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    };
161    s/^\s*PermitTunnel.*/PermitTunnel yes/ && do {
162        print $new_conf $_ unless $tunnel_on++;
163        next;
164    };
165    print $new_conf $_;
166}
167print $new_conf "GatewayPorts yes\n" unless $ports_on;
168print $new_conf "PermitTunnel yes\n" unless $tunnel_on;
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
177# Need these to make the Ethernet tap and bridge to work...
178system("kldload /boot/kernel/bridgestp.ko") 
179    if -r "/boot/kernel/bridgestp.ko";
180system("kldload /boot/kernel/if_bridge.ko");
181system("kldload /boot/kernel/if_tap.ko");
182
183if ($tunnelcfg && !$remote) {
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);
189}
190
191if (!$remote) {
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}
196
197if ($active) {
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.
203
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!)
206
207    do {
208        system("$NC -z $opts{'peer'} $SSH_PORT");
209    } until (!$?);
210
211    # XXX:  Do we need to clear out previously created bridge interfaces?
212
213    my $count = 0;
214    my @SSHCMD;
215
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") {
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        }
224
225        exit;
226    }
227
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;
235        my $cmd;
236
237        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
238
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.
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        }
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\" " . 
258            "$opts{'peer'}  \"$remote_script_dir/fed-tun.pl " . 
259            "$remote_config_file -r $addr $count\" & |";
260
261        print "$cmd\n" if $debug;
262
263        open($SSHCMD[$count], $cmd) 
264           or die "Failed to run ssh";
265
266        my $check = <$SSHCMD[$count]>;  # Make sure something ran...
267        print "Got line [$check] from remote side\n" if ($debug);
268
269        &setup_bridging($tun, $bridge, $iface, $addr);
270        $count++;
271        @ssh_port_fwds = ();  # only do this on the first connection
272    }
273    close(IFFILE);
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 $?;
291} elsif ($remote) {
292    # We're on the remote system;  figure out which interface to
293    # tweak, based on the IP address passed in.
294
295    my $iter = 0;
296    my $iface;
297
298    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
299    while (<RTFILE>) {
300        if (/interface: (\w+)/) {
301            $iface = $1;
302        }
303    }
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;
309
310    &setup_bridging($tun, $bridge, $iface, $addr);
311    print "Remote connection all set up!\n";  # Trigger other end with output
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    }
335} else {
336    print "inactive end of a connection, finishing" if ($debug);
337}
338
339print "all done!\n" if ($debug);
340exit;
341
342
343# Set up the bridging for the new stuff...
344
345sub setup_bridging($; $; $; $) {
346    my ($tun, $bridge, $iface, $addr) = @_;
347
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
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}
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" .
399           ($tunnel_mask ? " netmask $tunnel_mask" : "") . " up");
400    warn "configuration of tunnel interface failed" if ($?);
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;
407    my $max_retries = 30;
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 );
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.