SPB Git

Repository Public BSD-3-Clause

FuzzTests.swift 14.5 KB 268 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXMapPackage/Tests/ORIXMapPackageTests/FuzzTests.swift10// Module           : ORIXMapPackageTests11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import CryptoKit89import Foundation90import Testing91@testable import ORIXMapPackage9293/// Mutates valid packages and feeds random bytes to every parser of external data. The only acceptable outcomes94/// are success or a typed error: no crash, no hang, and no file created outside the staging directory.95@Suite struct FuzzTests {96    let key = Curve25519.Signing.PrivateKey()97    static let allowedNames: Set<String> = ["map.pmtiles", "search.sqlite", "routing.orixgraph", "terrain.pmtiles", "manifest.json", "manifest.sig"]9899    /// Verifies and extracts one candidate. Returns true when it was accepted.100    func attempt(_ data: Data, sandbox: URL, verifier: PackageVerifier, index: Int) -> Bool {101        let input = sandbox.appendingPathComponent("in/candidate.orixmap")102        try! data.write(to: input)103        let out = sandbox.appendingPathComponent("staging/install-\(index)")104        var accepted = false105        do {106            _ = try verifier.extract(input, into: out)107            accepted = true108            let names = Set(try! FileManager.default.contentsOfDirectory(atPath: out.path))109            #expect(names.isSubset(of: Self.allowedNames), "unexpected files \(names)")110            try! FileManager.default.removeItem(at: out)111        } catch {112            // `extract` has typed throws: reaching this point means a `PackageError`.113            let _: PackageError = error114            #expect(!FileManager.default.fileExists(atPath: out.path), "failed extraction left files")115        }116        // verify() must agree with extract().117        let verified = (try? verifier.verify(at: input)) != nil118        #expect(verified == accepted)119        return accepted120    }121122    func makeSandbox() -> TempDir {123        let sandbox = TempDir("fuzz")124        try! FileManager.default.createDirectory(at: sandbox.file("in"), withIntermediateDirectories: true)125        try! FileManager.default.createDirectory(at: sandbox.file("staging"), withIntermediateDirectories: true)126        return sandbox127    }128129    func expectNothingEscaped(_ sandbox: TempDir) {130        #expect(listTree(sandbox.url) == ["in", "in/candidate.orixmap", "staging"], "files outside the staging directory")131    }132133    @Test func byteMutationsOfAValidPackage() throws {134        let sandbox = makeSandbox()135        let seed = UInt64.random(in: 1...UInt64.max)136        var rng = SeededGenerator(seed: seed)137        let source = TempDir("fuzz-src")138        let base = try Data(contentsOf: Fixture.makePackage(in: source.url, sizes: [(.map, 3000), (.search, 1200), (.routing, 5000)], key: key).url)139        let header = try PackageHeader.parse(base)140        let verifier = PackageVerifier(trustStore: Fixture.trust(key))141        var accepted = 0142        let iterations = 4000143        for i in 0..<iterations {144            var d = base145            switch Int.random(in: 0..<8, using: &rng) {146            case 0:     // flip bits in the header147                for _ in 0..<Int.random(in: 1...4, using: &rng) { d[Int.random(in: 0..<64, using: &rng)] ^= UInt8.random(in: 1...255, using: &rng) }148            case 1:     // flip bits in the preamble149                for _ in 0..<Int.random(in: 1...6, using: &rng) { d[Int.random(in: 0..<Int(header.preambleLength), using: &rng)] ^= UInt8.random(in: 1...255, using: &rng) }150            case 2:     // flip bits anywhere151                for _ in 0..<Int.random(in: 1...8, using: &rng) { d[Int.random(in: 0..<d.count, using: &rng)] ^= UInt8.random(in: 1...255, using: &rng) }152            case 3:     // truncate153                d = d.prefix(Int.random(in: 0..<d.count, using: &rng))154            case 4:     // extend155                d.append(pseudoRandomData(Int.random(in: 1...9000, using: &rng), seed: rng.next()))156            case 5:     // overwrite a header integer with an extreme value157                let field = [8, 10, 12, 16, 20, 24, 28, 40].randomElement(using: &rng)!158                let values: [UInt64] = [0, 1, 63, 64, 65, 4095, 4096, 4097, 0x7FFF_FFFF, 0xFFFF_FFFF, 0x1_0000_0000, UInt64.max, UInt64.max - 4095, 1 << 62]159                let v = values.randomElement(using: &rng)!160                let width = field == 40 ? 8 : (field < 12 || field == 24 ? 2 : 4)161                for b in 0..<width { d[field + b] = UInt8(truncatingIfNeeded: v >> (8 * UInt64(b))) }162            case 6:     // splice a random block163                let start = Int.random(in: 0..<d.count, using: &rng)164                let length = min(d.count - start, Int.random(in: 1...300, using: &rng))165                d.replaceSubrange(start..<(start + length), with: pseudoRandomData(Int.random(in: 0...300, using: &rng), seed: rng.next()))166            default:    // duplicate or drop a block167                let start = Int.random(in: 0..<d.count, using: &rng)168                let length = min(d.count - start, Int.random(in: 1...5000, using: &rng))169                if Bool.random(using: &rng) { d.insert(contentsOf: d.subdata(in: start..<(start + length)), at: start) } else { d.removeSubrange(start..<(start + length)) }170            }171            if attempt(d, sandbox: sandbox.url, verifier: verifier, index: i) { accepted += 1 }172        }173        expectNothingEscaped(sandbox)174        // Only mutations confined to ignored header fields (minor version, flags, reserved bytes) can be accepted.175        #expect(accepted < iterations / 4, "seed \(seed): \(accepted) mutated packages accepted")176    }177178    @Test func signedManifestMutations() throws {179        // The attacker here holds a trusted key (or the builder is buggy): the signature always verifies, so every180        // structural check after it is exercised.181        let sandbox = makeSandbox()182        let seed = UInt64.random(in: 1...UInt64.max)183        var rng = SeededGenerator(seed: seed)184        let source = TempDir("fuzz-src")185        let base = try Data(contentsOf: Fixture.makePackage(in: source.url, sizes: [(.map, 3000), (.search, 1200), (.routing, 5000)], key: key).url)186        let verifier = PackageVerifier(trustStore: Fixture.trust(key))187        let hostileStrings = ["", "..", "../x", "../../../../tmp/orix-fuzz-escape", "/tmp/orix-fuzz-escape", "map", "search", "MAP", "map.pmtiles",188                              "a/b", "a\\b", "~", "\u{0}", "con", String(repeating: "A", count: 5000), "%2e%2e%2f", "routing", "terrain", "x y", "é"]189        let numbers: [Any] = [0, 1, -1, 4095, 4096, 4097, 8192, 16384, 3000, 1200, 5000, 20480, 21480, 1 << 31, 1 << 32, UInt64.max, UInt64.max - 4095,190                              Int64.max, 1.5, "12", NSNull(), true, [1], ["a": 1]]191        func randomValue(_ rng: inout SeededGenerator) -> Any {192            Bool.random(using: &rng) ? numbers.randomElement(using: &rng)! : hostileStrings.randomElement(using: &rng)!193        }194        var accepted = 0195        for i in 0..<2500 {196            let forged = try Fixture.resigned(base, key: key, fixTotal: Bool.random(using: &rng)) { object in197                for _ in 0..<Int.random(in: 1...3, using: &rng) {198                    if Bool.random(using: &rng), var components = object["components"] as? [[String: Any]], !components.isEmpty {199                        let index = Int.random(in: 0..<components.count, using: &rng)200                        switch Int.random(in: 0..<6, using: &rng) {201                        case 0: components[index]["id"] = randomValue(&rng)202                        case 1: components[index]["offset"] = randomValue(&rng)203                        case 2: components[index]["length"] = randomValue(&rng)204                        case 3: components[index]["sha256"] = randomValue(&rng)205                        case 4: components.append(components[index])206                        default: components.remove(at: index)207                        }208                        object["components"] = components209                    } else {210                        let key = object.keys.sorted().randomElement(using: &rng)!211                        if Int.random(in: 0..<5, using: &rng) == 0 { object[key] = nil } else { object[key] = randomValue(&rng) }212                    }213                }214            }215            if attempt(forged, sandbox: sandbox.url, verifier: verifier, index: i) { accepted += 1 }216        }217        expectNothingEscaped(sandbox)218        #expect(!FileManager.default.fileExists(atPath: "/tmp/orix-fuzz-escape"))219        #expect(accepted < 500, "seed \(seed): \(accepted) forged packages accepted")220    }221222    @Test func randomBytes() throws {223        let sandbox = makeSandbox()224        var rng = SeededGenerator(seed: UInt64.random(in: 1...UInt64.max))225        let verifier = PackageVerifier(trustStore: Fixture.trust(key))226        let keyId = Hex.decode(TrustedKey(key.publicKey).keyId)!227        for i in 0..<2500 {228            var d = pseudoRandomData(Int.random(in: 0...6000, using: &rng), seed: rng.next())229            // Half of the candidates get a plausible header so that the parser goes further than the magic.230            if i % 2 == 0, d.count >= 64 {231                d.replaceSubrange(0..<8, with: PackageFormat.magic)232                d.replaceSubrange(8..<12, with: [1, 0, 0, 0])233                d.replaceSubrange(12..<16, with: [64, 0, 0, 0])234                let length = UInt32.random(in: 1...UInt32(max(1, d.count)), using: &rng)235                d.replaceSubrange(16..<20, with: withUnsafeBytes(of: length.littleEndian) { Array($0) })236                d.replaceSubrange(20..<26, with: [64, 0, 0, 0, 1, 0])237                d.replaceSubrange(32..<40, with: keyId)238                d.replaceSubrange(40..<48, with: withUnsafeBytes(of: UInt64(d.count).littleEndian) { Array($0) })239            }240            #expect(!attempt(d, sandbox: sandbox.url, verifier: verifier, index: i), "random bytes accepted")241        }242        expectNothingEscaped(sandbox)243    }244245    @Test func randomJSONThroughTheManifestAndCatalogDecoders() {246        var rng = SeededGenerator(seed: UInt64.random(in: 1...UInt64.max))247        let fragments = ["{", "}", "[", "]", ":", ",", "\"", "\"format\":\"orixmap\"", "\"schemaVersion\":1", "\"schema\":{\"major\":1,\"minor\":0}", "\"regions\":[",248                         "\"components\":[", "\"offset\":", "18446744073709551616", "-1", "1e999", "null", "true", "\"..\"", "\\u0000", "\"id\":\"../x\"", " ", "\n",249                         "\"bbox\":{", "\"minLat\":", "NaN", "\"names\":{\"en\":\"x\",\"fr\":\"y\"}", "\"path\":\"../../secret\"", "\"latest\":{"]250        for _ in 0..<5000 {251            var text = Bool.random(using: &rng) ? "{" : ""252            for _ in 0..<Int.random(in: 0...40, using: &rng) { text += fragments.randomElement(using: &rng)! }253            let data = Data(text.utf8)254            _ = try? PackageManifest.decode(data)255            _ = try? Catalog.decode(data)256            _ = try? CatalogRegionDetail.decode(data)257            _ = try? CatalogRegionVersions.decode(data)258            _ = try? JSONDecoder().decode(TrustStore.self, from: data)259        }260        for _ in 0..<2000 {261            let data = pseudoRandomData(Int.random(in: 0...400, using: &rng), seed: rng.next())262            _ = try? PackageManifest.decode(data)263            _ = try? Catalog.decode(data)264            _ = try? PackageHeader.parse(data)265        }266    }267}268
Files main
Menu

Theme