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