| 1 | use strict; |
| 2 | use warnings; |
| 3 | use File::Temp qw(tempdir); |
| 4 | use POSIX qw(_exit WNOHANG); |
| 5 | use Socket qw(AF_UNIX SOCK_STREAM PF_UNSPEC); |
| 6 | |
| 7 | |
| 8 | |
| 9 | umask 077; |
| 10 | my $tmp = tempdir('cage-check-XXXXXXXX', DIR => '/private/var/tmp', CLEANUP => 0); |
| 11 | my $source = "$tmp/source"; |
| 12 | my $mount = "$tmp/mount"; |
| 13 | my @children; |
| 14 | my $attached = ''; |
| 15 | sub mounted_line { |
| 16 | open my $list, '-|', '/sbin/mount' or die "mount list"; |
| 17 | my @matches = grep { index($_, " on $mount (") >= 0 } <$list>; |
| 18 | close $list or die "mount list"; |
| 19 | die "ambiguous mount" if @matches > 1; |
| 20 | return $matches[0] // ''; |
| 21 | } |
| 22 | sub spawn_peer { |
| 23 | my ($side, $other, @cmd) = @_; |
| 24 | my $pid = fork(); |
| 25 | die "fork" unless defined $pid; |
| 26 | return $pid if $pid; |
| 27 | close $other; |
| 28 | open STDIN, '<&', $side or _exit(125); |
| 29 | open STDOUT, '>&', $side or _exit(125); |
| 30 | open STDERR, '>', '/dev/null' or _exit(125); |
| 31 | close $side; |
| 32 | exec @cmd or _exit(126); |
| 33 | } |
| 34 | my $ok = eval { |
| 35 | local $SIG{TERM} = local $SIG{HUP} = local $SIG{INT} = sub { die "cancelled" }; |
| 36 | mkdir $source, 0700 or die "source"; |
| 37 | mkdir $mount, 0700 or die "target"; |
| 38 | socketpair(my $a,my $b,AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair"; |
| 39 | push @children, spawn_peer($a,$b,'/usr/libexec/sftp-server','-R','-d',$source); |
| 40 | push @children, spawn_peer($b,$a,'/usr/local/libexec/cage-sshfs',":$source",$mount,'-f','-o','slave,ro,quiet,backend=fskit,nodev,nosuid,dir_cache=no'); |
| 41 | close $a; close $b; |
| 42 | for (1..35) { |
| 43 | $attached = mounted_line(); |
| 44 | last if $attached; |
| 45 | last unless kill 0, $children[1]; |
| 46 | select undef,undef,undef,0.2; |
| 47 | } |
| 48 | my $user = getpwuid($<); |
| 49 | my ($flags) = $attached =~ m{^macfuse://[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12} on \Q$mount\E \(macfuse, ([^\n]+)\)\s*$}i; |
| 50 | my %options = map { $_ => 1 } split /, /, ($flags // ''); |
| 51 | die "unexpected mount" unless $options{'fskit'} && $options{'read-only'} && $options{"mounted by $user"}; |
| 52 | 1; |
| 53 | }; |
| 54 | |
| 55 | my $live = mounted_line(); |
| 56 | if ($ok && $live && $live eq $attached) { |
| 57 | $ok = 0 unless system('/sbin/umount','-f',$mount) == 0; |
| 58 | } |
| 59 | for my $pid (@children) { |
| 60 | if (waitpid($pid,WNOHANG)==0) {kill 'TERM',$pid} |
| 61 | } |
| 62 | select undef,undef,undef,0.15; |
| 63 | for my $pid (@children) { |
| 64 | if (waitpid($pid,WNOHANG)==0) {kill 'KILL',$pid;waitpid($pid,0)} |
| 65 | } |
| 66 | $ok = 0 if mounted_line(); |
| 67 | $ok = 0 unless rmdir $mount; |
| 68 | $ok = 0 unless rmdir $source; |
| 69 | $ok = 0 unless rmdir $tmp; |
| 70 | exit($ok ? 0 : 1); |