Files
Chronos/tests/Titano.Core.Tests/Packaging/PayloadIntegrityTests.cs
T
Claude ee1ba9a4ad test(packaging): cover malformed manifests with a valid hash
Invalid JSON, missing or null required fields, an unknown format version, an
unsafe product name and an empty component list are all reported as corrupt.

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

227 lines
11 KiB
C#

using System.Buffers.Binary;
using System.IO.Compression;
using Titano.Core.Packaging;
using Titano.Testing;
namespace Titano.Core.Tests.Packaging;
public sealed class PayloadIntegrityTests(TestContext context)
{
private readonly PackagingFixture _fx = new(context);
private (string Installer, long PayloadOffset, byte[] Bytes) PackSample()
{
var app = _fx.Folder("app",
("Titano.exe", PackagingFixture.Text("program ", 3000)),
("noise.bin", PackagingFixture.Random(40_000, 5)),
("docs/readme.txt", PackagingFixture.Text("read me ", 200)));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)));
using var reader = PayloadReader.Open(installer);
return (installer, reader.PayloadOffset, File.ReadAllBytes(installer));
}
[Test]
public void TamperedManifestIsRejected()
{
var (installer, offset, bytes) = PackSample();
// Flip the first letter of "Titano" in "product":"Titano".
var at = Array.IndexOf(bytes, (byte)'T', (int)offset);
bytes[at] = (byte)'X';
File.WriteAllBytes(installer, bytes);
var ex = Assert.Throws<PayloadException>(() => PayloadReader.Open(installer));
Assert.Equal(PayloadError.Corrupt, ex.Error);
Assert.Contains("SHA-256", ex.Message);
}
[Test]
public void TamperedFooterHashIsRejected()
{
var (installer, _, bytes) = PackSample();
bytes[^1] ^= 0x5A;
File.WriteAllBytes(installer, bytes);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void FooterPointingOutsideTheFileIsRejected()
{
var (installer, _, bytes) = PackSample();
BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(bytes.Length - PayloadFormat.FooterLength + 16), long.MaxValue - 3);
File.WriteAllBytes(installer, bytes);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void CorruptStoredEntryFailsItsHash()
{
var (installer, _, bytes) = PackSample();
PayloadFile noise;
long dataOffset;
using (var reader = PayloadReader.Open(installer))
{
noise = reader.Manifest.Files.Single(f => f.Path == "noise.bin");
dataOffset = DataOffset(bytes, reader.PayloadOffset);
}
Assert.Equal(PayloadCompression.Stored, noise.Compression);
bytes[dataOffset + noise.Offset + 1234] ^= 0xFF;
File.WriteAllBytes(installer, bytes);
using var tampered = PayloadReader.Open(installer);
var ex = Assert.Throws<PayloadException>(() => tampered.Extract([noise], context.CreateTempDirectory()));
Assert.Equal(PayloadError.Corrupt, ex.Error);
Assert.Contains("noise.bin", ex.Message);
}
[Test]
public void EveryCorruptPayloadByteIsDetectedOrHarmless()
{
var (installer, offset, original) = PackSample();
var expected = new Dictionary<string, byte[]>
{
["Titano.exe"] = PackagingFixture.Text("program ", 3000),
["noise.bin"] = PackagingFixture.Random(40_000, 5),
["docs/readme.txt"] = PackagingFixture.Text("read me ", 200),
};
var step = Math.Max(1, (int)((original.Length - offset) / 150));
for (var at = offset; at < original.Length; at += step)
{
var bytes = (byte[])original.Clone();
bytes[at] ^= 0xFF;
File.WriteAllBytes(installer, bytes);
var target = context.CreateTempDirectory("fuzz");
try
{
using var reader = PayloadReader.Open(installer);
reader.Extract(reader.Manifest.Files, target);
foreach (var (path, content) in expected)
Assert.BytesEqual(content, File.ReadAllBytes(Path.Combine(target, path.Replace('/', Path.DirectorySeparatorChar))), $"flip at {at} produced wrong {path}");
}
catch (PayloadException)
{
// Detected: the expected outcome for almost every byte.
}
}
}
[Test]
public void TruncatedInstallersFailCleanly()
{
var (installer, _, original) = PackSample();
var lengths = new List<int> { 0, 1, 7, PayloadFormat.FooterLength - 1, PayloadFormat.FooterLength, original.Length - 1, original.Length - PayloadFormat.FooterLength };
for (var n = 97; n < original.Length; n += original.Length / 60) lengths.Add(n);
foreach (var length in lengths)
{
File.WriteAllBytes(installer, original.AsSpan(0, length).ToArray());
var ex = Assert.Throws<PayloadException>(() => PayloadReader.Open(installer), $"truncated to {length}");
Assert.True(ex.Error is PayloadError.NotFound or PayloadError.Corrupt, $"truncated to {length}: {ex.Error}");
}
}
[Test]
public void MissingFileIsReportedAsNotFound() =>
Assert.Equal(PayloadError.NotFound, Assert.Throws<PayloadException>(() => PayloadReader.Open(Path.Combine(_fx.Root, "nope.exe"))).Error);
[Theory]
[Case("../evil.txt")]
[Case("a/../../evil.txt")]
[Case("/etc/passwd")]
[Case("C:/Windows/evil.dll")]
[Case("sub\\evil.txt")]
[Case("file.txt:stream")]
public void ManifestPathEscapingTheTargetIsRejected(string path)
{
var content = PackagingFixture.Text("x");
var manifest = new PayloadManifest
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano", DefaultSelected = true, EstimatedSize = 1 }],
Files = [new PayloadFile { Path = path, Component = "Titano", Size = 1, Sha256 = PackagingFixture.Sha256(content), Compression = PayloadCompression.Stored, Offset = 0, Length = 1 }],
};
var installer = _fx.Craft(manifest, content);
Assert.Equal(PayloadError.UnsafePath, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Theory]
[Case("not json at all")]
[Case("{\"formatVersion\":1,\"version\":\"1.0\"}")]
[Case("{\"formatVersion\":1,\"product\":null,\"version\":\"1.0\"}")]
[Case("{\"formatVersion\":2,\"product\":\"Titano\",\"version\":\"1.0\",\"components\":[{\"id\":\"Titano\",\"displayName\":\"Titano\"}]}")]
[Case("{\"formatVersion\":1,\"product\":\"..\",\"version\":\"1.0\",\"components\":[{\"id\":\"Titano\",\"displayName\":\"Titano\"}]}")]
[Case("{\"formatVersion\":1,\"product\":\"Titano\",\"version\":\"1.0\",\"components\":[]}")]
public void MalformedManifestWithMatchingHashIsCorrupt(string json)
{
var installer = _fx.Craft(System.Text.Encoding.UTF8.GetBytes(json), []);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void DeclaredSizeBeyondTheDeflateLimitIsRejectedUpFront()
{
var manifest = new PayloadManifest
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }],
Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1L << 40, Sha256 = new string('0', 64), Compression = PayloadCompression.Deflate, Offset = 0, Length = 16 }],
};
var installer = _fx.Craft(manifest, new byte[16]);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void EntryInflatingPastItsDeclaredSizeStopsAtTheLimit()
{
var zeros = new byte[4 << 20];
using var compressed = new MemoryStream();
using (var deflate = new DeflateStream(compressed, CompressionLevel.SmallestSize, leaveOpen: true)) deflate.Write(zeros);
var data = compressed.ToArray();
var manifest = new PayloadManifest
{
Product = "Titano",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Titano", DisplayName = "Titano" }],
Files = [new PayloadFile { Path = "bomb.bin", Component = "Titano", Size = 1000, Sha256 = PackagingFixture.Sha256(new byte[1000]), Compression = PayloadCompression.Deflate, Offset = 0, Length = data.Length }],
};
using var reader = PayloadReader.Open(_fx.Craft(manifest, data));
var target = context.CreateTempDirectory();
var ex = Assert.Throws<PayloadException>(() => reader.Extract(reader.Manifest.Files, target));
Assert.Contains("larger", ex.Message);
Assert.True(new FileInfo(Path.Combine(target, "bomb.bin")).Length <= 1000);
}
[Test]
public void SignedStubLosesItsSignatureAndSignedInstallerStillOpens()
{
var stubBytes = PackagingFixture.PortableExecutable(5000, certificate: PackagingFixture.Random(1500, 9));
var stub = Path.Combine(_fx.Root, "signed-stub.exe");
File.WriteAllBytes(stub, stubBytes);
var app = _fx.Folder("app", ("Titano.exe", PackagingFixture.Text("app", 50)));
var installer = _fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Titano", "Titano", true, app)));
var packed = File.ReadAllBytes(installer);
var entry = PackagingFixture.SecurityDirectoryOffset(packed);
Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(packed.AsSpan(entry)), "stub signature directory cleared");
// Sign the whole installer the way signtool does, then read it back.
File.WriteAllBytes(installer, PackagingFixture.Sign(packed, PackagingFixture.Random(2048, 4)));
using var reader = PayloadReader.Open(installer);
Assert.Equal((long)(stubBytes.Length - 1500), reader.PayloadOffset);
var target = context.CreateTempDirectory();
reader.Extract(reader.Manifest.Files, target);
Assert.BytesEqual(PackagingFixture.Text("app", 50), File.ReadAllBytes(Path.Combine(target, "Titano.exe")));
var copy = Path.Combine(target, "Uninstall Titano.exe");
reader.WriteStub(copy);
var copied = File.ReadAllBytes(copy);
Assert.Equal(reader.PayloadOffset, (long)copied.Length);
Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(copied.AsSpan(entry)), "uninstaller signature directory cleared");
}
private static long DataOffset(byte[] installer, long payloadOffset)
{
var footer = installer.AsSpan(installer.Length - PayloadFormat.FooterLength);
return payloadOffset + BinaryPrimitives.ReadInt64LittleEndian(footer[16..]);
}
}