source: fedkit/fed-tun.ucb.pl @ 7a8d667

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

reconfigure sshd_config explicitly

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