Files
Chronos/src/Titano.Core/Packaging/PayloadReader.cs
T
Claude d79ab1e41b feat(packaging): add TPK1 self-extracting payload format
Installer payload appended to the setup program: JSON manifest (components,
files with size/SHA-256/offsets/mtime, shortcuts, file types) plus deflate or
stored entries and a 64-byte footer with the manifest hash. The reader finds
the footer before an Authenticode table, validates every offset, rejects
unsafe paths and bounds inflation by the declared size; the writer is
deterministic, deduplicates identical content and strips a signed stub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 09:56:37 +00:00

236 lines
10 KiB
C#

using System.Buffers;
using System.IO.Compression;
using System.Security.Cryptography;
namespace Titano.Core.Packaging;
/// <summary>Extraction progress: bytes written so far, total bytes, and the file being written.</summary>
public readonly record struct PayloadProgress(long Done, long Total, string CurrentPath);
/// <summary>
/// Reads a TPK1 payload from the end of an installer. Opening validates the footer, the manifest SHA-256 and every
/// manifest offset; extraction verifies each file's SHA-256 and never writes more bytes than the manifest declares.
/// </summary>
public sealed class PayloadReader : IDisposable
{
private const int BufferSize = 1 << 16;
private readonly FileStream _stream;
private readonly long _dataOffset;
private PayloadReader(string path, FileStream stream)
{
ArchivePath = path;
_stream = stream;
var footerOffset = LocateFooter(stream, out var footer);
var (payloadOffset, manifestLength, dataLength) = (footer.PayloadOffset, footer.ManifestLength, footer.DataLength);
if (payloadOffset < 0 || manifestLength <= 0 || manifestLength > PayloadFormat.MaxManifestLength || dataLength < 0
|| payloadOffset > footerOffset || manifestLength > footerOffset - payloadOffset
|| dataLength > footerOffset - payloadOffset - manifestLength)
throw Corrupt("The installer footer points outside the file.");
if (footerOffset - payloadOffset - manifestLength - dataLength >= PayloadFormat.Alignment)
throw Corrupt("The installer has unexpected bytes before its footer.");
var manifestBytes = new byte[manifestLength];
stream.Position = payloadOffset;
stream.ReadExactly(manifestBytes);
if (!SHA256.HashData(manifestBytes).AsSpan().SequenceEqual(footer.ManifestHash))
throw Corrupt("The installer manifest does not match its SHA-256.");
Manifest = PayloadManifest.Parse(manifestBytes);
Manifest.Validate(dataLength);
PayloadOffset = payloadOffset;
_dataOffset = payloadOffset + manifestLength;
}
/// <summary>The installer file the payload was read from.</summary>
public string ArchivePath { get; }
/// <summary>Absolute offset where the payload starts; the bytes before it are the setup program.</summary>
public long PayloadOffset { get; }
public PayloadManifest Manifest { get; }
/// <summary>Opens the payload appended to the running executable.</summary>
public static PayloadReader OpenCurrentProcess() =>
Open(Environment.ProcessPath ?? throw new PayloadException(PayloadError.NotFound, "The setup program path is unknown."));
/// <summary>Opens and validates the payload of <paramref name="path"/>.</summary>
public static PayloadReader Open(string path)
{
FileStream stream;
try
{
stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.RandomAccess);
}
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
throw new PayloadException(PayloadError.NotFound, $"'{path}' does not exist.", ex);
}
try
{
return new PayloadReader(path, stream);
}
catch (IOException ex)
{
stream.Dispose();
throw Corrupt("The installer could not be read to the end.", ex);
}
catch
{
stream.Dispose();
throw;
}
}
/// <summary>
/// Writes every file of <paramref name="files"/> under <paramref name="directory"/>, verifying sizes and hashes.
/// The directory should be a fresh staging folder: on failure it holds partial output the caller discards.
/// </summary>
public void Extract(IReadOnlyList<PayloadFile> files, string directory, IProgress<PayloadProgress>? progress = null, CancellationToken cancellationToken = default)
{
long total = 0;
foreach (var f in files) total += f.Size;
long done = 0;
var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
try
{
foreach (var file in files)
{
cancellationToken.ThrowIfCancellationRequested();
progress?.Report(new PayloadProgress(done, total, file.Path));
var target = PayloadPath.Resolve(directory, file.Path);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
ExtractOne(file, target, buffer, ref done, total, progress, cancellationToken);
}
progress?.Report(new PayloadProgress(done, total, string.Empty));
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
/// <summary>
/// Writes the setup program alone: the bytes before the payload, with the signature directory cleared because
/// the installer's signature covered the payload as well. Used for the uninstaller copy.
/// </summary>
public void WriteStub(string destinationPath)
{
using var output = new FileStream(destinationPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, BufferSize);
_stream.Position = 0;
CopyExactly(_stream, output, PayloadOffset);
PeImage.ClearCertificateDirectory(output);
output.Flush(flushToDisk: true);
}
public void Dispose() => _stream.Dispose();
private void ExtractOne(PayloadFile file, string target, byte[] buffer, ref long done, long total, IProgress<PayloadProgress>? progress, CancellationToken cancellationToken)
{
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize))
{
var window = new WindowStream(_stream, _dataOffset + file.Offset, file.Length);
using var input = file.Compression == PayloadCompression.Deflate ? new DeflateStream(window, CompressionMode.Decompress) : (Stream)window;
long written = 0;
var lastReport = 0L;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
int read;
try
{
read = input.Read(buffer, 0, buffer.Length);
}
catch (InvalidDataException ex)
{
throw Corrupt($"'{file.Path}' is damaged in the installer.", ex);
}
if (read == 0) break;
// Never write past the declared size: a crafted entry cannot inflate beyond what the manifest promised.
if (read > file.Size - written) throw Corrupt($"'{file.Path}' is larger than the installer declares.");
output.Write(buffer, 0, read);
hash.AppendData(buffer, 0, read);
written += read;
done += read;
if (progress is not null && written - lastReport >= 4 << 20)
{
lastReport = written;
progress.Report(new PayloadProgress(done, total, file.Path));
}
}
if (written != file.Size) throw Corrupt($"'{file.Path}' is shorter than the installer declares.");
output.Flush(flushToDisk: true);
}
if (!Convert.ToHexStringLower(hash.GetHashAndReset()).Equals(file.Sha256, StringComparison.Ordinal))
throw Corrupt($"'{file.Path}' does not match its SHA-256.");
File.SetLastWriteTimeUtc(target, FromUnixSeconds(file.ModifiedUnixSeconds));
}
/// <summary>True when <paramref name="stream"/> ends with a TPK1 footer (an installer must not become another one's stub).</summary>
internal static bool HasFooter(FileStream stream)
{
try
{
LocateFooter(stream, out _);
return true;
}
catch (PayloadException)
{
return false;
}
finally
{
stream.Position = 0;
}
}
/// <summary>Finds the footer just before the end of the content (the file end, or the start of a signature).</summary>
private static long LocateFooter(FileStream stream, out PayloadFooter footer)
{
var end = PeImage.ContentEnd(stream);
if (end < PayloadFormat.FooterLength) throw new PayloadException(PayloadError.NotFound, "The file is too small to hold an installer payload.");
// signtool may zero-pad up to 7 bytes before the certificate table; the packer aligns, but accept either.
var tailLength = (int)Math.Min(end, PayloadFormat.FooterLength + PayloadFormat.Alignment - 1);
var tail = new byte[tailLength];
stream.Position = end - tailLength;
stream.ReadExactly(tail);
for (var pad = 0; pad < PayloadFormat.Alignment && pad + PayloadFormat.FooterLength <= tailLength; pad++)
{
var start = tailLength - pad - PayloadFormat.FooterLength;
if (tail.AsSpan(tailLength - pad).ContainsAnyExcept((byte)0)) break;
if (PayloadFooter.TryParse(tail.AsSpan(start, PayloadFormat.FooterLength), out footer)) return end - pad - PayloadFormat.FooterLength;
}
throw new PayloadException(PayloadError.NotFound, "The file carries no installer payload.");
}
private static void CopyExactly(Stream source, Stream destination, long count)
{
var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
try
{
while (count > 0)
{
var read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, count));
if (read == 0) throw Corrupt("The setup program is truncated.");
destination.Write(buffer, 0, read);
count -= read;
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private static DateTime FromUnixSeconds(long seconds)
{
// File times start in 1601; clamp to a range every file system accepts.
const long min = 315532800; // 1980-01-01
const long max = 253402300799; // 9999-12-31
return DateTime.UnixEpoch.AddSeconds(Math.Clamp(seconds, min, max));
}
private static PayloadException Corrupt(string message, Exception? inner = null) => new(PayloadError.Corrupt, message, inner);
}