chiark / gitweb /
Add example invocation.
[userv-utils.git] / ipif / udptunnel
1 #!/usr/bin/perl
2 # Simple tunnel for userv-ipif tunnels.
3 #
4 # Example test invocation
5 #
6 #  ./udptunnel -e nonce -e timestamp/10/30 -e pkcs5/8 -e blowfish-cbcmac/128 -e blowfish-cbc/128 -m -f ./udptunnel-forwarder davenant,Any anarres,Command 172.30.206.1,172.30.206.2,1000,cslip 15,70 '' '' rsh anarres things/userv-utils/ipif/udptunnel -f things/userv-utils/ipif/udptunnel-forwarder
7 #
8 # usage:
9 #  udptunnel
10 #        [ -l[<local-command/arg>] ... .
11 #        | -e <encryption-mech>[/<encryption-parameter>...]
12 #        | -m   (`masquerade support': subcommand gets `Wait' instead of our addr/port)
13 #        | -d   (`dump keys': when no subcmd, spew keys rather than reading them;
14 #                we always send keys to our subcmd if there is one)
15 #        | -Dcrypto  (debug crypto - use with care, prints keys, packets &c on screen!)
16 #        | -f<path-to-udptunnel-forwarder>
17 #          ...
18 #        ]
19 #            <public-local-addr>,<public-local-port>
20 #            <public-remote-addr>,<public-remote-port>
21 #            <private-local-addr>,<private-remote-addr>,<mtu>,<proto>
22 #            <keepalive>,<timeout>
23 #            <extra-local-nets> <extra-remote-nets>
24 #          [ <remote-command> [<remote-args> ...] ]
25 #
26 # proto may be slip or cslip
27 #
28 # Any <..-addr> may also be hostname
29 #
30 # Local addr's and ports may also be:
31 #    `Print'     choose one ourselves and print both port and addr
32 #    `Any'       choose one ourselves and do not print it
33 # Remote addr's and ports may also be:
34 #    `Wait'      wait to receive a packet before assigning address
35 #    `Command'   run a subcommand and wait for it to tell us the values
36 # When any addr or port is `Command' then <remote-command> must be specified.
37 #
38 # If <remote-command> is specified it should run udptunnel at the
39 # remote end; it will be invoked as
40 #    <remote-command> [ <-e arguments passed along> ]
41 #                     <public-remote-addr'>,<public-remote-port'>
42 #                     <public-local-addr'>,<public-local-port'>
43 #                     <private-remote-addr>,<private-local-addr>,<mtu>,<proto>
44 #                     <keepalive>,<timeout>
45 #                     <extra-remote-nets> <extra-local-nets>
46 #
47
48 # If it was given Print for <public-remote-foo'>, this command's first
49 # stdout output should be the real
50 # <public-remote-addr>,<public-remote-port> pair (and of course this
51 # udptunnel's output will be).  It may then produce more stdout which,
52 # if any, will be forwarded to the local end's stdout as debugging info.
53 #
54 # After this, if any encryption was specified, the encryption
55 # parameters will be fed into its stdin.  See the documentation in the
56 # mech-*.c files for details of the parameters.  udptunnel will
57 # arrange to feed the keys fd of udptunnel-forwarder into the stdin of
58 # the remote command.
59 #
60 # <public-remote-foo'> is as follows:
61 #   <public-remote-foo>  <public-remote-foo'>
62 #   actual addr/port     that addr/port
63 #   `Command'            `Print'
64 #   `Wait'               `Any'
65 #
66 # <public-local-foo'> is as follows:
67 #   <public-local-foo>   <public-local-foo'>     <public-local-foo'>
68 #                        (-m not specified)      (-m specified)
69 #   actual addr/port     that addr/port          `Wait'
70 #   `Wait'               the chosen address      `Wait'
71 #   `Print'              the chosen address      `Wait'
72 #
73 # udptunnel will userv ipif locally, as
74 #    userv root ipif <private-local-addr>,<private-remote-addr>,<mtu>,<proto>
75 #                    <extra-local-nets>
76 # or, if -l was given, userv root ipif is replaced with the argument(s)
77 # following -l option(s) until `.'.
78 #
79 # udptunnel will also run udptunnel-forwarder with appropriate options
80 #
81 # recommended encryption parameters are:
82 #   -e nonce                            (prepend 32 bit counter)
83 #   -e timestamp/<max-skew>/<max-age>   (prepend 32 bit time_t, and check on receipt)
84 #   -e pkcs5/8                          (pad as per PKCS#5 to 8-byte boundary)
85 #   -e blowfish-cbcmac/128              (prepend CBC MAC with random IV and 128 bit key)
86 #   -e blowfish-cbc/128                 (encrypt with CBC, random IV and 128 bit key)
87 # where <max-skew> is perhaps 10 and <max-age> perhaps 30.
88
89 # Copyright (C) 1999-2000 Ian Jackson
90 #
91 # This is free software; you can redistribute it and/or modify it
92 # under the terms of the GNU General Public License as published by
93 # the Free Software Foundation; either version 2 of the License, or
94 # (at your option) any later version.
95 #
96 # This program is distributed in the hope that it will be useful, but
97 # WITHOUT ANY WARRANTY; without even the implied warranty of
98 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
99 # General Public License for more details.
100 #
101 # You should have received a copy of the GNU General Public License
102 # along with userv-utils; if not, write to the Free Software
103 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
104 #
105 # $Id$
106
107 use Socket;
108 use POSIX;
109 use Fcntl;
110
111 $progname= $0; $progname =~ s,.*/,,;
112 $|=1;
113
114 chomp($hostname= `uname -n`);
115 $? and die "$progname: cannot get hostname (uname failed with code $?)\n";
116
117 sub quit ($) { die "$progname - $hostname: fatal error: $_[0]\n"; }
118 sub debug ($) { print "$progname - $hostname: debug: $_[0]\n"; }
119 sub fail ($) { quit("unexpected system call failure: $_[0]: $!"); }
120 sub warning ($) { warn "$progname - $hostname: $_[0]\n"; }
121
122 sub eat_addr_port ($) {
123     my ($x) = @_;
124     @ARGV or quit("<addr>,<port> missing");
125     $_= shift(@ARGV);
126     (m/^$x,/i && m/^[a-z]/ || m/,$x$/i && m/,[a-z]/)
127         and warning("$_: use Mixed Case for special values");
128     m/^([0-9a-z][0-9a-z-+.]+|$x)\,(\d+|$x)$/
129         or quit("$_: <host/addr>,<port> bad syntax".
130                 (m/[A-Z]/ ? ' (use lowercase for hostnames)' : ''));
131     return ($1,$2);
132 }
133 sub conv_host_addr ($) {
134     my ($s,$r,@h) = @_;
135     return INADDR_ANY() if $s =~ m/^[A-Z][a-z]/;
136     return $r if defined($r= inet_aton($s));
137     @h= gethostbyname($s) or quit("$s: cannot get address");
138     $h[2] eq &AF_INET or quit("$s: address is not IPv4");
139     @h < 5 or quit("$s: name maps to no addresses");
140     $r= $h[4];
141     @h == 5 or warning("$s: name has several addresses, using ".inet_ntoa($r));
142     return $r;
143 }
144 sub conv_port_number ($) {
145     my ($s,$r) = @_;
146     return 0 if $s =~ m/^[A-Z][a-z]/;
147     $r= $s+0;
148     $r>0 && $r<65536 or quit("$s: port out of range");
149     return $r;
150 }
151 sub show_addr ($) {
152     my ($s,@s) = @_;
153     @s= unpack_sockaddr_in($s);
154     return inet_ntoa($s[1]);
155 }
156 sub show_port ($) {
157     my ($s,@s) = @_;
158     @s= unpack_sockaddr_in($s);
159     return $s[0];
160 }
161 sub show_addr_port ($) {
162     my ($s) = @_;
163     return show_addr($s).','.show_port($s);
164 }
165 sub arg_value ($$) {
166     my ($val,$opt) = @_;
167     $_= '-';
168     return $val if length $val;
169     @ARGV or quit("$opt needs value");
170     return shift @ARGV;
171 }
172
173 $|=1;
174
175 @lcmd= ();
176 @encryption= ();
177 $masq= 0;
178 $dump= 0;
179 $fcmd= 'udptunnel-forwarder';
180 $xfwdopts= '';
181
182 while ($ARGV[0] =~ m/^-/) {
183     $_= shift @ARGV;
184     last if m/^--?$/;
185     while (!m/^-$/) {
186         if (s/^-l//) {
187             push @lcmd,$_ if length;
188             while (@ARGV && ($_= shift @ARGV) ne '.') { push @lcmd, $_; }
189             $_= '-'
190         } elsif (s/^-f//) {
191             $fcmd= arg_value($_,'-f');
192         } elsif (s/^-e//) {
193             $encrarg= arg_value($_,'-e');
194             push @remoteopts, "-e$encrarg";
195             @thisencryption= split m#/#, $encrarg;
196             $thisencryption[0] =~ s/^/\|/;
197             push @encryption, @thisencryption;
198         } elsif (s/^-m/-/) {
199             $masq= 1;
200         } elsif (s/^-d/-/) {
201             $dump= 1;
202         } elsif (s/^-Dcrypto$/-/) {
203             $xfwdopts.= 'K';
204             push @remoteopts, '-Dcrypto';
205         } else {
206             quit("unknown option \`$_'");
207         }
208     }
209 }
210
211 # Variables \$[lr]a?p?(|s|d|r)
212 # Local/Remote  Address&/Port
213 #    actualvalue/Specified/Displaypassdown/fromRemote/passtoForwarder
214 #
215 ($las,$lps)= eat_addr_port('Print|Any');
216 $la= conv_host_addr($las);
217 $lp= conv_port_number($lps);
218 $ls= pack_sockaddr_in $lp,$la;
219
220 ($ras,$rps)= eat_addr_port('Wait|Command');
221 $ra= conv_host_addr($ras);
222 $rp= conv_port_number($rps);
223 $rs= pack_sockaddr_in $rp,$ra;
224
225 $_= shift @ARGV;
226 m/^([.0-9]+),([.0-9]+),(\d+),(slip|cslip)$/
227     or quit("lvaddr,rvaddr,mtu,proto missing or bad syntax or proto not [c]slip");
228 ($lva,$rva,$mtu,$proto) = ($1,$2,$3,$4);
229
230 $_= shift @ARGV;
231 m/^(\d+),(\d+)$/ or quit("keepalive,timeout missing or bad syntax");
232 ($keepalive,$timeout)= ($1,$2);
233 $keepalive && ($timeout > $keepalive*2) or quit("timeout must be < 2*keepalive")
234     if $timeout;
235
236 # Variables \$[lr]exn
237 # Local/Remote Extra Nets
238 $lexn= shift @ARGV;
239 $rexn= shift @ARGV;
240
241 defined($udp= getprotobyname('udp')) or fail("getprotobyname udp");
242
243 socket(L,PF_INET,SOCK_DGRAM,$udp) or fail("socket");
244 bind(L,$ls) or quit("bind failed: $!");
245 defined($ls= getsockname(L)) or fail("getsockname");
246 $lad= show_addr($ls);
247 $lpd= show_port($ls);
248 $lapd= "$lad,$lpd";
249
250 print "$lapd\n" or fail("print addr/port") if ($las eq 'Print' || $lps eq 'Print');
251
252 $rapcmd= ($ras eq 'Command' || $rps eq 'Command');
253 quit("need remote-command if Command for remote addr/port") if $rapcmd && !@ARGV;
254
255 sub xform_remote ($$) {
256     my ($showed,$spec) = @_;
257     return 'Print' if $spec eq 'Command';
258     return 'Any' if $spec eq 'Wait';
259     return $showed;
260 }
261
262 if (@ARGV) {
263     warning("-d specified with remote command, ignoring") if $dump;
264     $dump= 1;
265     
266     $rad= xform_remote(show_addr($rs),$ras);
267     $rpd= xform_remote(show_port($rs),$rps);
268     @rcmd= (@ARGV,
269             @remoteopts,
270             "$rad,$rpd",
271             $masq ? 'Wait,Wait' : $lapd,
272             "$rva,$lva,$mtu,$proto",
273             "$keepalive,$timeout",
274             $rexn, $lexn);
275     debug("remote command @rcmd");
276
277     if ($rapcmd) {
278         pipe(RAPREAD,RCMDREADSUB) or fail("pipe");
279         select(RCMDREADSUB); $|=1; select(STDOUT);
280     }
281     pipe(RCMDWRITESUB,DUMPKEYS) or fail("pipe");
282     defined($c_rcmd= fork) or fail("fork for remote");
283     if (!$c_rcmd) {
284         open STDIN, "<&RCMDWRITESUB" or fail("reopen stdin for remote command");
285         open STDOUT, ">&RCMDREADSUB" or fail("reopen stdout for remote command")
286             if $rapcmd;
287         close RAPREAD if $rapcmd;
288         close DUMPKEYS;
289         close RCMDWRITESUB;
290         close RCMDREADSUB;
291         close L;
292         exec @rcmd; fail("failed to execute remote command $rcmd[0]");
293     }
294     close RCMDWRITESUB;
295     
296     if ($rapcmd) {
297         close RCMDREADSUB if $rapcmd;
298         $!=0; $_= <RAPREAD>; $e="$!";
299
300         defined($c_catremdebug= fork) or fail("fork for cat remote debug");
301         if (!$c_catremdebug) {
302             open(STDIN,"<&RAPREAD") or fail("redirect remote debug");
303             close RAPREAD;
304             close DUMPKEYS;
305             close L;
306             exec "cat"; fail("execute cat");
307         }
308         close RAPREAD;
309         
310         if (!length) {
311             close DUMPKEYS;
312             waitpid $c_rcmd,0 or fail("wait for remote command");
313             quit($? ? "remote command failed (code $?)" :
314                  $e ? "read error from remote command: $e" :
315                  "no details received from remote");
316         }
317         chomp;
318         m/^([.0-9]+)\,(\d+)$/ or quit("invalid details from remote end: \`$_'");
319         ($rar,$rpr) = ($1,$2);
320         $ra= conv_host_addr($rar);
321         $rp= conv_port_number($rpr);
322     }
323 } elsif ($dump) {
324     open DUMPKEYS, ">&STDOUT" or fail("reopen stdout for key material");
325     $dump= 1;
326 } else {
327     open DUMPKEYS, "<&STDIN" or fail("reopen stdout for key material");
328 }
329
330 $rs= pack_sockaddr_in $rp,$ra;
331
332 if ($ras eq 'Wait' || $rps eq 'Wait') {
333     @rapf= ('');
334     $rapd= ('Wait,Wait');
335 } else {
336     @rapf= (show_addr($rs), show_port($rs));
337     $rapd= show_addr_port($rs);
338 }
339 @lcmd= qw(userv root ipif) unless @lcmd;
340
341 debug("using remote $rapd local $lapd");
342 push @lcmd, ("$lva,$rva,$mtu,$proto",$lexn);
343 debug("local command @lcmd.");
344
345 pipe(UR,UW) or fail("up pipe");
346 pipe(DR,DW) or fail("down pipe");
347
348 defined($c_lcmd= fork) or fail("fork for local command");
349 if (!$c_lcmd) {
350     close UR; close DW;
351     open(STDIN,"<&DR") or fail("reopen stdin for packets");
352     open(STDOUT,">&UW") or fail("reopen stdout for packets");
353     exec @lcmd;
354     quit("cannot execute $lcmd[0]: $!");
355 }
356 close UW;
357 close DR;
358
359 $xfwdopts.= 'w' if $dump;
360
361 @fcmd= ($fcmd, $xfwdopts,
362         fileno(L), fileno(DW), fileno(UR), fileno(DUMPKEYS),
363         $mtu, $keepalive, $timeout,
364         @rapf,
365         @encryption);
366 debug("forwarding command @fcmd.");
367
368 defined($c_fwd= fork) or fail("fork for udptunnel-forwarder");
369 if (!$c_fwd) {
370     foreach $fd (qw(L DW UR DUMPKEYS)) {
371         fcntl($fd, F_SETFD, 0) or fail("set no-close-on-exec $fd");
372     }
373     exec @fcmd; fail("cannot execute $fcmd[0]");
374 }
375
376 close L;
377 close DUMPKEYS;
378 close UR;
379 close DW;
380
381 %procs= ($c_fwd, 'forwarder',
382          $c_lcmd, 'local command');
383 $procs{$c_rcmd}= 'remote command' if $c_rcmd;
384 $procs{$c_catremdebug}= 'debug cat' if $c_catremdebug;
385
386 $estatus= 0;
387
388 while (keys %procs) {
389     ($c= wait) >0 or
390         fail("wait failed (expecting ". join('; ',keys %procs). ")");
391     $status= $?;
392     warning("unexpected child reaped: pid $c, code $status"), next
393         unless exists $procs{$c};
394     $str= $procs{$c};
395     delete $procs{$c};
396     $status ? warning("subprocess $str failed with code $status")
397         : debug("subprocess $str finished");
398     if ($c==$c_lcmd || $c==$c_fwd || $c==$c_rcmd) {
399         kill 15, grep (exists $procs{$_}, $c_fwd, $c_rcmd);
400     }
401     $estatus=1 unless $c == $c_catremdebug;
402 }
403
404 debug("all processes terminated, exiting with status $estatus");
405
406 exit $estatus;