source: fedkit/fed-tun.pl @ 329f61d

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

demo done

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