Foreign/Backend/Unix.pm untested

filter: Statementstmt 0.0% 0 / 291 Branchbran 0.0% 0 / 146 Conditioncond 0.0% 0 / 220 MC/DCmcdc 0.0% 0 / 123 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 808 CC 74 SCAR 70.1
CC
74
Cov
0%
_init_transport
2070.0
_do_io
420.0
_open4
72.0
CRAP 1110.7
1 package Net::SFTP::Foreign::Backend::Unix;
2  
3 our $VERSION = '1.88_02';
4  
5 use strict;
6 use warnings;
7  
8 use Carp;
9 our @CARP_NOT = qw(Net::SFTP::Foreign);
10  
11 use Fcntl qw(O_NONBLOCK F_SETFL F_GETFL);
12 use POSIX ();
13 use Net::SFTP::Foreign::Helpers qw(_tcroak _ensure_list _debug _hexdump $debug);
14 use Net::SFTP::Foreign::Constants qw(SSH2_FX_BAD_MESSAGE
15 SFTP_ERR_REMOTE_BAD_MESSAGE);
16 use Time::HiRes qw(sleep time);
17  
18 sub _new { shift }
19  
20 sub _defaults {
21 ( queue_size => 32 )
22 }
23  
24 sub _init_transport_streams {
25 my (undef, $sftp) = @_;
26 for my $dir (qw(ssh_in ssh_out)) {
27 binmode $sftp->{$dir};
28 my $flags = fcntl($sftp->{$dir}, F_GETFL, 0);
29 fcntl($sftp->{$dir}, F_SETFL, $flags | O_NONBLOCK);
30 }
31 }
32  
33 sub _open_dev_null {
34 my $sftp = shift;
35 my $dev_null;
36 unless (open $dev_null, '>', "/dev/null") {
37 $sftp->_conn_failed("Unable to redirect stderr to /dev/null");
38 return;
39 }
40 $dev_null
41 }
42  
43 sub _fileno_dup_over {
44 my ($good_fn, $fh) = @_;
45 if (defined $fh) {
46 my @keep_open;
47 my $fn = fileno $fh;
48 for (1..5) {
49 $fn >= $good_fn and return $fn;
50 $fn = POSIX::dup($fn);
51 push @keep_open, $fn;
52 }
53 POSIX::_exit(255);
54 }
55 undef;
56 }
57  
58 sub _open4 {
59 my $backend = shift;
60 my $sftp = shift;
61 my ($dad_in, $dad_out, $child_in, $child_out);
62 unless (pipe ($dad_in, $child_out) and
63 pipe ($child_in, $dad_out)) {
64 $sftp->_conn_failed("Unable to created pipes: $!");
65 return;
66 }
67 my $pid = fork;
68 unless ($pid) {
69 unless (defined $pid) {
70 $sftp->_conn_failed("Unable to fork new process: $!");
71 return;
72 }
73 close ($dad_in);
74 close ($dad_out);
75  
76 shift; shift;
77 my $child_err = shift;
78 my $pty = shift;
79  
80 $pty->make_slave_controlling_terminal if defined $pty;
81  
82 my $child_err_fno = eval { no warnings; fileno($child_err ? $child_err : *STDERR) };
83 my $child_err_safe; # passed handler may be tied, so we
84 # duplicate it in order to get a plain OS
85 # handler.
86 if (defined $child_err_fno and $child_err_fno >= 0) {
87 open $child_err_safe, ">&=$child_err_fno" or POSIX::_exit(1);
88 }
89 else {
90 open $child_err_safe, ">/dev/null" or POSIX::_exit(1);
91 }
92  
93 my $child_in_fno = _fileno_dup_over(0 => $child_in );
94 my $child_out_fno = _fileno_dup_over(1 => $child_out );
95 my $child_err_safe_fno = _fileno_dup_over(2 => $child_err_safe);
96  
97 unless (($child_in_fno == 0 or POSIX::dup2($child_in_fno, 0)) and
98 ($child_out_fno == 1 or POSIX::dup2($child_out_fno, 1)) and
99 ($child_err_safe_fno == 2 or POSIX::dup2($child_err_safe_fno, 2))) {
100 POSIX::_exit(1);
101 }
102 do { exec @_ };
103 POSIX::_exit(1);
104 }
105 close $child_in;
106 close $child_out;
107  
108 $_[0] = $dad_in;
109 $_[1] = $dad_out;
110 $pid;
111 }
112  
113 sub _init_transport {
114 my ($backend, $sftp, $opts) = @_;
115  
116 my $transport = delete $opts->{transport};
117  
118 if (defined $transport) {
119 if (ref $transport eq 'ARRAY') {
120 @{$sftp}{qw(ssh_in ssh_out pid)} = @$transport;
121 }
122 else {
123 $sftp->{ssh_in} = $sftp->{ssh_out} = $transport;
124 $sftp->{_ssh_out_is_not_dupped} = 1;
125 }
126 }
127 else {
128 my $user = delete $opts->{user};
129 my $pass = delete $opts->{passphrase};
130 my $ask_for_username_at_login;
131 my $pass_is_passphrase;
132 my $password_prompt;
133 if (defined $pass) {
134 $pass_is_passphrase = 1;
135 }
136 else {
137 $pass = delete $opts->{password};
138 if (defined $pass) {
139 $sftp->{_password_authentication} = 1;
140 $password_prompt = $sftp->{_password_prompt} = delete $opts->{password_prompt};
141 if (defined $password_prompt) {
142 unless (ref $password_prompt eq 'Regexp') {
143 $password_prompt = quotemeta $password_prompt;
144 $password_prompt = qr/$password_prompt\s*$/i;
145 }
146 }
147 $ask_for_username_at_login =
148 $sftp->{_ask_for_username_at_login} =
149 ( delete($opts->{ask_for_username_at_login}) ||
150 delete($opts->{asks_for_username_at_login}) );
151 if ($ask_for_username_at_login) {
152 croak "ask_for_username_at_login set but user was not given" unless defined $user;
153 croak "ask_for_username_at_login can not be used with a custom password prompt"
154 if defined $password_prompt;
155 }
156 }
157 }
158  
159 delete $opts->{expect_log_user}; # backward compatibility, not used anymore
160 my $stderr_discard = delete $opts->{stderr_discard};
161 my $stderr_fh = ($stderr_discard ? undef : delete $opts->{stderr_fh});
162 my $open2_cmd = delete $opts->{open2_cmd};
163 my $ssh_cmd_interface = delete $opts->{ssh_cmd_interface};
164  
165 my @open2_cmd;
166 if (defined $open2_cmd) {
167 @open2_cmd = _ensure_list($open2_cmd);
168 }
169 else {
170 my $host = delete $opts->{host};
171 defined $host or croak "sftp target host not defined";
172  
173 my $key_path = delete $opts->{key_path};
174  
175 my $ssh_cmd = delete $opts->{ssh_cmd};
176 $ssh_cmd = 'ssh' unless defined $ssh_cmd;
177 @open2_cmd = _ensure_list $ssh_cmd;
178  
179 unless (defined $ssh_cmd_interface) {
180 $ssh_cmd_interface = ( "@open2_cmd" =~ /\bplink\b/i ? 'plink' :
181 "@open2_cmd" =~ /\bsshg3\b/i ? 'tectia' :
182 'ssh' );
183 }
184  
185 my $port = delete $opts->{port};
186 my $ssh1 = delete $opts->{ssh1};
187  
188 my $more = delete $opts->{more};
189 defined $more and !ref($more) and $more =~ /^-\w\s+\S/ and
190 warnings::warnif("Net::SFTP::Foreign", "'more' argument looks like it should be split first");
191 my @more = _ensure_list $more;
192  
193 my @preferred_authentications;
194 if (defined $key_path) {
195 push @preferred_authentications, 'publickey';
196 push @open2_cmd, map { -i => $_ } _ensure_list $key_path;
197 }
198  
199 if ($ssh_cmd_interface eq 'plink') {
200 push @open2_cmd, -P => $port if defined $port;
201 if (defined $pass and !$pass_is_passphrase) {
202 warnings::warnif("Net::SFTP::Foreign", "using insecure password authentication with plink");
203 push @open2_cmd, -pw => $pass;
204 undef $pass;
205 }
206  
207 }
208 elsif ($ssh_cmd_interface eq 'ssh') {
209 push @open2_cmd, -p => $port if defined $port;
210 if (defined $pass and !$pass_is_passphrase) {
211 push @open2_cmd, -o => 'NumberOfPasswordPrompts=1';
212 push @preferred_authentications, ('keyboard-interactive', 'password');
213 }
214 if (@preferred_authentications
215 and not grep { $more[$_] eq '-o' and
216 $more[$_ + 1] =~ /^PreferredAuthentications\W/ } 0..$#more-1) {
217 push @open2_cmd, -o => 'PreferredAuthentications=' . join(',', @preferred_authentications);
218 }
219 }
220 elsif ($ssh_cmd_interface eq 'tectia') {
221 }
222 else {
223 die "Unsupported ssh_cmd_interface '$ssh_cmd_interface'";
224 }
225  
226 push @open2_cmd, -l => $user if defined $user;
227 push @open2_cmd, @more;
228 push @open2_cmd, $host;
229 push @open2_cmd, ($ssh1 ? "/usr/lib/sftp-server" : -s => 'sftp');
230 }
231  
232 my $redirect_stderr_to_tty = ( defined $pass and
233 ( delete $opts->{redirect_stderr_to_tty} or $ssh_cmd_interface eq 'tectia' ) );
234  
235 $redirect_stderr_to_tty and ($stderr_discard or $stderr_fh)
236 and croak "stderr_discard or stderr_fh can not be used together with password/passphrase "
237 . "authentication when Tectia client is used";
238  
239 $debug and $debug & 1 and _debug "ssh cmd: @open2_cmd\n";
240  
241 %$opts and return; # Net::SFTP::Foreign will find the
242 # unhandled options and croak
243  
244 if (${^TAINT} and Scalar::Util::tainted($ENV{PATH})) {
245 _tcroak('Insecure $ENV{PATH}')
246 }
247  
248 if ($stderr_discard) {
249 $stderr_fh = $backend->_open_dev_null($sftp) or return;
250 }
251  
252 if (defined $pass) {
253 # user has requested to use a password or a passphrase for
254 # authentication we use IO::Pty to handle that
255  
256 eval { require IO::Pty; 1 }
257 or croak "password authentication not available, IO::Pty is not installed or failed to load: $@";
258  
259 local ($ENV{SSH_ASKPASS}, $ENV{SSH_AUTH_SOCK}) if $pass_is_passphrase;
260  
261 my $name = $pass_is_passphrase ? 'Passphrase' : 'Password';
262  
263 my $child;
264 my $pty = IO::Pty->new;
265  
266 $redirect_stderr_to_tty and $stderr_fh = $pty->slave;
267  
268 $child = $backend->_open4($sftp, $sftp->{ssh_in}, $sftp->{ssh_out}, $stderr_fh, $pty, @open2_cmd);
269 unless (defined $child) {
270 $sftp->_conn_failed("Bad ssh command", $!);
271 return;
272 }
273 $sftp->{pid} = $child;
274 open my $pty_dup, '+>&', $pty; # store pty as a file handler instead of a object in
275 # order to save it from being destroyed too early
276 # during global destruction
277 $sftp->{_pty} = $pty_dup;
278  
279 $debug and $debug & 65536 and _debug "starting password authentication";
280 my $rv = '';
281 vec($rv, fileno($pty), 1) = 1;
282 my $buffer = '';
283 my $at = 0;
284 my $password_sent;
285 my $start_time = time;
286 while(1) {
287 if (defined $sftp->{_timeout}) {
288 $debug and $debug & 65536 and _debug "checking timeout, max: $sftp->{_timeout}, ellapsed: " . (time - $start_time);
289 if (time - $start_time > $sftp->{_timeout}) {
290 $sftp->_conn_failed("login procedure timed out");
291 return;
292 }
293 }
294  
295 if (waitpid($child, POSIX::WNOHANG()) > 0 or $! == Errno::ECHILD()) {
296 undef $sftp->{pid};
297 my $err = $? >> 8;
298 $sftp->_conn_failed("SSH slave exited unexpectedly with error code $err");
299 return;
300 }
301  
302 $debug and $debug & 65536 and _debug "waiting for data from the pty to become available";
303  
304 my $rv1 = $rv;
305 select($rv1, undef, undef, 1) > 0 or next;
306 if (my $bytes = sysread($pty, $buffer, 4096, length $buffer)) {
307 if ($debug and $debug & 65536) {
308 _debug "$bytes bytes readed from pty:";
309 _hexdump substr($buffer, -$bytes);
310 }
311 if ($buffer =~ /^The authenticity of host/mi or
312 $buffer =~ /^Warning: the \S+ host key for/mi) {
313 $sftp->_conn_failed("the authenticity of the target host can't be established, " .
314 "the remote host public key is probably not present on the " .
315 "'~/.ssh/known_hosts' file");
316 return;
317 }
318 if ($password_sent) {
319 $debug and $debug & 65536 and _debug "looking for password ok";
320 last if substr($buffer, $at) =~ /\n$/;
321 }
322 else {
323 $debug and $debug & 65536 and _debug "looking for user/password prompt";
324 my $re = ( defined $password_prompt
325 ? $password_prompt
326 : qr/(user|name|login)?[:?]\s*$/i );
327  
328 $debug and $debug & 65536 and _debug "matching against $re";
329  
330 if (substr($buffer, $at) =~ $re) {
331 if ($ask_for_username_at_login and
332 ($ask_for_username_at_login ne 'auto' or defined $1)) {
333 $debug and $debug & 65536 and _debug "sending username";
334 print $pty "$user\n";
335 undef $ask_for_username_at_login;
336 }
337 else {
338 $debug and $debug & 65536 and _debug "sending password";
339 print $pty "$pass\n";
340 $password_sent = 1;
341 }
342 $at = length $buffer;
343 }
344 }
345 }
346 else {
347 $debug and $debug & 65536 and _debug "no data available from pty, delaying until next read";
348 sleep 0.1;
349 }
350  
351 }
352 $debug and $debug & 65536 and _debug "password authentication done";
353 $pty->close_slave();
354 }
355 else {
356 $sftp->{pid} = $backend->_open4($sftp, $sftp->{ssh_in}, $sftp->{ssh_out}, $stderr_fh, undef, @open2_cmd);
357 unless (defined $sftp->{pid}) {
358 $sftp->_conn_failed("Bad ssh command", $!);
359 return;
360 }
361 }
362 }
363 $backend->_init_transport_streams($sftp);
364 }
365  
366 sub _after_init {
367 my ($backend, $sftp) = @_;
368 if ($sftp->{pid} and not $sftp->error) {
369 # do not propagate signals sent from the terminal to the
370 # slave SSH:
371 local ($@, $!);
372 eval { setpgrp($sftp->{pid}, 0) };
373 }
374 }
375  
376 sub _do_io {
377 my (undef, $sftp, $timeout) = @_;
378  
379 $debug and $debug & 32 and _debug(sprintf "_do_io connected: %s", $sftp->{_connected} || 0);
380  
381 return undef unless $sftp->{_connected};
382  
383 my $fnoout = fileno $sftp->{ssh_out};
384 my $fnoin = fileno $sftp->{ssh_in};
385 my ($rv, $wv) = ('', '');
386 vec($rv, $fnoin, 1) = 1;
387 vec($wv, $fnoout, 1) = 1;
388  
389 my $bin = \$sftp->{_bin};
390 my $bout = \$sftp->{_bout};
391  
392 local $SIG{PIPE} = 'IGNORE';
393  
394 my $len;
395 while (1) {
396 my $lbin = length $$bin;
397 if (defined $len) {
398 return 1 if $lbin >= $len;
399 }
400 elsif ($lbin >= 4) {
401 $len = 4 + unpack N => $$bin;
402 if ($len > 256 * 1024) {
403 $sftp->_set_status(SSH2_FX_BAD_MESSAGE);
404 $sftp->_set_error(SFTP_ERR_REMOTE_BAD_MESSAGE,
405 "bad remote message received");
406 return undef;
407 }
408 return 1 if $lbin >= $len;
409 }
410  
411 my $rv1 = $rv;
412 my $wv1 = length($$bout) ? $wv : '';
413  
414 $debug and $debug & 32 and _debug("_do_io select(-,-,-, ". (defined $timeout ? $timeout : 'undef') .")");
415  
416 my $n = select($rv1, $wv1, undef, $timeout);
417 if ($n > 0) {
418 if (vec($wv1, $fnoout, 1)) {
419 my $written = syswrite($sftp->{ssh_out}, $$bout, 64 * 1024);
420 if ($debug and $debug & 32) {
421 _debug (sprintf "_do_io write queue: %d, syswrite: %s, max: %d, \$!: %s",
422 length $$bout,
423 (defined $written ? $written : 'undef'),
424 64 * 1024, $!);
425 $debug & 2048 and $written and _hexdump(substr($$bout, 0, $written));
426 }
427 if ($written) {
428 substr($$bout, 0, $written, '');
429 }
430 elsif ($! != Errno::EAGAIN() and $! != Errno::EINTR()) {
431 $sftp->_conn_lost;
432 return undef;
433 }
434 }
435 if (vec($rv1, $fnoin, 1)) {
436 my $read = sysread($sftp->{ssh_in}, $$bin, 64 * 1024, length($$bin));
437 if ($debug and $debug & 32) {
438 _debug (sprintf "_do_io read sysread: %s, total read: %d, \$!: %s",
439 (defined $read ? $read : 'undef'),
440 length $$bin,
441 $!);
442 $debug & 1024 and $read and _hexdump(substr($$bin, -$read));
443 }
444 if (!$read and $! != Errno::EAGAIN() and $! != Errno::EINTR()) {
445 $sftp->_conn_lost;
446 return undef;
447 }
448 }
449 }
450 else {
451 $debug and $debug & 32 and _debug "_do_io select failed: $!";
452 next if ($n < 0 and ($! == Errno::EINTR() or $! == Errno::EAGAIN()));
453 return undef;
454 }
455 }
456 }
457  
458 1;