SPB Git

Repository Public License

PDFTests.swift 12.7 KB 276 lines swift

1// ORIX Secure2// File: Packages/ORIXFileInspection/Tests/ORIXFileInspectionTests/PDFTests.swift3// Description: PDF raw scan (tokens, escapes, header, end marker, scan windows) on hand-written PDFs, and PDFKit4//              facts (pages, attributes, links, protection) on PDFs generated with CoreGraphics.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel10import Testing11@testable import ORIXFileInspection12#if canImport(CoreGraphics)13import CoreGraphics14#endif1516@Suite("PDF inspection")17struct PDFTests {18    static let active = bytes("""19    %PDF-1.720    1 0 obj21    << /Type /Catalog /Pages 2 0 R /OpenAction 4 0 R /AcroForm << /Fields [] >> /Names << /JavaScript 5 0 R >> >>22    endobj23    2 0 obj24    << /Type /Pages /Kids [3 0 R] /Count 1 >>25    endobj26    3 0 obj27    << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /AA << /O 4 0 R >> >>28    endobj29    4 0 obj30    << /Type /Action /S /JavaScript /JS (app.alert\\('hello'\\);) >>31    endobj32    6 0 obj33    << /Type /Action /S /Launch /F (calc.exe) >>34    endobj35    7 0 obj36    << /Type /Filespec /EF << /F 8 0 R >> /Type /EmbeddedFile >>37    endobj38    9 0 obj39    << /Type /ObjStm /N 3 /First 20 /Length 0 >>40    endobj41    trailer42    << /Root 1 0 R /Size 10 >>43    %%EOF4445    """)4647    func scan(_ data: [UInt8], options: InspectionOptions = .init()) throws -> PDFReport {48        try PDFInspector.scan(source: DataByteSource(data), options: options)49    }5051    @Test("Name tokens are counted exactly")52    func tokens() throws {53        let report = try scan(Self.active)54        #expect(report.headerVersion == "1.7")55        #expect(report.headerOffset == 0)56        #expect(report.count("/OpenAction") == 1)57        #expect(report.count("/JavaScript") == 2)58        #expect(report.count("/JS") == 1)59        #expect(report.count("/AA") == 1)60        #expect(report.count("/Launch") == 1)61        #expect(report.count("/EmbeddedFile") == 1)62        #expect(report.count("/AcroForm") == 1)63        #expect(report.count("/ObjStm") == 1)64        #expect(report.count("/Encrypt") == 0)65        #expect(report.count("/XFA") == 0)66        #expect(report.hasEOFMarker)67        #expect(report.trailingByteCount == 0)68        #expect(!report.rawScanTruncated)69        #expect(report.rawScanByteCount == UInt64(Self.active.count))70    }7172    @Test("Longer names that merely start like a token are not counted")73    func tokenBoundaries() throws {74        let data = bytes("%PDF-1.4\n<< /JSON 1 /JavaScripts 2 /AAA 3 /OpenActions 4 /Launcher 5 /MyJS 6 /JS[1] /AA<<>> /XFA(x) >>\n%%EOF")75        let report = try scan(data)76        #expect(report.count("/JS") == 1)77        #expect(report.count("/AA") == 1)78        #expect(report.count("/XFA") == 1)79        #expect(report.count("/JavaScript") == 0)80        #expect(report.count("/OpenAction") == 0)81        #expect(report.count("/Launch") == 0)82        // A token ending exactly at the end of the data.83        let atEnd = try scan(bytes("%PDF-1.4\n/OpenAction"))84        #expect(atEnd.count("/OpenAction") == 1)85    }8687    @Test("Names spelled with #xx escapes are decoded and reported")88    func escapedNames() throws {89        let data = bytes("%PDF-1.4\n<< /S /J#61vaScript /#4AS (x) /Open#41ction 1 0 R /J#zz 1 >>\n%%EOF\n")90        let report = try scan(data)91        #expect(report.count("/JavaScript") == 1)92        #expect(report.count("/JS") == 1)93        #expect(report.count("/OpenAction") == 1)94        #expect(report.escapedTokenCount == 3)95        let core = try inspectBytes(data, name: "odd.pdf")96        let finding = try #require(core.findings.with("file.pdf.escapedNames"))97        #expect(finding.severity == .moderate)98        expectHonest(core.findings)99    }100101    @Test("Findings state facts and their benign reading")102    func findings() throws {103        var options = InspectionOptions()104        options.usePDFKit = false105        let core = try inspectBytes(Self.active, name: "form.pdf", options: options)106        expectHonest(core.findings)107        let open = try #require(core.findings.with("file.pdf.openAction"))108        #expect(open.title == "This PDF declares an action that runs when it opens")109        #expect(open.severity == .moderate)110        #expect(open.confidence == .heuristic)111        #expect(core.findings.with("file.pdf.javascript")?.severity == .low)112        #expect(core.findings.with("file.pdf.javascript")?.explanation.contains("forms") == true)113        #expect(core.findings.with("file.pdf.launch")?.severity == .moderate)114        #expect(core.findings.has("file.pdf.additionalActions"))115        #expect(core.findings.has("file.pdf.embeddedFiles"))116        #expect(core.findings.with("file.pdf.form")?.state == .verified)117        #expect(core.notInspected.contains { $0.contains("compressed object stream") })118        // An open action alone (initial view) stays low.119        let viewOnly = try inspectBytes(bytes("%PDF-1.4\n<< /OpenAction [3 0 R /Fit] >>\n%%EOF\n"), name: "plain.pdf", options: options)120        #expect(viewOnly.findings.with("file.pdf.openAction")?.severity == .low)121        let quiet = try inspectBytes(Samples.pdf, name: "quiet.pdf", options: options)122        #expect(!quiet.findings.contains { $0.state == .attention })123    }124125    @Test("End marker and trailing data")126    func endMarker() throws {127        let trailing = try scan(Samples.pdf + bytes("MZ hidden payload"))128        #expect(trailing.hasEOFMarker)129        #expect(trailing.trailingByteCount == 15)130        let blank = try scan(Samples.pdf + bytes("\r\n \n"))131        #expect(blank.trailingByteCount == 0)132        let none = try scan(bytes("%PDF-1.4\n1 0 obj\n<< >>\nendobj\n"))133        #expect(!none.hasEOFMarker)134        var options = InspectionOptions()135        options.usePDFKit = false136        let first = try inspectBytes(Samples.pdf + bytes("extra"), name: "a.pdf", options: options)137        #expect(first.findings.with("file.pdf.trailingData")?.severity == .low)138        let second = try inspectBytes(bytes("%PDF-1.4\n1 0 obj\n<< >>\nendobj\n"), name: "b.pdf", options: options)139        #expect(second.findings.has("file.pdf.noEOF"))140    }141142    @Test("Tokens across chunk boundaries are counted once")143    func chunkBoundaries() throws {144        let token = bytes("/JavaScript ")145        for shift in [0, 1, 5, 11, 12, 127, 128, 129] {146            var data = bytes("%PDF-1.4\n")147            data += [UInt8](repeating: 0x61, count: (1 << 20) - data.count - shift)148            data += token149            data += [UInt8](repeating: 0x62, count: (1 << 20) + 300)150            data += bytes("/JS /OpenAction\n%%EOF\n")151            let report = try scan(data)152            #expect(report.count("/JavaScript") == 1, "shift \(shift)")153            #expect(report.count("/JS") == 1, "shift \(shift)")154            #expect(report.count("/OpenAction") == 1, "shift \(shift)")155        }156    }157158    @Test("Large files are scanned at both ends only, and the report says so")159    func scanWindows() throws {160        var options = InspectionOptions()161        options.rawScanWindowBytes = 64 << 10162        options.usePDFKit = false163        var data = bytes("%PDF-1.5\n/OpenAction ")164        data += [UInt8](repeating: 0x20, count: 100_000)165        data += bytes("/Launch /JavaScript ")166        data += [UInt8](repeating: 0x20, count: 100_000)167        data += bytes("/AcroForm\n%%EOF\n")168        let core = try inspectBytes(data, name: "big.pdf", options: options)169        let report = try #require(core.pdf)170        #expect(report.rawScanTruncated)171        #expect(report.rawScanByteCount == 128 << 10)172        #expect(report.count("/OpenAction") == 1)173        #expect(report.count("/AcroForm") == 1)174        #expect(report.count("/Launch") == 0)175        #expect(core.notInspected.contains { $0.contains("middle of the file") })176        let full = try scan(data)177        #expect(full.count("/Launch") == 1)178        #expect(!full.rawScanTruncated)179    }180181    #if canImport(PDFKit) && canImport(CoreGraphics)182    func makePDF(in dir: TempDir, name: String, pages: Int, links: [String], password: String? = nil) throws -> URL {183        let url = dir.url.appendingPathComponent(name)184        var box = CGRect(x: 0, y: 0, width: 300, height: 400)185        var info: [CFString: Any] = [kCGPDFContextTitle: "Quarterly report", kCGPDFContextAuthor: "ORIX Tests", kCGPDFContextCreator: "ArchiveTests"]186        if let password { info[kCGPDFContextUserPassword] = password; info[kCGPDFContextOwnerPassword] = password + "-owner" }187        let context = try #require(CGContext(url as CFURL, mediaBox: &box, info as CFDictionary))188        for page in 0..<pages {189            context.beginPDFPage(nil)190            context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1))191            context.fill(CGRect(x: 20, y: 20, width: 100, height: 40))192            if page == 0 {193                for (index, link) in links.enumerated() {194                    let target = try #require(URL(string: link))195                    context.setURL(target as CFURL, for: CGRect(x: 20, y: 80 + index * 30, width: 200, height: 20))196                }197            }198            context.endPDFPage()199        }200        context.closePDF()201        return url202    }203204    @Test("PDFKit: page count, attributes and link annotations")205    func pdfKitFacts() async throws {206        let dir = try TempDir()207        let url = try makePDF(in: dir, name: "report.pdf", pages: 3, links: ["https://example.com/a?b=1", "https://example.org/", "https://example.com/a?b=1", "mailto:someone@example.com"])208        let inspection = try await FileInspector().inspect(fileAt: url)209        expectHonest(inspection.findings)210        let report = try #require(inspection.pdf)211        #expect(inspection.detectedType == .pdf)212        #expect(report.pageCount == .measured(3))213        #expect(report.isLocked == .measured(false))214        #expect(report.title == "Quarterly report")215        #expect(report.author == "ORIX Tests")216        #expect(report.creationDate != nil)217        #expect(Set(report.links) == ["https://example.com/a?b=1", "https://example.org/", "mailto:someone@example.com"])218        #expect(report.links.count == 3)219        #expect(!report.linksTruncated)220        #expect(report.hasEOFMarker)221        let links = try #require(inspection.findings.with("file.pdf.links"))222        #expect(links.state == .verified)223        #expect(links.evidence.contains { $0.value.contains("example.org") })224        #expect(inspection.declaredTypeIdentifier == "com.adobe.pdf")225    }226227    @Test("PDFKit: link cap and unusual schemes")228    func linkLimits() async throws {229        let dir = try TempDir()230        let url = try makePDF(in: dir, name: "many.pdf", pages: 1, links: (0..<12).map { "https://example.com/page/\($0)" } + ["file:///etc/hosts"])231        var options = InspectionOptions()232        options.maxPDFLinks = 5233        let capped = try await FileInspector().inspect(fileAt: url, options: options)234        #expect(capped.pdf?.links.count == 5)235        #expect(capped.pdf?.linksTruncated == true)236        let full = try await FileInspector().inspect(fileAt: url)237        #expect(full.pdf?.links.count == 13)238        #expect(full.findings.with("file.pdf.linksUnusual")?.severity == .low)239        options.usePDFKit = false240        let raw = try await FileInspector().inspect(fileAt: url, options: options)241        #expect(raw.pdf?.links.isEmpty == true)242        #expect(raw.pdf?.pageCount.isMeasured == false)243    }244245    @Test("PDFKit: a password-protected PDF is reported as locked")246    func locked() async throws {247        let dir = try TempDir()248        let url = try makePDF(in: dir, name: "private.pdf", pages: 1, links: ["https://example.com/"], password: "s3cret")249        let inspection = try await FileInspector().inspect(fileAt: url)250        expectHonest(inspection.findings)251        let report = try #require(inspection.pdf)252        #expect(report.isEncrypted == .measured(true))253        #expect(report.isLocked == .measured(true))254        #expect(report.pageCount.value == nil)255        #expect(report.links.isEmpty)256        #expect(report.count("/Encrypt") >= 1)257        let finding = try #require(inspection.findings.with("file.pdf.locked"))258        #expect(finding.confidence == .measured)259        #expect(finding.notInspected.isEmpty == false)260    }261262    @Test("PDFKit: a PDF header followed by noise does not throw")263    func unreadable() async throws {264        let dir = try TempDir()265        var generator = SplitMix64(seed: 7)266        let noise = (0..<4000).map { _ in UInt8.random(in: 0...255, using: &generator) }267        let url = try dir.write("broken.pdf", bytes("%PDF-1.6\n") + noise)268        let inspection = try await FileInspector().inspect(fileAt: url)269        expectHonest(inspection.findings)270        #expect(inspection.detectedType == .pdf)271        #expect(inspection.pdf?.pageCount.value == nil || inspection.pdf?.pageCount.value == 0)272        #expect(inspection.findings.has("file.pdf.noEOF"))273    }274    #endif275}276
Files main
Menu

Theme