source: fedkit/fed-tun.ucb.pl @ d81971a

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

FreeBSD 7.0 compatibility

  • Property mode set to 100755
File size: 12.8 KB
RevLine 
[f3691ff]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 IO::Pipe;
[01073f7]24use File::Copy;
[f3691ff]25
26my $IFCONFIG = "/sbin/ifconfig";
27my $TMCC = "/usr/local/etc/emulab/tmcc";
[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";
[f3691ff]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
[7a8d667]35my $sshd_config = "/etc/ssh/sshd_config";    # Probably should be a param
[f3691ff]36
37# Ports that are forwarded between testbeds
38my $TMCD_PORT = 7777;
39my $SMBFS_PORT = 139;
40my $PUBSUB_PORT = 16505;
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.
[01073f7]47                                           
48die "Cannot exec $SSH" unless -x $SSH;
49
[f3691ff]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 = "";
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:r', \%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        $ssh_port_fwds = "-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT ";
120    }
121
122    if (defined($opts{'bossname'})) {
123        $ssh_port_fwds .= "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT ";
124    }
125
126    if (defined($opts{'eventservername'})) {
127        $ssh_port_fwds .= "-R :$remote_pubsub_port:$opts{'eventservername'}:" . 
128            "$PUBSUB_PORT ";
129    }
130    if (defined($opts{'remoteeventservername'})) {
131        $ssh_port_fwds .= "-L :$remote_pubsub_port:" . 
132            "$opts{'remoteeventservername'}:$PUBSUB_PORT ";
133    }
134
135    $ssh_port_fwds = "" if ($opts{'type'} eq 'experiment');
136
137    print "ssh_port_fwds = $ssh_port_fwds\n" if ($debug);
138}
139
[01073f7]140
141# Both sides need to have GatewayPorts and PermitTunnel set.  Copy the existing
142# sshd_config, making sure GatewayPorts and PermitTunnel are set to yes,
143# replace the original, and restart sshd.
[7a8d667]144my $ports_on = 0;
[01073f7]145my $tunnel_on = 0;
[7a8d667]146
147my $conf = new IO::File($sshd_config) || die "Can't open $sshd_config: $!\n";
148my $new_conf = new IO::File(">/tmp/sshd_config") || 
149    die "Can't open new ssh_config: $!\n";
150
151while(<$conf>) {
152    s/^\s*GatewayPorts.*/GatewayPorts yes/ && do {
153        print $new_conf $_ unless $ports_on++;
154        next;
155    };
[01073f7]156    s/^\s*PermitTunnel.*/PermitTunnel yes/ && do {
157        print $new_conf $_ unless $tunnel_on++;
158        next;
159    };
[7a8d667]160    print $new_conf $_;
161}
162print $new_conf "GatewayPorts yes\n" unless $ports_on;
[01073f7]163print $new_conf "PermitTunnel yes\n" unless $tunnel_on;
[7a8d667]164$conf->close();
165$new_conf->close();
166
167copy("/tmp/sshd_config", $sshd_config) || 
168    die "Cannot replace $sshd_config: $!\n";
169
170system("/etc/rc.d/sshd restart");
171
172
[f3691ff]173# Need these to make the Ethernet tap and bridge to work...
[01073f7]174system("kldload /boot/kernel/bridgestp.ko") 
175    if -r "/boot/kernel/bridgestp.ko";
[f3691ff]176system("kldload /boot/kernel/if_bridge.ko");
177system("kldload /boot/kernel/if_tap.ko");
178
179if (!$remote) {
180    # At the Berkeley federant, the outgoing addresses are fixed and based on
181    # the control net.  We do set up a host route to the peer.  This is a
182    # simplified version of the DETER setup.
183
184    &setup_tunnel_cfg(%opts);
185}
186
187if (!$remote) {
188    system("umask 077 && cp $opts{'privkeys'} /root/.ssh/id_rsa");
189    system("umask 077 && cp $opts{'pubkeys'} /root/.ssh/id_rsa.pub");
190    system("umask 077 && cat $opts{'pubkeys'} >> /root/.ssh/authorized_keys");
191}
192
193if ($active) {
194    # If we're the initiator, open up a separate tunnel to the remote
195    # host for each of the different experiment net interfaces on this
196    # machine.  Execute this startup script on the far end, but with
197    # the -r option to indicate that it's getting invoked remotely and
198    # we should just handle the remote-end tasks.
199
200    # Set up synchronization, so that the various user machines won't try to
201    # contact boss before the tunnels are set up.  (Thanks jjh!)
202
203    do {
204        system("$NC -z $opts{'peer'} $SSH_PORT");
205    } until (!$?);
206
207    # XXX:  Do we need to clear out previously created bridge interfaces?
208
209    my $count = 0;
210    my @SSHCMD;
211
212    # If we are just setting up a control net connection, just fire up
213    # ssh with the null command, and hang loose.
214
215    if ($type eq "control") {
216        system("$SSH $ssh_port_fwds -Nno \"StrictHostKeyChecking no\" $opts{'peer'} &"); #or die "Failed to run ssh";
217
218        exit;
219    }
220
221    open(IFFILE, "/var/emulab/boot/ifmap") || die "couldn't open ifmap\n";
222    while (<IFFILE>) {
223        my @a = split(' ');
224        my $iface = $a[0];
225        my $addr = $a[1];
226        my $bridge = "bridge" . $count;
227        my $tun = "tap" . $count;
228
229        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
230
231        # Note that we're going to fire off an ssh which will never return;
232        # we need the connection to stay up to keep the tunnel up.
233        # In order to check for problems, we open it this way and read
234        # the expected single line of output when the tunnel is connected.
235
[01073f7]236        # The Tunnel option specifies the level to tunnel at.  Ethernet creates
237        # a tap device rather than a tun device.  Strict host key checking
238        # avoids asking the user to OK a strange host key.
239        my $cmd =  "$SSH -w $count:$count -o \"Tunnel ethernet\" " . 
240            "-o \"StrictHostKeyChecking no\" " . 
241            "$opts{'peer'}  \"$remote_script_dir/fed-tun.pl " . 
242            "$remote_config_file -r $addr $count\" & |";
243
244        print "$cmd\n" if $debug;
245        open($SSHCMD[$count], $cmd) or die "Failed to run ssh";
[f3691ff]246
247        my $check = <$SSHCMD[$count]>;  # Make sure something ran...
248        print "Got line [$check] from remote side\n" if ($debug);
249
250        &setup_bridging($tun, $bridge, $iface, $addr);
251        $count++;
252        $ssh_port_fwds = "";  # only do this on the first connection
253    }
254    close(IFFILE);
255
256    # Start a local event repeater (unless we're missing parameters
257    die "Missing event repeater params (No config file ?)\n"
258        unless $event_repeater && $opts{'remoteexperiment'} && 
259        $opts{'localexperiment'};
260
261    print "Starting event repeater\n" if $debug;
262   
263    print("$event_repeater -M -P $remote_pubsub_port -S localhost " . 
264        "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}\n") 
265        if $debug;
266    # Connect to the forwarded pubsub port on this host to listen to the
267    # other experiment's events, and to the local experiment to forward
268    # events.
269    system("$event_repeater -M -P $remote_pubsub_port -S localhost " . 
270        "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}");
271    warn "Event repeater returned $?\n" if $?;
272} elsif ($remote) {
273    # We're on the remote system;  figure out which interface to
274    # tweak, based on the IP address passed in.
275
276    my $iter = 0;
277    my $iface;
278
279    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
280    while (<RTFILE>) {
281        if (/interface: (\w+)/) {
282            $iface = $1;
283        }
284    }
285    close(RTFILE);
286
287    die "Couldn't find interface to use." if (!defined($iface));
288    my $bridge = "bridge" . $count;
289    my $tun = "tap" . $count;
290
291    &setup_bridging($tun, $bridge, $iface, $addr);
292    print "Remote connection all set up!\n";  # Trigger other end with output
293
294    # If this is the first remote invocation on a control gateway, start the
295    # event repeater.
296
297    my $file = new IO::File(">/tmp/remote");
298    print($file "hello!!!\n") if $file;
299    if ( $count == 0 && $type ne "experiment" ) {
300        my $remote_pubsub_port = $PUBSUB_PORT - 1;  # There will be a local
301                                                    # pubsubd running, so we
302                                                    # dodge the port on the
303                                                    # remote tunnel node.
304        print($file "In here!\n");
305        # Make sure we have the relevant parameters
306        die "Missing event repeater params (No config file ?)\n"
307            unless $event_repeater && $opts{'remoteexperiment'} && 
308            $opts{'localexperiment'};
309
310        print "Starting event repeater\n" if $debug;
311       
312        print($file "$event_repeater -P $remote_pubsub_port -S localhost " . 
313            "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}\n") 
314            if $file;
315        # Connect to the forwarded pubsub port on this host to listen to the
316        # other experiment's events, and to the local experiment to forward
317        # events.
318        system("$event_repeater -P $remote_pubsub_port -S localhost " . 
319            "-E $opts{'remoteexperiment'} -e $opts{'localexperiment'}");
320        warn "Event repeater returned $?\n" if $?;
321    }
322    $file->close() if $file;
323} else {
324    print "inactive end of a connection, finishing" if ($debug);
325}
326
327print "all done!\n" if ($debug);
328exit;
329
330
331# Set up the bridging for the new stuff...
332
333sub setup_bridging($; $; $; $) {
334    my ($tun, $bridge, $iface, $addr) = @_;
335
336    print "Waiting to see if new iface $tun is up\n" if ($debug);
337
338    do {
339        sleep 1;
340        system("$IFCONFIG $tun");
341    } until (!$?);
342
343    print "setting up $bridge with $iface and nuking $addr\n" if ($debug);
344
345    system("ifconfig $bridge create");
346    system("ifconfig $iface delete $addr");
347    system("ifconfig $bridge addm $iface up");
348    system("ifconfig $bridge addm $tun");
349}
350
351# Set up tunnel info for UCB testbed
352
353sub setup_tunnel_cfg {
354    my (%opts) = @_;
355    my $tunnel_iface = "em5";
356    my $control_iface = "em4";
357    my $tunnel_prefix = "192.154.6.";
358    my $tunnel_router = "192.154.6.1";
359    my $netmask = "255.255.255.0";
360    my $ipipe = new IO::Pipe();
361    my $pcnum;
362
363    $ipipe->reader("$IFCONFIG $control_iface");
364
365    while (<$ipipe>) {
366        /inet\s+\d+\.\d+\.\d+\.(\d+)/ && do {
367            $pcnum = $1;
368            last;
369        };
370    }
371    $ipipe->close();
372    $pcnum += 50;
373    $pcnum &=0xff if $pcnum > 255;
374
[48f7524]375    system("ifconfig $tunnel_iface $tunnel_prefix$pcnum netmask $netmask");
[f3691ff]376    warn "configuration of tunnel interface failed" if ($?);
377
378    # Sometimes the insertion of DNS names lags a bit.  Retry this
379    # configuration a few times to let DNS catch up.  Might want to really
380    # check the DNS name before we try this...
381    my $config_succeeded = 0;
382    my $tries = 0;
[2aeb39e]383    my $max_retries = 30;
[f3691ff]384
385    do {
386        system("route add $opts{'peer'} $tunnel_router");
387        if ( $? ) {
388            warn "configuration routes via tunnel interface failed";
389            $tries++;
390            sleep(10);
391        }
392        else { $config_succeeded = 1; }
393    } until ( $config_succeeded || $tries > $max_retries );
394
395    print "setup_tunnel_cfg done\n" if ($debug);
396}
397
398# Trick config-file parsing code from Ted Faber:
399
400# Parse the config file.  The format is a colon-separated parameter name
401# followed by the value of that parameter to the end of the line.  This parses
402# that format and puts the parameters into the referenced hash.  Parameter
403# names are mapped to lower case, parameter values are unchanged.  Returns 0 on
404# failure (e.g. file open) and 1 on success.
405sub parse_config {
406    my($file, $href) = @_;
407    my($fh) = new IO::File($file);
408       
409    unless ($fh) {
410        warn "Can't open $file: $!\n";
411        return 0;
412    }
413
414    while (<$fh>) {
415        next if /^\s*#/ || /^\s*$/;     # Skip comments & blanks
416        chomp;
417        /^([^:]+):\s*(.*)/ && do {
418            my($key) = $1; 
419
420            $key =~ tr/A-Z/a-z/;
421            $href->{$key} = $2;
422            next;
423        };
424        warn "Unparasble line in $file: $_\n";
425    }
426    $fh->close();   # It will close when it goes out of scope, but...
427    return 1;
428}
Note: See TracBrowser for help on using the repository browser.