using System.Buffers.Binary; using System.Diagnostics; using System.Text; using Triforce.Core.GameFiles; using Triforce.Logic; using static Triforce.LogicTests.T; namespace Triforce.LogicTests; /// ((Triforce, 11-26) The launcher's security and edge-case audit: what a crafted or damaged input, a server that sends /// more than it says, or a name the launcher did not expect now does (refused with a reason, never a crash or a lost file). static partial class Tests { // ---------------- names and numbers from folders and output ---------------- static void HardeningNames() { // (a mods folder whose number is in another script's digits: a name, not a crash that empties the Mods page) var (_, num, name) = Mods.Parse("01-Skins"); Equal(null, num, "full-width digits are no number"); Equal("01-Skins", name, "the name whole"); Equal(1, Mods.Parse("-01-Skins").Number, "ASCII digits still are"); // (the build's step times: a number too large for an int is no time, not an exception in the output reader) var steps = BuildProtocol.ParseSteps("x 99999999999:00, read 1:32"); Check(!steps.ContainsKey("x") && steps["read"] == 92, "an overlong number left out, the rest read"); // (the benchmark's verdict is HTML on the page: a place's name from the results file is encoded) Check(Benchmark.SkippedNote(new[] { "" }).Contains("<img src=x>"), "a place's name encoded"); // (release notes: a long line of [ no longer takes quadratic time) var sw = Stopwatch.StartNew(); ReleaseNotes.Plain(new string('[', 60000)); Check(sw.Elapsed < TimeSpan.FromSeconds(2), "a long line of [ read in " + sw.ElapsedMilliseconds + " ms"); // (names only the launcher makes beside a save folder: a player's own ".old" is never taken for its) Check(Partial.Suffix == ".triforce-partial" && Partial.Aside == ".triforce-old", "the launcher's own names"); Check(Uninstaller.OwnFolders.Contains(Randomizer.WorkFolder), "the randomizer's folder goes with an uninstall"); var root = NewRoot("hardening-names"); Check(new Ootrr(Ctx(root)).Folder.StartsWith(Path.Combine(Ctx(root).Home, Randomizer.WorkFolder), StringComparison.OrdinalIgnoreCase), "OOTRR lives in the randomizer's folder, not in tools (which a tools update replaces whole)"); } // ---------------- downloads ---------------- static async Task HardeningDownloads() { using var s = new FakeServer(); var root = NewRoot("hardening-downloads"); var ctx = Ctx(root); using var http = Downloader.CreateHttp(); var d = new Downloader(ctx); // (an address that is not https is not fetched; a test's own 127.0.0.1 server only in a test run) var plain = Path.Combine(root, "plain.bin"); await ThrowsAsync(() => d.ToFileAsync(http, "http://example.invalid/x.zip", plain, 0, null, CancellationToken.None), "plain http refused"); Equal(0, s.Requests, "nothing asked of any server"); // (no size listed: the most it may be; a server that offers more is refused, nothing kept) s.Add("/big", new byte[100_000]); var big = Path.Combine(root, "big.bin"); var e = await ThrowsAsync(() => d.ToFileAsync(http, s.Url + "/big", big, 0, null, CancellationToken.None, most: 50_000), "more than the most"); Check(e.Message.Contains("more than"), "said: " + e.Message); Check(!File.Exists(big) && !File.Exists(big + ".part"), "nothing of it kept"); await d.ToFileAsync(http, s.Url + "/big", big, 0, null, CancellationToken.None, most: 200_000); Equal(100_000L, new FileInfo(big).Length, "within the most: downloaded"); // (a JSON answer read whole, but no more than its limit once unpacked) await ThrowsAsync(() => Downloader.TextAsync(new ByteArrayContent(new byte[5000]), 4000, CancellationToken.None), "an answer over its limit"); Equal("{\"a\":1}", await Downloader.TextAsync(new StringContent("{\"a\":1}"), 4000, CancellationToken.None), "an answer within it"); } // ---------------- files the launcher changes ---------------- static void HardeningFiles() { var root = NewRoot("hardening-files"); // (the benchmark's settings: every line of a key set, the file's bytes and line ends kept) var ini = Path.Combine(root, "triforce_options.ini"); File.WriteAllBytes(ini, Encoding.Latin1.GetBytes("a=1\r\nb=2\r\na=3\r\nname=café\r\n")); BenchIni.Set(ini, new Dictionary { ["a"] = 9, ["c"] = 4 }); Equal("a=9\r\nb=2\r\na=9\r\nname=café\r\nc=4\r\n", Encoding.Latin1.GetString(File.ReadAllBytes(ini)), "both a lines, CRLF and the byte 0xE9 kept, c added"); var back = Path.Combine(root, "backup.ini"); File.WriteAllText(back, "x=1\n"); BenchIni.Restore(back, ini); Check(File.ReadAllText(ini) == "x=1\n" && !File.Exists(ini + ".new"), "put back in one step"); // (the texture pack's Remove: its own pictures and list go; what else a player keeps there stays) var game = Path.Combine(root, "game"); var pack = TexturePack.Folder(game); Directory.CreateDirectory(Path.Combine(pack, "mine")); File.WriteAllText(Path.Combine(pack, "0123456789abcdef.png"), "p"); File.WriteAllText(Path.Combine(pack, "0123456789abcdef_m1.png.new"), "p"); File.WriteAllText(Path.Combine(pack, TexturePack.StateName), "{}"); File.WriteAllText(Path.Combine(pack, "notes.txt"), "mine"); File.WriteAllText(Path.Combine(pack, "mine", "x.png"), "mine"); new TexturePack(Ctx(root)).Remove(game); Check(!File.Exists(Path.Combine(pack, "0123456789abcdef.png")) && !File.Exists(Path.Combine(pack, TexturePack.StateName)) && !File.Exists(Path.Combine(pack, "0123456789abcdef_m1.png.new")), "the pack's files gone"); Check(File.Exists(Path.Combine(pack, "notes.txt")) && File.Exists(Path.Combine(pack, "mine", "x.png")), "the player's files kept"); Directory.Delete(Path.Combine(pack, "mine"), true); File.Delete(Path.Combine(pack, "notes.txt")); File.WriteAllText(Path.Combine(pack, "0123456789abcdef.png"), "p"); new TexturePack(Ctx(root)).Remove(game); Check(!Directory.Exists(pack), "nothing else in it: the folder goes"); } // ---------------- game files that are damaged or made to harm ---------------- static void HardeningParsers() { // (a texture archive that names 131072 textures in a few bytes: refused at once, not 17 GB of names) var bntx = new byte[0x40]; "BNTX"u8.CopyTo(bntx); BinaryPrimitives.WriteUInt32LittleEndian(bntx.AsSpan(0x24), 131072); BinaryPrimitives.WriteUInt64LittleEndian(bntx.AsSpan(0x28), 0x30); var sw = Stopwatch.StartNew(); Throws(() => new Bntx(bntx), "a texture table larger than the file"); // (two entries that point at one texture: refused) var twice = new byte[0x200]; "BNTX"u8.CopyTo(twice); BinaryPrimitives.WriteUInt32LittleEndian(twice.AsSpan(0x24), 2); BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x28), 0x30); BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x30), 0x80); BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x38), 0x80); "BRTI"u8.CopyTo(twice.AsSpan(0x80)); BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x80 + 0x60), 0x180); Throws(() => new Bntx(twice), "one texture named twice"); // (a texture name longer than a name is) BinaryPrimitives.WriteUInt32LittleEndian(twice.AsSpan(0x24), 1); BinaryPrimitives.WriteUInt16LittleEndian(twice.AsSpan(0x180), 0xFFFF); Throws(() => new Bntx(twice), "a 64K-character name"); Check(sw.Elapsed < TimeSpan.FromSeconds(2), "refused at once: " + sw.ElapsedMilliseconds + " ms"); // (a zstd frame that unpacks to more than it may: refused, whether it says its size or not) var frame = new ZstdSharp.Compressor().Wrap(new byte[100_000]).ToArray(); Throws(() => Zs.Decompress(frame, null, 10_000), "a frame that says it is larger than the most"); Equal(100_000, Zs.Decompress(frame, null).Length, "within the most: unpacked"); // (a texture's sizes from its header, checked before anything is allocated) Throws(() => ImageLimits.Check(0, 16), "no width"); Throws(() => ImageLimits.Check(70000, 16), "wider than any texture"); Throws(() => BlockCompression.Decode(new byte[64], 40000, 40000, BlockCompression.Kind.BC1), "a BC1 texture of 40000 x 40000"); Throws(() => BlockLinear.Deswizzle(new byte[64], 16384, 32767, 4, 0), "a 2 GB deswizzle from a 64-byte texture"); } }