| 1 | |
| 2 | use strict; |
| 3 | use warnings; |
| 4 | use JSON::PP; |
| 5 | use Digest::SHA; |
| 6 | use Fcntl qw(:DEFAULT); |
| 7 | |
| 8 | my ($mode, $manifest_path, $kit) = @ARGV; |
| 9 | die "Invalid component operation\n" unless defined($mode) && $mode =~ /^(source|targets|verify|publish)$/; |
| 10 | open(my $input, '<', $manifest_path) or die "Component manifest unavailable\n"; |
| 11 | local $/; |
| 12 | my $encoded = <$input>; |
| 13 | close($input); |
| 14 | die "Component manifest too large\n" if length($encoded) > 4 * 1024 * 1024; |
| 15 | my $manifest = decode_json($encoded); |
| 16 | die "Invalid component manifest\n" unless $manifest->{protocol} == 1 && $manifest->{system} eq 'macos' && ref($manifest->{files}) eq 'ARRAY' && $manifest->{revision} =~ /^[a-f0-9]{64}$/; |
| 17 | for my $entry (@{$manifest->{files}}) { |
| 18 | my ($source, $target) = ($entry->{source}, $entry->{target} // ''); |
| 19 | die "Invalid component source\n" unless defined($source) && $source !~ m{(?:^/|(?:^|/)\.\.?(?:/|$)|[\x00\r\n])}; |
| 20 | die "Invalid component target\n" if $target ne '' && ($target !~ m{^/(?:Applications/Cage[^/]*\.app/|usr/local/libexec/cage-)} || $target =~ m{(?:^|/)\.\.?(?:/|$)|[\x00\r\n]}); |
| 21 | die "Invalid component digest\n" unless $entry->{sha256} =~ /^[a-f0-9]{64}$/ && $entry->{installed_sha256} =~ /^[a-f0-9]{64}$/; |
| 22 | if ($mode eq 'targets') { print "$source\0$target\0" if $target ne ''; next; } |
| 23 | next if $mode ne 'source' && $target eq ''; |
| 24 | my $path = $mode eq 'source' ? "$kit/$source" : $target; |
| 25 | open(my $file, '<', $path) or die "Missing component $path\n"; |
| 26 | binmode($file); |
| 27 | my $actual = Digest::SHA->new(256)->addfile($file)->hexdigest; |
| 28 | close($file); |
| 29 | my $expected = $mode eq 'source' ? $entry->{sha256} : $entry->{installed_sha256}; |
| 30 | die "Component digest mismatch $path\n" unless $actual eq $expected; |
| 31 | } |
| 32 | if ($mode eq 'publish') { |
| 33 | die "Component publication requires administrator\n" unless $> == 0; |
| 34 | my $target = '/var/db/cage-components.json'; |
| 35 | die "Invalid existing component receipt\n" if -l $target || (-e $target && !-f $target); |
| 36 | my $temporary = "$target.$$"; |
| 37 | sysopen(my $output, $temporary, O_WRONLY | O_CREAT | O_EXCL, 0644) or die "Cannot stage component receipt\n"; |
| 38 | print $output $encoded or die "Cannot write component receipt\n"; |
| 39 | close($output) or die "Cannot close component receipt\n"; |
| 40 | rename($temporary, $target) or die "Cannot publish component receipt\n"; |
| 41 | } |