diff --git a/bridge/process/ProcessRunTokenReader.swift b/bridge/process/ProcessRunTokenReader.swift index 21a2726fb..d4b21fe51 100644 --- a/bridge/process/ProcessRunTokenReader.swift +++ b/bridge/process/ProcessRunTokenReader.swift @@ -112,6 +112,11 @@ enum RunTokenReadError: Error { case ambiguousEnvironmentBoundary } +struct ParsedRunToken { + let runId: String? + let environmentEntryCount: Int +} + @_silgen_name("csops") private func csops( _ pid: Int32, @@ -122,19 +127,67 @@ private func csops( private let csOpsStatus: UInt32 = 0 private let csPlatformBinary: UInt32 = 0x0400_0000 +private let csRestrict: UInt32 = 0x0000_0800 -/** - * Whether the target image is an Apple platform binary. Current macOS omits - * the environment of platform binaries from KERN_PROCARGS2 for every caller, - * so this distinguishes a policy-withheld environment from a process whose - * environment is genuinely absent or transiently unreadable. - */ -func isPlatformBinary(pid: Int32) -> Bool { +/** Read the target's current code-signing flags when csops permits inspection. */ +private func codeSigningFlags(pid: Int32) -> UInt32? { var flags: UInt32 = 0 let result = withUnsafeMutablePointer(to: &flags) { pointer in csops(pid, csOpsStatus, UnsafeMutableRawPointer(pointer), MemoryLayout.size) } - return result == 0 && (flags & csPlatformBinary) != 0 + return result == 0 ? flags : nil +} + +/** Derive one process-token observation from parser facts and native flags. */ +func processRunTokenObservation( + pid: Int32, + parse: Result, + codeSigningFlags: () -> UInt32? +) -> RunTokenObservation { + switch parse { + case .success(let parsed): + if let runId = parsed.runId { + return RunTokenObservation(pid: pid, state: "readable", run_id: runId, reason: nil) + } + // A non-empty environment without REA's token proves this candidate is + // unrelated. CS_RESTRICT cannot turn that readable fact into uncertainty. + if parsed.environmentEntryCount > 0 { + return RunTokenObservation(pid: pid, state: "readable", run_id: nil, reason: nil) + } + let flags = codeSigningFlags() + if let flags, (flags & csPlatformBinary) != 0 { + return unavailable(pid: pid, reason: "platform_binary_environment_withheld") + } + if let flags, (flags & csRestrict) != 0 { + return unavailable(pid: pid, reason: "restricted_process_environment_withheld") + } + return RunTokenObservation(pid: pid, state: "readable", run_id: nil, reason: nil) + case .failure(let failure): + switch failure { + case .environmentUnavailable: + let flags = codeSigningFlags() + if let flags, (flags & csPlatformBinary) != 0 { + return unavailable(pid: pid, reason: "platform_binary_environment_withheld") + } + if let flags, (flags & csRestrict) != 0 { + return unavailable(pid: pid, reason: "restricted_process_environment_withheld") + } + return unavailable(pid: pid, reason: "environment_unavailable") + case .ambiguousEnvironmentBoundary: + if let flags = codeSigningFlags(), (flags & csRestrict) != 0 { + return unavailable(pid: pid, reason: "restricted_process_environment_withheld") + } + return unavailable(pid: pid, reason: "ambiguous_environment_boundary") + case .duplicateToken: + return unavailable(pid: pid, reason: "duplicate_run_token") + case .invalidTokenEncoding: + return unavailable(pid: pid, reason: "invalid_run_token_encoding") + case .appleVectorUnavailable: + return unavailable(pid: pid, reason: "apple_vector_unavailable") + case .invalidBuffer: + return unavailable(pid: pid, reason: "malformed_procargs") + } + } } private func readRunToken(pid: Int32, pointerSize: Int) -> RunTokenObservation { @@ -151,33 +204,19 @@ private func readRunToken(pid: Int32, pointerSize: Int) -> RunTokenObservation { return unavailable(pid: pid, reason: "sysctl_failed_\(errno)") } bytes = Array(bytes.prefix(size)) + let parse: Result do { - let runId = try token(in: bytes, pointerSize: pointerSize) - // A complete empty environment is readable for an ordinary image. Apple - // platform images can expose the same layout after the kernel withholds - // their environment, so they remain explicitly unverified without a token. - if runId == nil && isPlatformBinary(pid: pid) { - return unavailable(pid: pid, reason: "platform_binary_environment_withheld") - } - return RunTokenObservation(pid: pid, state: "readable", run_id: runId, reason: nil) - } catch RunTokenReadError.duplicateToken { - return unavailable(pid: pid, reason: "duplicate_run_token") - } catch RunTokenReadError.invalidTokenEncoding { - return unavailable(pid: pid, reason: "invalid_run_token_encoding") - } catch RunTokenReadError.environmentUnavailable { - return unavailable( - pid: pid, - reason: isPlatformBinary(pid: pid) - ? "platform_binary_environment_withheld" - : "environment_unavailable" - ) - } catch RunTokenReadError.appleVectorUnavailable { - return unavailable(pid: pid, reason: "apple_vector_unavailable") - } catch RunTokenReadError.ambiguousEnvironmentBoundary { - return unavailable(pid: pid, reason: "ambiguous_environment_boundary") + parse = .success(try parseProcessEnvironment(in: bytes, pointerSize: pointerSize)) + } catch let failure as RunTokenReadError { + parse = .failure(failure) } catch { - return unavailable(pid: pid, reason: "malformed_procargs") + parse = .failure(.invalidBuffer) } + return processRunTokenObservation( + pid: pid, + parse: parse, + codeSigningFlags: { codeSigningFlags(pid: pid) } + ) } func readRunTokens(pids: [Int32]) -> [RunTokenObservation] { @@ -201,7 +240,10 @@ func readRunTokens(pids: [Int32]) -> [RunTokenObservation] { } } -func token(in bytes: [UInt8], pointerSize: Int = MemoryLayout.size) throws -> String? { +func parseProcessEnvironment( + in bytes: [UInt8], + pointerSize: Int = MemoryLayout.size +) throws -> ParsedRunToken { guard bytes.count >= MemoryLayout.size else { throw RunTokenReadError.invalidBuffer } let argc = bytes.withUnsafeBytes { $0.loadUnaligned(as: Int32.self).littleEndian } guard argc >= 0, Int(argc) <= bytes.count else { throw RunTokenReadError.invalidBuffer } @@ -277,7 +319,7 @@ func token(in bytes: [UInt8], pointerSize: Int = MemoryLayout. found = decoded } } - return found + return ParsedRunToken(runId: found, environmentEntryCount: environmentEntries.count) } private func readString( diff --git a/src/dotnet/ManagedArtifactInspector.test.ts b/src/dotnet/ManagedArtifactInspector.test.ts index 3fc74337e..2d30bf580 100644 --- a/src/dotnet/ManagedArtifactInspector.test.ts +++ b/src/dotnet/ManagedArtifactInspector.test.ts @@ -22,6 +22,163 @@ const metadataLayoutFor = (bytes: Buffer) => { ); }; +const resizedOptionalHeader = ( + size: number, + magic: number, +): { readonly bytes: Buffer; readonly optional: number } => { + const bytes = buildManagedPeFixture(); + const coff = bytes.readUInt32LE(0x3c) + 4; + const optional = coff + 20; + const originalSize = bytes.readUInt16LE(coff + 16); + const section = Buffer.from( + bytes.subarray(optional + originalSize, optional + originalSize + 40), + ); + section.copy(bytes, optional + size); + bytes.writeUInt16LE(size, coff + 16); + bytes.writeUInt16LE(magic, optional); + return { bytes, optional }; +}; + +describe("managed PE optional-header directory count", () => { + it.each([96, 108, 111])( + "retains an unreadable PE32+ directory count at optional size %i", + (optionalSize) => { + const { bytes, optional } = resizedOptionalHeader(optionalSize, 0x020b); + // The section's first four bytes look like a count that excludes CLI. + bytes.writeUInt32LE(14, optional + optionalSize); + + const layout = readManagedPeLayout(bytes); + expect(layout).toMatchObject({ + optionalHeader: "pe32-plus", + machine: 0x014c, + cli: null, + cliDirectoryState: "unreadable", + cliIssue: { + code: "invalid-directory", + scope: "pe.optional-header", + }, + }); + const result = inspectManagedArtifactBytes( + bytes, + managedPeFixtureTarget(bytes), + ); + expect(result.classification.status).toBe("malformed"); + expect(result.metadata.status).toBe("malformed"); + expect(result.coverage.issues).toContainEqual( + expect.objectContaining({ + code: "invalid-directory", + scope: "pe.optional-header", + }), + ); + }, + ); + + it.each([ + { size: 96, magic: 0x010b, countOffset: 92, header: "pe32" }, + { size: 112, magic: 0x020b, countOffset: 108, header: "pe32-plus" }, + ])("accepts a minimum $header header with no CLI directory", (fixture) => { + const { bytes, optional } = resizedOptionalHeader( + fixture.size, + fixture.magic, + ); + bytes.writeUInt32LE(0, optional + fixture.countOffset); + + expect(readManagedPeLayout(bytes)).toMatchObject({ + optionalHeader: fixture.header, + cli: null, + cliDirectoryState: "absent", + cliIssue: null, + }); + }); +}); + +describe("managed CLI directory availability", () => { + it("keeps a declared but truncated CLI directory malformed", () => { + const bytes = buildManagedPeFixture(); + const peOffset = bytes.readUInt32LE(0x3c); + const coff = peOffset + 4; + const optional = coff + 20; + const originalOptionalSize = bytes.readUInt16LE(coff + 16); + const truncatedOptionalSize = 96 + 14 * 8 + 7; + const sectionHeader = Buffer.from( + bytes.subarray( + optional + originalOptionalSize, + optional + originalOptionalSize + 40, + ), + ); + sectionHeader.copy(bytes, optional + truncatedOptionalSize); + bytes.writeUInt16LE(truncatedOptionalSize, coff + 16); + bytes.writeUInt32LE(15, optional + 92); + + const layout = readManagedPeLayout(bytes); + expect(layout).toMatchObject({ + cli: null, + cliDirectoryState: "unreadable", + cliIssue: { + code: "invalid-directory", + scope: "pe.data-directories", + }, + }); + + const target = managedPeFixtureTarget(bytes); + const results = [ + inspectManagedArtifactBytes(bytes, target), + inspectManagedMembersBytes(bytes, target), + inspectManagedNativeBoundariesBytes(bytes, target), + ]; + for (const [index, result] of results.entries()) { + expect(result.metadata.status).toBe("malformed"); + expect(result.coverage).toMatchObject({ + state: index === 0 ? "partial" : "unavailable", + issues: [ + expect.objectContaining({ + code: "invalid-directory", + scope: "pe.data-directories", + }), + ], + }); + } + }); + + it("treats a CLI directory excluded by NumberOfRvaAndSizes as absent", () => { + const bytes = buildManagedPeFixture(); + const peOffset = bytes.readUInt32LE(0x3c); + const optional = peOffset + 4 + 20; + bytes.writeUInt32LE(14, optional + 92); + + const layout = readManagedPeLayout(bytes); + expect(layout).toMatchObject({ + cli: null, + cliDirectoryState: "absent", + cliIssue: null, + }); + const result = inspectManagedArtifactBytes( + bytes, + managedPeFixtureTarget(bytes), + ); + expect(result.classification.status).toBe("not-managed"); + expect(result.metadata.status).toBe("absent"); + }); + + it("retains an in-range CLI directory when the count overstates later entries", () => { + const bytes = buildManagedPeFixture(); + const peOffset = bytes.readUInt32LE(0x3c); + const optional = peOffset + 4 + 20; + bytes.writeUInt32LE(17, optional + 92); + + const layout = readManagedPeLayout(bytes); + expect(layout.cliDirectoryState).toBe("present"); + expect(layout.cliIssue).toBeNull(); + expect(layout.cli).not.toBeNull(); + const result = inspectManagedArtifactBytes( + bytes, + managedPeFixtureTarget(bytes), + ); + expect(result.classification.status).toBe("managed"); + expect(result.metadata.status).toBe("complete"); + }); +}); + describe("managed artifact inventory", () => { it.each([ { moduleRowCount: 0, assemblyRowCount: 1, scope: "metadata.Module" }, diff --git a/src/dotnet/ManagedArtifactInspector.ts b/src/dotnet/ManagedArtifactInspector.ts index cd0d627b0..7df8aae83 100644 --- a/src/dotnet/ManagedArtifactInspector.ts +++ b/src/dotnet/ManagedArtifactInspector.ts @@ -102,7 +102,7 @@ const unavailableResult = ( bytes: Buffer, layout: ManagedPeLayout, ): ManagedArtifactInspection => { - const malformed = layout.cliDirectoryPresent; + const malformed = layout.cliDirectoryState !== "absent"; const issues = layout.cliIssue === null ? [] : [layout.cliIssue]; const limitations = malformed ? [ diff --git a/src/dotnet/ManagedNativeBoundaryInspector.ts b/src/dotnet/ManagedNativeBoundaryInspector.ts index 22fd92ea0..773a95c07 100644 --- a/src/dotnet/ManagedNativeBoundaryInspector.ts +++ b/src/dotnet/ManagedNativeBoundaryInspector.ts @@ -134,7 +134,7 @@ export const inspectManagedNativeBoundariesBytes = ( return emptyInspection( target, bytes, - pe.cliDirectoryPresent ? "malformed" : "not-managed", + pe.cliDirectoryState !== "absent" ? "malformed" : "not-managed", { issues: pe.cliIssue === null ? [] : [pe.cliIssue] }, ); const issues: ManagedParseIssue[] = []; diff --git a/src/dotnet/ManagedPeReader.ts b/src/dotnet/ManagedPeReader.ts index 6f11cc491..2f9bc3151 100644 --- a/src/dotnet/ManagedPeReader.ts +++ b/src/dotnet/ManagedPeReader.ts @@ -39,7 +39,7 @@ export interface ManagedPeLayout { readonly characteristics: number; readonly sections: readonly PeSection[]; readonly cli: ManagedCliHeader | null; - readonly cliDirectoryPresent: boolean; + readonly cliDirectoryState: "absent" | "present" | "unreadable"; readonly cliIssue: ManagedParseIssue | null; rvaToOffset(rva: number, size: number, scope: string): number; rvaAvailableBytes(rva: number, scope: string): number; @@ -68,6 +68,11 @@ interface OptionalHeader { readonly directoryOffset: number; } +type CliDirectoryRead = + | { readonly kind: "absent" } + | { readonly kind: "present"; readonly directory: PeDataDirectory } + | { readonly kind: "unreadable"; readonly issue: ManagedParseIssue }; + const requireRange = ( bytes: Buffer, offset: number, @@ -355,15 +360,38 @@ const readCliDirectory = ( bytes: Buffer, coff: CoffHeader, optional: OptionalHeader, -): PeDataDirectory => { - requireRange(bytes, optional.directoryCountOffset, 4, "pe.data-directories"); +): CliDirectoryRead => { + const countOffset = optional.directoryCountOffset - optional.optionalOffset; + if (countOffset + 4 > coff.optionalSize) + return { + kind: "unreadable", + issue: { + code: "invalid-directory", + scope: "pe.optional-header", + detail: "PE optional header does not contain its directory count", + offset: optional.directoryCountOffset, + }, + }; const directoryCount = bytes.readUInt32LE(optional.directoryCountOffset); - if ( - directoryCount <= 14 || - coff.optionalSize < optional.directoryOffset - optional.optionalOffset + 120 - ) - return { rva: 0, size: 0 }; - return readDirectory(bytes, optional.directoryOffset + 14 * 8); + if (directoryCount <= 14) return { kind: "absent" }; + const availableDirectoryCount = Math.floor( + (coff.optionalSize - (optional.directoryOffset - optional.optionalOffset)) / + 8, + ); + if (availableDirectoryCount < 15) + return { + kind: "unreadable", + issue: { + code: "invalid-directory", + scope: "pe.data-directories", + detail: "PE data-directory count exceeds the optional-header extent", + offset: optional.directoryCountOffset, + }, + }; + const directory = readDirectory(bytes, optional.directoryOffset + 14 * 8); + return directory.rva !== 0 || directory.size !== 0 + ? { kind: "present", directory } + : { kind: "absent" }; }; /** Parse the file-backed PE and CLI layout without loading target code. */ @@ -379,26 +407,28 @@ export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => { const coff = readCoffHeader(bytes); const optional = readOptionalHeader(bytes, coff); const sections = readSections(bytes, coff, optional); - const cliDirectory = readCliDirectory(bytes, coff, optional); - const cliDirectoryPresent = cliDirectory.rva !== 0 || cliDirectory.size !== 0; + const cliDirectoryRead = readCliDirectory(bytes, coff, optional); + const cliDirectoryState = cliDirectoryRead.kind; let cli: ManagedCliHeader | null = null; - let cliIssue: ManagedParseIssue | null = null; - if (cliDirectoryPresent) + let cliIssue: ManagedParseIssue | null = + cliDirectoryRead.kind === "unreadable" ? cliDirectoryRead.issue : null; + if (cliDirectoryRead.kind === "present") { try { - cli = readCliHeader(bytes, sections, cliDirectory); + cli = readCliHeader(bytes, sections, cliDirectoryRead.directory); } catch (cause: unknown) { if (!(cause instanceof ManagedReaderFailure)) throw cause; cliIssue = cause.issue; } + } return { machine: coff.machine, - architecture: architectureFor(coff.machine, cliDirectoryPresent), + architecture: architectureFor(coff.machine, cliDirectoryState !== "absent"), optionalHeader: optional.optionalHeader, sectionCount: coff.sectionCount, characteristics: coff.characteristics, sections, cli, - cliDirectoryPresent, + cliDirectoryState, cliIssue, rvaToOffset: (rva, size, scope) => mapRva({ bytes, sections, rva, size, scope }), diff --git a/src/process/ProcessOwnership.test.ts b/src/process/ProcessOwnership.test.ts index 5f1906a3a..0aa644add 100644 --- a/src/process/ProcessOwnership.test.ts +++ b/src/process/ProcessOwnership.test.ts @@ -138,7 +138,10 @@ describe("opaque process neighbors during cleanup", () => { expect(signalGroup).not.toHaveBeenCalledWith(900, "SIGKILL"); }); - it("fails closed for an unrelated unreadable candidate the OS should expose", async () => { + it.each([ + "environment_unavailable", + "restricted_process_environment_withheld", + ])("fails closed for an unrelated candidate with %s", async (diagnostic) => { const processes = [ { pid: 100, parentPid: 1, processGroupId: 100, command: "capture" }, { @@ -171,7 +174,7 @@ describe("opaque process neighbors during cleanup", () => { pid === 900 ? { state: "unavailable" as const, - reason: "environment_unavailable", + reason: diagnostic, } : { state: "readable" as const, runId: "run-token" }, ]), @@ -191,13 +194,11 @@ describe("opaque process neighbors during cleanup", () => { expect(result).toMatchObject({ cleaned: false, - reason: expect.stringContaining("environment_unavailable=1"), + reason: expect.stringContaining(`${diagnostic}=1`), }); if (result.cleaned) throw new Error("Expected unknown ownership to fail closed"); - expect(result.reason).toContain( - "live candidates 900=environment_unavailable", - ); + expect(result.reason).toContain(`live candidates 900=${diagnostic}`); expect(result.reason).not.toContain("unowned"); expect(result.reason).not.toContain("run-token"); expect(signalGroup.mock.calls).toEqual([[100, "SIGKILL"]]); diff --git a/src/process/ProcessOwnership.ts b/src/process/ProcessOwnership.ts index 983d840e5..5b181fe76 100644 --- a/src/process/ProcessOwnership.ts +++ b/src/process/ProcessOwnership.ts @@ -642,6 +642,8 @@ const cleanupValidationFailure = ( const sanitizedTokenReadFailure = (diagnostic: string | undefined): string => { if (diagnostic === "environment_unavailable") return diagnostic; if (diagnostic === "platform_binary_environment_withheld") return diagnostic; + if (diagnostic === "restricted_process_environment_withheld") + return diagnostic; const environmentErrno = /^(EACCES|EPERM|ENOENT|ESRCH):/u.exec( diagnostic ?? "", ); diff --git a/tests/boundary/process/darwinProcessRunTokenReader.test.ts b/tests/boundary/process/darwinProcessRunTokenReader.test.ts index db492df83..caae8b2be 100644 --- a/tests/boundary/process/darwinProcessRunTokenReader.test.ts +++ b/tests/boundary/process/darwinProcessRunTokenReader.test.ts @@ -875,6 +875,38 @@ it.skipIf(!onDarwin)( }); expect(JSON.parse(stdout)).toEqual({ argvDecoyIgnored: true, + readableEnvironmentWithoutToken: { + runId: null, + environmentEntryCount: 1, + }, + restrictedReadableEnvironmentWithoutToken: { + state: "readable", + reason: null, + }, + restrictedEmptyEnvironment: { + state: "unavailable", + reason: "restricted_process_environment_withheld", + }, + platformEmptyEnvironment: { + state: "unavailable", + reason: "platform_binary_environment_withheld", + }, + restrictedUnavailableEnvironment: { + state: "unavailable", + reason: "restricted_process_environment_withheld", + }, + restrictedAmbiguousEnvironment: { + state: "unavailable", + reason: "restricted_process_environment_withheld", + }, + ordinaryAmbiguousEnvironment: { + state: "unavailable", + reason: "ambiguous_environment_boundary", + }, + ordinaryUnavailableEnvironment: { + state: "unavailable", + reason: "environment_unavailable", + }, alternatePaddingRead: true, appleVectorTokenFailsClosed: true, clearedAppleVectorTokenFailsClosed: true, diff --git a/tests/fixtures/processRunTokenParserProbe.swift b/tests/fixtures/processRunTokenParserProbe.swift index a753511f9..db046ea09 100644 --- a/tests/fixtures/processRunTokenParserProbe.swift +++ b/tests/fixtures/processRunTokenParserProbe.swift @@ -26,38 +26,42 @@ func fixture( @main struct ProcessRunTokenParserProbe { static func main() throws { - let argvDecoy = try token(in: fixture( + let argvDecoy = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable", "REA_PROCESS_RUN_ID=argv-decoy", "trailing"], environment: ["DECOY=words REA_PROCESS_RUN_ID=synthetic-decoy"] )) - let realToken = try token(in: fixture( + let realToken = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["DECOY=words REA_PROCESS_RUN_ID=synthetic-decoy", "REA_PROCESS_RUN_ID=owned-token"] )) - let emptyLaterArgument = try token(in: fixture( + let readableNoToken = try parseProcessEnvironment(in: fixture( + arguments: ["/fixture/executable"], + environment: ["PATH=/usr/bin"] + )) + let emptyLaterArgument = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable", "", "after-empty"], environment: ["REA_PROCESS_RUN_ID=empty-argument-token"], pointerSize: 8 )) - let alternatePadding = try token(in: fixture( + let alternatePadding = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable", "argument"], environment: ["REA_PROCESS_RUN_ID=alternate-padding-token"], pointerSize: 4 ), pointerSize: 4) - let emptyArgv0Read = try token(in: fixture( + let emptyArgv0Read = try parseProcessEnvironment(in: fixture( arguments: ["", "", "after-empty"], environment: ["REA_PROCESS_RUN_ID=empty-argv0-token"], pointerSize: 8 )) - let finalAssignmentArgumentRead = try token(in: fixture( + let finalAssignmentArgumentRead = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable", "FOO=bar"], environment: ["REA_PROCESS_RUN_ID=final-assignment-token"] )) - let reservedArgumentIgnored = try token(in: fixture( + let reservedArgumentIgnored = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable", "REA_PROCESS_RUN_ID=argv-decoy"], environment: ["DECOY=words REA_PROCESS_RUN_ID=synthetic-decoy"] )) - let nonAsciiPathRead = try token(in: fixture( + let nonAsciiPathRead = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/é", "FOO=bar"], environment: ["REA_PROCESS_RUN_ID=utf8-path-token"], pointerSize: 8, @@ -65,7 +69,7 @@ struct ProcessRunTokenParserProbe { )) let appleVectorTokenFailsClosed: Bool do { - _ = try token(in: fixture( + _ = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["pfz=user-value", "PATH=/usr/bin"], appleRecords: ["pfz=synthetic", "REA_PROCESS_RUN_ID=apple-decoy"] @@ -76,7 +80,7 @@ struct ProcessRunTokenParserProbe { } let clearedAppleVectorTokenFailsClosed: Bool do { - _ = try token(in: fixture( + _ = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["REA_PROCESS_RUN_ID=cleared-pfz-owned-token"], appleRecords: ["REA_PROCESS_RUN_ID=apple-decoy"], @@ -86,14 +90,14 @@ struct ProcessRunTokenParserProbe { } catch RunTokenReadError.ambiguousEnvironmentBoundary { clearedAppleVectorTokenFailsClosed = true } - let callerPfzBeforeTokenRead = try token(in: fixture( + let callerPfzBeforeTokenRead = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["pfz=caller-value", "REA_PROCESS_RUN_ID=cleared-pfz-owned-token"], zeroedPfz: true )) let emptyEnvironmentRecordsBeforeTokenFailClosed: Bool do { - _ = try token(in: fixture( + _ = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["DECOY=value", "", "", "REA_PROCESS_RUN_ID=synthetic-decoy"], appleRecords: [], @@ -103,7 +107,7 @@ struct ProcessRunTokenParserProbe { } catch RunTokenReadError.ambiguousEnvironmentBoundary { emptyEnvironmentRecordsBeforeTokenFailClosed = true } - let zeroArgumentsRead = try token(in: fixture( + let zeroArgumentsRead = try parseProcessEnvironment(in: fixture( arguments: [], environment: ["REA_PROCESS_RUN_ID=zero-argc-token"], pointerSize: 4 @@ -117,14 +121,14 @@ struct ProcessRunTokenParserProbe { truncatedArgv.append(contentsOf: Array("REA_PROCESS_RUN_ID=synthetic-decoy".utf8)) let truncatedArgvFailsClosed: Bool do { - _ = try token(in: truncatedArgv) + _ = try parseProcessEnvironment(in: truncatedArgv) truncatedArgvFailsClosed = false } catch { truncatedArgvFailsClosed = true } let duplicateTokenFailsClosed: Bool do { - _ = try token(in: fixture( + _ = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["REA_PROCESS_RUN_ID=first", "REA_PROCESS_RUN_ID=second"] )) @@ -134,7 +138,7 @@ struct ProcessRunTokenParserProbe { } let missingAppleBoundaryFailsClosed: Bool do { - _ = try token(in: fixture( + _ = try parseProcessEnvironment(in: fixture( arguments: ["/fixture/executable"], environment: ["REA_PROCESS_RUN_ID=synthetic-decoy"], appleRecords: [] @@ -144,23 +148,97 @@ struct ProcessRunTokenParserProbe { missingAppleBoundaryFailsClosed = true } + let restrictedReadableNoToken = processRunTokenObservation( + pid: 1, + parse: .success(readableNoToken), + codeSigningFlags: { 0x0000_0800 } + ) + let restrictedEmptyEnvironment = processRunTokenObservation( + pid: 1, + parse: .success(try parseProcessEnvironment(in: fixture( + arguments: ["/fixture/executable"], + environment: [] + ))), + codeSigningFlags: { 0x0000_0800 } + ) + let platformEmptyEnvironment = processRunTokenObservation( + pid: 1, + parse: .success(try parseProcessEnvironment(in: fixture( + arguments: ["/fixture/executable"], + environment: [] + ))), + codeSigningFlags: { 0x0400_0000 } + ) + let restrictedUnavailableEnvironment = processRunTokenObservation( + pid: 1, + parse: .failure(.environmentUnavailable), + codeSigningFlags: { 0x0000_0800 } + ) + let restrictedAmbiguousEnvironment = processRunTokenObservation( + pid: 1, + parse: .failure(.ambiguousEnvironmentBoundary), + codeSigningFlags: { 0x0000_0800 } + ) + let ordinaryAmbiguousEnvironment = processRunTokenObservation( + pid: 1, + parse: .failure(.ambiguousEnvironmentBoundary), + codeSigningFlags: { 0 } + ) + let ordinaryUnavailableEnvironment = processRunTokenObservation( + pid: 1, + parse: .failure(.environmentUnavailable), + codeSigningFlags: { 0 } + ) + let result: [String: Any] = [ - "argvDecoyIgnored": argvDecoy == nil, - "realTokenRead": realToken == "owned-token", - "emptyLaterArgumentRead": emptyLaterArgument == "empty-argument-token", - "alternatePaddingRead": alternatePadding == "alternate-padding-token", + "argvDecoyIgnored": argvDecoy.runId == nil && argvDecoy.environmentEntryCount == 1, + "realTokenRead": realToken.runId == "owned-token", + "readableEnvironmentWithoutToken": [ + "runId": readableNoToken.runId as Any? ?? NSNull(), + "environmentEntryCount": readableNoToken.environmentEntryCount, + ], + "restrictedReadableEnvironmentWithoutToken": [ + "state": restrictedReadableNoToken.state, + "reason": restrictedReadableNoToken.reason as Any? ?? NSNull(), + ], + "restrictedEmptyEnvironment": [ + "state": restrictedEmptyEnvironment.state, + "reason": restrictedEmptyEnvironment.reason as Any? ?? NSNull(), + ], + "platformEmptyEnvironment": [ + "state": platformEmptyEnvironment.state, + "reason": platformEmptyEnvironment.reason as Any? ?? NSNull(), + ], + "restrictedUnavailableEnvironment": [ + "state": restrictedUnavailableEnvironment.state, + "reason": restrictedUnavailableEnvironment.reason as Any? ?? NSNull(), + ], + "restrictedAmbiguousEnvironment": [ + "state": restrictedAmbiguousEnvironment.state, + "reason": restrictedAmbiguousEnvironment.reason as Any? ?? NSNull(), + ], + "ordinaryAmbiguousEnvironment": [ + "state": ordinaryAmbiguousEnvironment.state, + "reason": ordinaryAmbiguousEnvironment.reason as Any? ?? NSNull(), + ], + "ordinaryUnavailableEnvironment": [ + "state": ordinaryUnavailableEnvironment.state, + "reason": ordinaryUnavailableEnvironment.reason as Any? ?? NSNull(), + ], + "emptyLaterArgumentRead": emptyLaterArgument.runId == "empty-argument-token", + "alternatePaddingRead": alternatePadding.runId == "alternate-padding-token", "truncatedArgvFailsClosed": truncatedArgvFailsClosed, "duplicateTokenFailsClosed": duplicateTokenFailsClosed, "missingAppleBoundaryFailsClosed": missingAppleBoundaryFailsClosed, - "emptyArgv0Read": emptyArgv0Read == "empty-argv0-token", - "finalAssignmentArgumentRead": finalAssignmentArgumentRead == "final-assignment-token", - "reservedArgumentIgnored": reservedArgumentIgnored == nil, - "nonAsciiPathRead": nonAsciiPathRead == "utf8-path-token", + "emptyArgv0Read": emptyArgv0Read.runId == "empty-argv0-token", + "finalAssignmentArgumentRead": finalAssignmentArgumentRead.runId == "final-assignment-token", + "reservedArgumentIgnored": reservedArgumentIgnored.runId == nil && reservedArgumentIgnored.environmentEntryCount == 1, + "nonAsciiPathRead": nonAsciiPathRead.runId == "utf8-path-token", "appleVectorTokenFailsClosed": appleVectorTokenFailsClosed, "clearedAppleVectorTokenFailsClosed": clearedAppleVectorTokenFailsClosed, - "callerPfzBeforeTokenRead": callerPfzBeforeTokenRead == "cleared-pfz-owned-token", + "callerPfzBeforeTokenRead": callerPfzBeforeTokenRead.runId == "cleared-pfz-owned-token", "emptyEnvironmentRecordsBeforeTokenFailClosed": emptyEnvironmentRecordsBeforeTokenFailClosed, - "zeroArgumentsRead": zeroArgumentsRead == "zero-argc-token", + "zeroArgumentsRead": zeroArgumentsRead.runId == "zero-argc-token", ] let output = try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]) FileHandle.standardOutput.write(output)