diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ca1755..7d59a21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,21 @@ Notable changes to GreenBubbles are documented here. The project follows confirmed nor ruled out. If lldb exits unexpectedly after a captured value was rejected, the exit is reported as the cause, with the rejection as context. As before, no output is created or replaced in either case (#48). +- `greenbubbles-acquire preflight` and `capture` check the key destination as + the invoking user, without changing it, before the WeChat logout step: an + existing key file without `--overwrite`, a file owned by someone else, or a + folder you can't write (such as a root-owned folder from an earlier capture) + now stops preflight instead of failing at the final write (#50). +- With only `source.passphrase_file` in `config.toml`, `greenbubbles-acquire` + keys the database root queries discover: the most recently written account, + unless another one was written within 14 days. When `GREENBUBBLES_CONFIG_FILE` + points elsewhere, or with `--db-root`, an explicit `--output` is required + instead (#50). +- The `--db-root` conflict check compares directories by device and inode + instead of by path spelling; a root that can't be looked up counts as a + different account (#50). +- The `Next:` command printed by `preflight --overwrite` keeps `--overwrite` + (#50). ## 0.11.0 - 2026-11-23 diff --git a/Sources/GreenBubblesAcquire/QueryProfileTarget.swift b/Sources/GreenBubblesAcquire/QueryProfileTarget.swift index 65271d6..477d175 100644 --- a/Sources/GreenBubblesAcquire/QueryProfileTarget.swift +++ b/Sources/GreenBubblesAcquire/QueryProfileTarget.swift @@ -11,6 +11,7 @@ public enum QueryProfileError: Error, Equatable, CustomStringConvertible { case notLiveProfile(name: String, mode: String) case invalidEnvironment(String) case unsafeSourceRoot(String) + case liveSourceUnavailable(String) public var description: String { switch self { @@ -32,6 +33,8 @@ public enum QueryProfileError: Error, Equatable, CustomStringConvertible { + "with a live profile, or give both --db-root and --output" case .unsafeSourceRoot(let reason): return "The database root is not usable: \(reason)" + case .liveSourceUnavailable(let reason): + return "The database root for config.toml's source.passphrase_file is unavailable: \(reason)" case .invalidEnvironment(let variable): return "\(variable) must be an absolute, non-root path" } @@ -50,17 +53,28 @@ public struct AcquireTarget: Equatable, Sendable { public let credentialFile: URL? /// How `sourceRoot` was chosen, for the preflight line. public let sourceRootOrigin: String? + /// Why the root queries would discover for a configured key file could + /// not be found (only `source.passphrase_file` set); `sourceRoot` is then + /// nil. Capture and verify need an explicit `--db-root` instead. + public let sourceRootDiscoveryFailure: QueryProfileError? + /// Whether `sourceRoot` was discovered the way queries discover it rather + /// than configured. + public let sourceRootDiscovered: Bool public init( profileName: String? = nil, sourceRoot: URL? = nil, credentialFile: URL? = nil, - sourceRootOrigin: String? = nil + sourceRootOrigin: String? = nil, + sourceRootDiscoveryFailure: QueryProfileError? = nil, + sourceRootDiscovered: Bool = false ) { self.profileName = profileName self.sourceRoot = sourceRoot self.credentialFile = credentialFile self.sourceRootOrigin = sourceRootOrigin + self.sourceRootDiscoveryFailure = sourceRootDiscoveryFailure + self.sourceRootDiscovered = sourceRootDiscovered } public static let none = AcquireTarget() @@ -73,20 +87,27 @@ public struct AcquireTarget: Equatable, Sendable { /// configured but its root is auto-discovered — else nil. The caller then /// requires an explicit `--output` (fail closed). /// - /// Roots are compared after `canonicalize` (realpath, run as the invoking - /// user), so symbolic links can't make two spellings name different - /// accounts; a root that can't be resolved counts as different. + /// Roots are compared by filesystem identity (`st_dev` and `st_ino` from + /// `stat`, run as the invoking user), not by spelling: symbolic links + /// can't make two spellings name different accounts, and two spellings + /// that differ only in Unicode normalization still count as different + /// directories on a normalization-sensitive volume unless they are the + /// same directory. A root whose identity can't be read counts as + /// different. public func originConflicting( withDatabaseRoot databaseRoot: URL?, - canonicalize: (URL) -> URL? = QueryProfileTarget.canonicalPath + identify: (URL) -> QueryProfileTarget.FileIdentity? = QueryProfileTarget.fileIdentity ) -> String? { guard let databaseRoot else { return nil } - guard let sourceRoot else { + // A discovered root is found under the invoking user's login home, but + // a query discovers under its own $HOME, which can differ; keep + // requiring --output whenever --db-root is given for a configured key + // file without a configured root. + guard let sourceRoot, !sourceRootDiscovered else { return credentialFile == nil ? nil : "auto-discovered for the configured key file" } - if let resolvedOverride = canonicalize(databaseRoot), - let resolvedSource = canonicalize(sourceRoot), - resolvedOverride.path == resolvedSource.path + if let override = identify(databaseRoot), let source = identify(sourceRoot), + override == source { return nil } @@ -220,6 +241,33 @@ public enum QueryProfileTarget { let (name, profile) = try store.select(profileName) return try target(for: profile, named: name) } + if settings.sourceRoot == nil, let passphraseFile = settings.passphraseFile { + // Queries with only a key file configured pick the root with Rust's + // discover_default_live_source_root, so capture must key that root. + let credentialFile = URL(fileURLWithPath: passphraseFile) + // Rust discovers under the query's $HOME. A query reads the default + // ~/.greenbubbles/config.toml only with $HOME at this home, so the + // same discovery is known to apply; with GREENBUBBLES_CONFIG_FILE the + // query's home can't be established, so don't guess an account. + guard locations.settingsOverride == nil else { + return AcquireTarget( + credentialFile: credentialFile, + sourceRootDiscoveryFailure: .liveSourceUnavailable( + "\(settingsEnvironmentVariable) is set, so the home folder queries search can't be " + + "known; set source.root in that file, or pass --db-root together with --output")) + } + do { + return AcquireTarget( + sourceRoot: try discoverDefaultLiveSourceRoot( + home: locations.home, ownerUID: ownerUID), + credentialFile: credentialFile, + sourceRootOrigin: "auto-discovered as queries do for config.toml source.passphrase_file", + sourceRootDiscovered: true + ) + } catch let error as QueryProfileError { + return AcquireTarget(credentialFile: credentialFile, sourceRootDiscoveryFailure: error) + } + } return AcquireTarget( sourceRoot: settings.sourceRoot.map { URL(fileURLWithPath: $0) }, credentialFile: settings.passphraseFile.map { URL(fileURLWithPath: $0) }, @@ -227,6 +275,149 @@ public enum QueryProfileTarget { ) } + // MARK: - Live root discovery (Rust's discover_default_live_source_root) + + /// Rust's ambiguity window: a second account written within 14 days of + /// the newest one makes the choice ambiguous. + static let ambiguousWindowSeconds = 14 * 24 * 60 * 60 + + /// The `db_storage` root a query picks when no root is configured, with + /// the candidate and recency rules of Rust's + /// `discover_default_live_source_root` (`query_profile.rs`): + /// + /// - candidates are `/db_storage` for every entry of + /// `~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files` + /// and of `xwechat_files` in each `~/Library/Group Containers` entry whose + /// ASCII-lowercased name contains `wechat` or `xinwechat`; + /// - a candidate is usable when it is a real directory (not a symbolic + /// link) owned by `ownerUID` and `contact`, `session`, and `message` are + /// directories; + /// - its recency is the newest `mtime` (whole seconds) of a regular file + /// directly inside those three folders; one without such a file is + /// skipped; + /// - the most recent wins, unless the next one is less than 14 days older. + /// + /// The path is returned as Rust builds it, without resolving links. Call + /// inside `InvokingUser.perform(_:)` with that user's uid. + public static func discoverDefaultLiveSourceRoot(home: URL, ownerUID: uid_t) throws -> URL { + // Paths are kept as bytes, as Rust's PathBuf does, so a name that isn't + // UTF-8 is still looked up exactly as listed. + let homePath = Array(home.path.utf8) + var candidates = [ + homePath + + Array("/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files".utf8) + ] + let groups = homePath + Array("/Library/Group Containers".utf8) + for name in directoryEntryNames(groups) { + let lowered = name.map { (0x41...0x5A).contains($0) ? $0 + 0x20 : $0 } + if containsBytes(lowered, Array("wechat".utf8)) + || containsBytes(lowered, Array("xinwechat".utf8)) + { + candidates.append(groups + [0x2F] + name + Array("/xwechat_files".utf8)) + } + } + var found: [(modified: Int, path: [UInt8])] = [] + for filesRoot in candidates { + for account in directoryEntryNames(filesRoot) { + let databaseRoot = filesRoot + [0x2F] + account + Array("/db_storage".utf8) + guard isUsableLiveDatabaseRoot(databaseRoot, ownerUID: ownerUID), + let modified = databaseRootRecency(databaseRoot) + else { continue } + found.append((modified, databaseRoot)) + } + } + // Rust sorts newest first; ties are ambiguous below either way. + found.sort { $0.modified > $1.modified } + guard let newest = found.first else { + throw QueryProfileError.liveSourceUnavailable("no live WeChat database was found") + } + if found.count > 1, newest.modified - found[1].modified < ambiguousWindowSeconds { + throw QueryProfileError.liveSourceUnavailable( + "more than one WeChat account was written recently; set source.root in " + + "~/.greenbubbles/config.toml to the account you are signed in to, or pass --db-root " + + "together with --output") + } + // The rest of greenbubbles-acquire handles paths as text; refuse rather + // than open a different folder than the one discovered. + guard let path = strictUTF8(newest.path) else { + throw QueryProfileError.liveSourceUnavailable("the discovered database path is not UTF-8") + } + return URL(fileURLWithPath: path, isDirectory: true) + } + + private static func containsBytes(_ haystack: [UInt8], _ needle: [UInt8]) -> Bool { + guard haystack.count >= needle.count else { return false } + return (0...(haystack.count - needle.count)).contains { + haystack[$0..<($0 + needle.count)].elementsEqual(needle) + } + } + + /// Runs `body` with `path` as a NUL-terminated C string. + private static func withRawPath(_ path: [UInt8], _ body: (UnsafePointer) -> T) -> T { + (path + [0]).withUnsafeBufferPointer { buffer in + buffer.baseAddress!.withMemoryRebound(to: CChar.self, capacity: buffer.count) { body($0) } + } + } + + private static func rawStat(_ path: [UInt8], followingLinks: Bool) -> stat? { + var info = stat() + let flags = followingLinks ? 0 : AT_SYMLINK_NOFOLLOW + let status = withRawPath(path) { fstatat(AT_FDCWD, $0, &info, flags) } + return status == 0 ? info : nil + } + + /// Entry names as Rust's `fs::read_dir` lists them: every entry except + /// `.` and `..`, hidden ones included, as raw bytes; empty when the folder + /// can't be read. + private static func directoryEntryNames(_ path: [UInt8]) -> [[UInt8]] { + guard let directory = withRawPath(path, { opendir($0) }) else { return [] } + defer { closedir(directory) } + var names: [[UInt8]] = [] + // Darwin's readdir returns variable-length records, so read only the + // name's d_namlen bytes in place, never the whole d_name array. + let lengthOffset = MemoryLayout.offset(of: \dirent.d_namlen)! + let nameOffset = MemoryLayout.offset(of: \dirent.d_name)! + while let entry = readdir(directory) { + let record = UnsafeRawPointer(entry) + let length = record.loadUnaligned( + fromByteOffset: lengthOffset, as: type(of: dirent().d_namlen)) + let name = Array( + UnsafeRawBufferPointer(start: record + nameOffset, count: Int(length))) + if name != [0x2E], name != [0x2E, 0x2E] { names.append(name) } + } + return names + } + + private static func isUsableLiveDatabaseRoot(_ path: [UInt8], ownerUID: uid_t) -> Bool { + guard let info = rawStat(path, followingLinks: false), info.st_mode & S_IFMT == S_IFDIR, + info.st_uid == ownerUID + else { return false } + // Rust's Path::is_dir follows symbolic links. + return ["contact", "session", "message"].allSatisfy { component in + guard let child = rawStat(path + Array("/\(component)".utf8), followingLinks: true) + else { return false } + return child.st_mode & S_IFMT == S_IFDIR + } + } + + // Directory timestamps stay behind after an account switch; the files + // WeChat writes are the evidence of the account in use. Rust's + // DirEntry::metadata does not follow symbolic links. + private static func databaseRootRecency(_ path: [UInt8]) -> Int? { + var newest: Int? + for component in ["contact", "session", "message"] { + let directory = path + Array("/\(component)".utf8) + for name in directoryEntryNames(directory) { + guard let info = rawStat(directory + [0x2F] + name, followingLinks: false), + info.st_mode & S_IFMT == S_IFREG + else { continue } + let modified = Int(info.st_mtimespec.tv_sec) + newest = max(newest ?? modified, modified) + } + } + return newest + } + private static func target(for profile: ProfileStore.Profile, named name: String) throws -> AcquireTarget { @@ -269,6 +460,21 @@ public enum QueryProfileTarget { return URL(fileURLWithPath: String(cString: resolved), isDirectory: true) } + /// A directory's identity on disk. + public struct FileIdentity: Equatable, Sendable { + public let device: dev_t + public let inode: ino_t + } + + /// The identity (`st_dev`, `st_ino`) of what the path names once the + /// kernel resolves it, or nil when `stat` fails. Call inside + /// `InvokingUser.perform(_:)` so it resolves with the user's rights. + public static func fileIdentity(_ url: URL) -> FileIdentity? { + var info = stat() + guard fstatat(AT_FDCWD, url.path, &info, 0) == 0 else { return nil } + return FileIdentity(device: info.st_dev, inode: info.st_ino) + } + /// The checks Rust's `LiveQuerySource::open` applies to the root exactly as /// given, before canonicalising it: `symlink_metadata` must succeed, the /// path must be a real directory (not a symbolic link), and it must be diff --git a/Sources/GreenBubblesAcquire/SecretOutputWriter.swift b/Sources/GreenBubblesAcquire/SecretOutputWriter.swift index 042a19b..7f19229 100644 --- a/Sources/GreenBubblesAcquire/SecretOutputWriter.swift +++ b/Sources/GreenBubblesAcquire/SecretOutputWriter.swift @@ -10,6 +10,8 @@ public enum SecretOutputError: Error, Equatable, CustomStringConvertible { case relativePath case dotComponents case symbolicLinkParent + case destinationNotWritable(code: Int32) + case outputNotWritable(code: Int32) case posix(operation: String, code: Int32) public var description: String { @@ -30,6 +32,15 @@ public enum SecretOutputError: Error, Equatable, CustomStringConvertible { return "The folder that would hold the passphrase output is a symbolic link; " + "give its real path instead (for example /private/tmp rather than /tmp)" + case .destinationNotWritable(let code): + return + "You can't create or replace the passphrase output file there (POSIX error \(code)): " + + "a folder on its path isn't writable or searchable by you (for example one an " + + "earlier capture created as root); fix that folder or choose another --output" + case .outputNotWritable(let code): + return + "You can't write the existing passphrase output file (POSIX error \(code)); " + + "make it writable by you or choose another --output" case .posix(let operation, let code): return "\(operation) failed with POSIX error \(code)" } @@ -68,6 +79,84 @@ public struct SecretOutputWriter: Sendable { } } + /// Checks, as `user` and without changing anything, that `write` could + /// put the key at `url`: an existing output must be replaceable (only + /// with `overwrite`, a single-link regular file the user owns and can + /// write, in a folder that is not a symbolic link), and otherwise the + /// nearest existing folder on the path must let the user create entries. + /// Run before capture starts, so a destination the final write would + /// refuse fails before the owner logs out of WeChat. + public static func checkDestinationAccess( + _ url: URL, + overwrite: Bool, + as user: InvokingUser + ) throws { + try checkDestination(url) + try user.perform { + try checkDestinationAccessAsUser(url.path, overwrite: overwrite, ownerUID: user.uid) + } + } + + // Access is checked with faccessat(AT_EACCESS): under sudo the real user + // is root, so plain access(2) would approve everything. + private static func checkDestinationAccessAsUser( + _ path: String, + overwrite: Bool, + ownerUID: uid_t + ) throws { + let parentPath = (path as NSString).deletingLastPathComponent + var info = stat() + if Darwin.lstat(path, &info) == 0 { + guard overwrite else { throw SecretOutputError.outputExists } + var parent = stat() + guard Darwin.lstat(parentPath, &parent) == 0 else { + throw SecretOutputError.destinationNotWritable(code: errno) + } + if parent.st_mode & S_IFMT == S_IFLNK { throw SecretOutputError.symbolicLinkParent } + // The writer opens the folder O_RDONLY, then the file inside it. + guard Darwin.faccessat(AT_FDCWD, parentPath, R_OK | X_OK, AT_EACCESS) == 0 else { + throw SecretOutputError.destinationNotWritable(code: errno) + } + guard info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1 else { + throw SecretOutputError.unsafeOutputFile + } + guard info.st_uid == ownerUID else { throw SecretOutputError.notOwnedByUser } + guard Darwin.faccessat(AT_FDCWD, path, W_OK, AT_EACCESS) == 0 else { + throw SecretOutputError.outputNotWritable(code: errno) + } + return + } + guard errno == ENOENT else { throw SecretOutputError.destinationNotWritable(code: errno) } + // Walk up to the nearest folder that exists; `write` creates the rest. + var existing = parentPath + while true { + var folder = stat() + if Darwin.lstat(existing, &folder) == 0 { + if existing == parentPath, folder.st_mode & S_IFMT == S_IFLNK { + throw SecretOutputError.symbolicLinkParent + } + break + } + guard errno == ENOENT, existing != "/" else { + throw SecretOutputError.destinationNotWritable(code: errno) + } + existing = (existing as NSString).deletingLastPathComponent + } + var folder = stat() + guard Darwin.fstatat(AT_FDCWD, existing, &folder, 0) == 0 else { + throw SecretOutputError.destinationNotWritable(code: errno) + } + guard folder.st_mode & S_IFMT == S_IFDIR else { + throw SecretOutputError.destinationNotWritable(code: ENOTDIR) + } + // New folders need write and search access; an existing containing + // folder is also opened O_RDONLY by the writer, so it must be readable. + let needed = existing == parentPath ? R_OK | W_OK | X_OK : W_OK | X_OK + guard Darwin.faccessat(AT_FDCWD, existing, needed, AT_EACCESS) == 0 else { + throw SecretOutputError.destinationNotWritable(code: errno) + } + } + @discardableResult public func write( _ secret: PassphraseSecret, diff --git a/Sources/GreenBubblesAcquireCLI/main.swift b/Sources/GreenBubblesAcquireCLI/main.swift index c447e4d..1813d88 100644 --- a/Sources/GreenBubblesAcquireCLI/main.swift +++ b/Sources/GreenBubblesAcquireCLI/main.swift @@ -307,9 +307,20 @@ private func resolveTarget(_ arguments: Arguments, needsOutput: Bool) throws -> { throw CLIError.rootConflictsWithTarget(origin) } + // Only source.passphrase_file is configured and the root queries would + // pick can't be determined: capture can't tell which account to key. + if arguments.dbRoot == nil, let failure = target.sourceRootDiscoveryFailure { + throw failure + } return target } +// The key destination as the invoking user, without changing anything: the +// final write's rules, checked before the owner logs out of WeChat. +private func checkCaptureOutput(_ output: URL, overwrite: Bool) throws { + try SecretOutputWriter.checkDestinationAccess(output, overwrite: overwrite, as: invokingUser) +} + // Where capture writes the key for this target. private func captureOutput(_ arguments: Arguments, _ target: AcquireTarget) -> URL { arguments.output @@ -373,6 +384,7 @@ private func captureCommand(_ arguments: Arguments) -> [String] { command += ["--output", path(output, placeholder: "")] } if let processID = arguments.processID { command += ["--pid", String(processID)] } + if arguments.overwrite { command.append("--overwrite") } return command } @@ -483,14 +495,17 @@ private func selectProcess( private func runPreflight( dbRootOption: URL?, + rootAutoDiscovered: Bool? = nil, rootOrigin: String = "from --db-root", processIDOption: pid_t? = nil, includePaths: Bool, - targetError: String? = nil + targetError: String? = nil, + destinationError: String? = nil ) -> PreflightResult { var checks: [PreflightCheck] = [] var remediation: String? let homeDirectory = invokingUserHomeDirectory() + let autoDiscovered = rootAutoDiscovered ?? (dbRootOption == nil) let lldbAvailable = LLDBPassphraseCapture().lldbAvailable checks.append( @@ -633,6 +648,12 @@ private func runPreflight( } checks.append(PreflightCheck(ok: databasesOK, label: databaseLabel, hint: databaseHint)) + // Checked apart from the database root, so a key-file problem doesn't hide + // the database and process diagnostics. + if let destinationError { + checks.append(PreflightCheck(ok: false, label: destinationError, hint: nil)) + } + let blockers = checks.filter { !$0.ok }.map { check in check.hint.map { "\(check.label) (\($0))" } ?? check.label } @@ -656,7 +677,7 @@ private func runPreflight( return nil }(), databaseRoot: databaseRootReference, - databaseRootAutoDiscovered: dbRootOption == nil, + databaseRootAutoDiscovered: autoDiscovered, databaseCount: databaseCount, distinctSaltCount: distinctSaltCount ) @@ -673,6 +694,12 @@ private func rootOrigin(_ arguments: Arguments, _ target: AcquireTarget) -> Stri return "from --db-root" } +// Whether the root was discovered rather than named: no --db-root and no +// configured root (a root queries discover for a configured key file counts). +private func rootAutoDiscovered(_ arguments: Arguments, _ target: AcquireTarget) -> Bool { + arguments.dbRoot == nil && (target.sourceRoot == nil || target.sourceRootDiscovered) +} + do { let arguments = try Arguments(Array(CommandLine.arguments.dropFirst())) switch arguments.command { @@ -681,19 +708,26 @@ do { case .preflight: var target = AcquireTarget.none var targetError: String? + var destinationError: String? + // Readiness means capture would accept this target and destination. do { - // Readiness means capture would accept this target and destination. target = try resolveTarget(arguments, needsOutput: true) - try SecretOutputWriter.checkDestination(captureOutput(arguments, target)) + do { + try checkCaptureOutput(captureOutput(arguments, target), overwrite: arguments.overwrite) + } catch { + destinationError = String(describing: error) + } } catch { targetError = String(describing: error) } let result = runPreflight( dbRootOption: arguments.dbRoot ?? target.sourceRoot, + rootAutoDiscovered: rootAutoDiscovered(arguments, target), rootOrigin: rootOrigin(arguments, target), processIDOption: arguments.processID, includePaths: arguments.includePaths, - targetError: targetError + targetError: targetError, + destinationError: destinationError ) if arguments.json { try printJSON(result.report) @@ -705,12 +739,21 @@ do { let target = try resolveTarget(arguments, needsOutput: true) let dbRoot = arguments.dbRoot ?? target.sourceRoot let output = captureOutput(arguments, target) - try SecretOutputWriter.checkDestination(output) + // A destination problem blocks like any other preflight check, before + // the owner is asked to log out. + var destinationError: String? + do { + try checkCaptureOutput(output, overwrite: arguments.overwrite) + } catch { + destinationError = String(describing: error) + } let preflight = runPreflight( dbRootOption: dbRoot, + rootAutoDiscovered: rootAutoDiscovered(arguments, target), rootOrigin: rootOrigin(arguments, target), processIDOption: arguments.processID, - includePaths: arguments.includePaths + includePaths: arguments.includePaths, + destinationError: destinationError ) guard preflight.report.ready, let processTarget = preflight.target, let root = preflight.databaseRoot diff --git a/Tests/GreenBubblesAcquireTests/QueryProfileTargetTests.swift b/Tests/GreenBubblesAcquireTests/QueryProfileTargetTests.swift index d121a90..4341133 100644 --- a/Tests/GreenBubblesAcquireTests/QueryProfileTargetTests.swift +++ b/Tests/GreenBubblesAcquireTests/QueryProfileTargetTests.swift @@ -118,15 +118,19 @@ struct QueryProfileTargetTests { #expect( settingsRootOnly.originConflicting(withDatabaseRoot: other) == "from config.toml source.root") - // These made-up paths don't exist, so they are compared as spelled here; - // without that, an unresolvable root always counts as different. - let asSpelled: (URL) -> URL? = { $0.standardizedFileURL } + // These made-up paths don't exist, so they get made-up identities here; + // without that, a root whose identity can't be read always counts as + // different. + let madeUp: (URL) -> QueryProfileTarget.FileIdentity? = { + $0.standardizedFileURL.path == root.path + ? QueryProfileTarget.FileIdentity(device: 1, inode: 2) : nil + } #expect( - settingsRootOnly.originConflicting(withDatabaseRoot: root, canonicalize: asSpelled) == nil) + settingsRootOnly.originConflicting(withDatabaseRoot: root, identify: madeUp) == nil) #expect( settingsRootOnly.originConflicting( withDatabaseRoot: URL(fileURLWithPath: "/example/settings/./db_storage"), - canonicalize: asSpelled) == nil) + identify: madeUp) == nil) #expect(settingsRootOnly.originConflicting(withDatabaseRoot: root) != nil) #expect(settingsRootOnly.originConflicting(withDatabaseRoot: nil) == nil) let profile = AcquireTarget( @@ -147,17 +151,123 @@ struct QueryProfileTargetTests { target.originConflicting(withDatabaseRoot: URL(fileURLWithPath: "/example/other")) != nil) } - @Test func configuredKeyFileWithoutARootNeedsExplicitOutputForAnyDbRoot() throws { + @Test func configuredKeyFileWithoutADiscoverableRootNeedsExplicitOutputForAnyDbRoot() throws { let home = try TemporaryHome() try home.writeSettings("[source]\npassphrase_file = \"/example/keys/settings-key\"\n") let target = try home.resolve(nil) #expect(target.sourceRoot == nil) + #expect( + target.sourceRootDiscoveryFailure + == .liveSourceUnavailable("no live WeChat database was found")) #expect(target.credentialFile?.path == "/example/keys/settings-key") #expect( target.originConflicting(withDatabaseRoot: URL(fileURLWithPath: "/example/any")) != nil) #expect(target.originConflicting(withDatabaseRoot: nil) == nil) } + // MARK: Discovery for a configured key file (Rust's discover_default_live_source_root) + + @Test func configuredKeyFileUsesTheRootQueriesDiscover() throws { + let home = try TemporaryHome() + try home.writeSettings("[source]\npassphrase_file = \"/example/keys/settings-key\"\n") + let live = try home.makeAccount("live", ageDays: 0) + _ = try home.makeAccount("stale", ageDays: 15) + let target = try home.resolve(nil) + #expect(target.sourceRoot?.path == live.path) + #expect(target.sourceRootDiscovered) + #expect(target.sourceRootDiscoveryFailure == nil) + #expect(target.credentialFile?.path == "/example/keys/settings-key") + // A query may discover under a different $HOME, so any --db-root still + // needs an explicit --output. + #expect(target.originConflicting(withDatabaseRoot: live) != nil) + #expect(target.originConflicting(withDatabaseRoot: nil) == nil) + } + + @Test func configuredKeyFileFromAnOverriddenSettingsFileIsNotGuessed() throws { + let home = try TemporaryHome() + _ = try home.makeAccount("live", ageDays: 0) + let settings = home.directory.appending(path: ".greenbubbles/elsewhere.toml") + try Data("[source]\npassphrase_file = \"/example/keys/k\"\n".utf8).write(to: settings) + chmod(settings.path, 0o600) + let locations = try QueryProfileTarget.locations( + environment: [QueryProfileTarget.settingsEnvironmentVariable: settings.path], + home: home.directory) + let target = try QueryProfileTarget.resolve( + requestedProfile: nil, locations: locations, ownerUID: getuid()) + #expect(target.sourceRoot == nil) + #expect(target.sourceRootDiscoveryFailure != nil) + #expect(target.credentialFile?.path == "/example/keys/k") + } + + @Test func discoveryRefusesTwoAccountsWrittenWithinFourteenDays() throws { + let home = try TemporaryHome() + _ = try home.makeAccount("a", ageDays: 0) + _ = try home.makeAccount("b", ageDays: 13) + #expect(throws: QueryProfileError.self) { try home.discover() } + // A group container whose name contains "wechat" is a candidate too. + let home2 = try TemporaryHome() + let group = try home2.makeAccount( + "acct", ageDays: 0, + filesRoot: home2.directory.appending( + path: "Library/Group Containers/5A4RE8SF68.com.tencent.XinWeChat/xwechat_files")) + #expect(try home2.discover().path == group.path) + _ = try home2.makeAccount("other", ageDays: 1) + #expect(throws: QueryProfileError.self) { try home2.discover() } + } + + @Test func discoverySkipsRootsRustSkips() throws { + let home = try TemporaryHome() + let live = try home.makeAccount("live", ageDays: 20) + // Newer, but each unusable: incomplete, no regular files, a symbolic + // link, owned by someone else, or in a group container without "wechat". + let incomplete = home.filesRoot.appending(path: "incomplete/db_storage/contact") + try FileManager.default.createDirectory(at: incomplete, withIntermediateDirectories: true) + try Data().write(to: incomplete.appending(path: "c.db")) + let empty = home.filesRoot.appending(path: "empty/db_storage") + for component in ["contact", "session", "message"] { + try FileManager.default.createDirectory( + at: empty.appending(path: component), withIntermediateDirectories: true) + } + try FileManager.default.createDirectory( + at: home.filesRoot.appending(path: "linked"), withIntermediateDirectories: true) + let elsewhere = try home.makeAccount( + "real", ageDays: 0, filesRoot: home.directory.appending(path: "elsewhere")) + #expect( + symlink(elsewhere.path, home.filesRoot.appending(path: "linked/db_storage").path) == 0) + _ = try home.makeAccount( + "acct", ageDays: 0, + filesRoot: home.directory.appending( + path: "Library/Group Containers/group.example.other/xwechat_files")) + #expect(try home.discover().path == live.path) + #expect(throws: QueryProfileError.self) { try home.discover(ownerUID: getuid() &+ 1) } + } + + @Test func rootsAreComparedByIdentityNotSpelling() throws { + let home = try TemporaryHome() + // "é" composed (NFC) and decomposed (NFD): different strings to Swift's + // `==` only after normalization, and different paths to the kernel on a + // normalization-sensitive volume. + let composed = home.directory.appending(path: "caf\u{E9}/db_storage") + try FileManager.default.createDirectory(at: composed, withIntermediateDirectories: true) + let decomposed = URL(fileURLWithPath: home.directory.path + "/cafe\u{301}/db_storage") + let target = AcquireTarget( + profileName: "a", sourceRoot: composed, + credentialFile: URL(fileURLWithPath: "/example/keys/a"), + sourceRootOrigin: "from query profile a") + let identity = QueryProfileTarget.fileIdentity(composed) + #expect(identity != nil) + // The decomposed spelling conflicts unless it is the same directory. + let sameDirectory = QueryProfileTarget.fileIdentity(decomposed) == identity + #expect((target.originConflicting(withDatabaseRoot: decomposed) == nil) == sameDirectory) + // A failed lookup on either side is a conflict. + let missing = home.directory.appending(path: "missing") + #expect(target.originConflicting(withDatabaseRoot: missing) != nil) + let missingSource = AcquireTarget( + profileName: "b", sourceRoot: missing, credentialFile: URL(fileURLWithPath: "/k"), + sourceRootOrigin: "from query profile b") + #expect(missingSource.originConflicting(withDatabaseRoot: missing) != nil) + } + @Test func tomlWhitespaceIsOnlySpaceAndTab() throws { let home = try TemporaryHome() try home.writeSettings("\t[source] \n \troot\t= \"/example/tabs\"\t# ok\n") @@ -320,6 +430,8 @@ struct QueryProfileTargetTests { #expect( QueryProfileTarget.canonicalPath(throughLink)?.path == QueryProfileTarget.canonicalPath(accountA)?.path) + #expect( + QueryProfileTarget.fileIdentity(throughLink) == QueryProfileTarget.fileIdentity(accountA)) } @Test func jsonMustBeASingleUTF8Value() throws { @@ -691,6 +803,32 @@ private final class TemporaryHome { try QueryProfileTarget.resolve(requestedProfile: name, locations: locations, ownerUID: ownerUID) } + func discover(ownerUID: uid_t = getuid()) throws -> URL { + try QueryProfileTarget.discoverDefaultLiveSourceRoot(home: directory, ownerUID: ownerUID) + } + + /// The app container's xwechat_files, where Rust looks first. + var filesRoot: URL { + directory.appending( + path: "Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files") + } + + /// A made-up account whose database files were last written `ageDays` ago. + func makeAccount(_ name: String, ageDays: Int, filesRoot: URL? = nil) throws -> URL { + let root = (filesRoot ?? self.filesRoot).appending(path: name).appending(path: "db_storage") + let modified = Date().addingTimeInterval(-Double(ageDays) * 24 * 60 * 60) + for component in ["contact", "session", "message"] { + let folder = root.appending(path: component) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let file = folder.appending(path: component + ".db") + try Data("x".utf8).write(to: file) + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: file.path) + } + // Folder timestamps don't count; make them look fresh. + try FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: root.path) + return root + } + private func write(_ text: String, to url: URL) throws { unlink(url.path) try Data(text.utf8).write(to: url) diff --git a/Tests/GreenBubblesAcquireTests/SecretOutputWriterTests.swift b/Tests/GreenBubblesAcquireTests/SecretOutputWriterTests.swift index 6efc13b..a1661bd 100644 --- a/Tests/GreenBubblesAcquireTests/SecretOutputWriterTests.swift +++ b/Tests/GreenBubblesAcquireTests/SecretOutputWriterTests.swift @@ -219,6 +219,127 @@ struct SecretOutputWriterTests { #expect(try posixMode(of: output) == 0o600) } + // MARK: Destination access (preflight and capture, before the login step) + + @Test func destinationCheckAcceptsWhatTheWriteAcceptsWithoutChangingAnything() throws { + let base = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: base) } + let nested = base.appending(path: "a/b/passphrase.txt") + try SecretOutputWriter.checkDestinationAccess(nested, overwrite: false, as: currentUser()) + #expect(try FileManager.default.contentsOfDirectory(atPath: base.path).isEmpty) + + let output = base.appending(path: "passphrase.txt") + try SecretOutputWriter.checkDestinationAccess(output, overwrite: false, as: currentUser()) + let secret = try PassphraseSecret(bytes: bytesFromHex(passphraseHex)) + try SecretOutputWriter().write(secret, to: output) + let written = try Data(contentsOf: output) + #expect(throws: SecretOutputError.outputExists) { + try SecretOutputWriter.checkDestinationAccess(output, overwrite: false, as: currentUser()) + } + try SecretOutputWriter.checkDestinationAccess(output, overwrite: true, as: currentUser()) + #expect(try Data(contentsOf: output) == written) + #expect(try posixMode(of: output) == 0o600) + } + + @Test func destinationCheckRefusesWhatTheWriteWouldRefuse() throws { + guard geteuid() != 0 else { return } + let base = try makeTemporaryDirectory() + let locked = base.appending(path: "locked", directoryHint: .isDirectory) + defer { + chmod(locked.path, 0o700) + try? FileManager.default.removeItem(at: base) + } + let user = currentUser() + + // A folder the user can't write, such as a root-owned 0700 folder left + // by an earlier capture: a new file or new levels below it. + try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: false) + chmod(locked.path, 0o500) + for path in ["passphrase.txt", "new/passphrase.txt"] { + #expect(throws: SecretOutputError.destinationNotWritable(code: EACCES)) { + try SecretOutputWriter.checkDestinationAccess( + locked.appending(path: path), overwrite: false, as: user) + } + } + // A folder the user can't search hides even whether the file exists. + chmod(locked.path, 0o000) + #expect(throws: SecretOutputError.destinationNotWritable(code: EACCES)) { + try SecretOutputWriter.checkDestinationAccess( + locked.appending(path: "passphrase.txt"), overwrite: true, as: user) + } + // Writable and searchable but not readable: the writer can't open it. + chmod(locked.path, 0o300) + #expect(throws: SecretOutputError.destinationNotWritable(code: EACCES)) { + try SecretOutputWriter.checkDestinationAccess( + locked.appending(path: "passphrase.txt"), overwrite: false, as: user) + } + // A missing level below it is created by the writer, so that's fine. + try SecretOutputWriter.checkDestinationAccess( + locked.appending(path: "new/passphrase.txt"), overwrite: false, as: user) + chmod(locked.path, 0o700) + + // An existing file the user can't write, even with --overwrite. + let readOnly = base.appending(path: "read-only.txt") + try Data("x".utf8).write(to: readOnly) + chmod(readOnly.path, 0o400) + #expect(throws: SecretOutputError.outputNotWritable(code: EACCES)) { + try SecretOutputWriter.checkDestinationAccess(readOnly, overwrite: true, as: user) + } + + // A linked file, a folder in the file's place, and a file in a folder's place. + let target = base.appending(path: "target.txt") + try Data("x".utf8).write(to: target) + let hardLink = base.appending(path: "hard.txt") + #expect(link(target.path, hardLink.path) == 0) + let symbolic = base.appending(path: "symbolic.txt") + try FileManager.default.createSymbolicLink(at: symbolic, withDestinationURL: target) + for url in [hardLink, symbolic, locked] { + #expect(throws: SecretOutputError.unsafeOutputFile) { + try SecretOutputWriter.checkDestinationAccess(url, overwrite: true, as: user) + } + } + #expect(throws: SecretOutputError.destinationNotWritable(code: ENOTDIR)) { + try SecretOutputWriter.checkDestinationAccess( + target.appending(path: "passphrase.txt"), overwrite: false, as: user) + } + #expect(throws: SecretOutputError.destinationNotWritable(code: ENOTDIR)) { + try SecretOutputWriter.checkDestinationAccess( + target.appending(path: "deeper/passphrase.txt"), overwrite: false, as: user) + } + + // A symbolic link as the containing folder, whether or not the file exists. + let linkedFolder = base.appending(path: "linked") + try FileManager.default.createSymbolicLink(at: linkedFolder, withDestinationURL: locked) + #expect(throws: SecretOutputError.symbolicLinkParent) { + try SecretOutputWriter.checkDestinationAccess( + linkedFolder.appending(path: "passphrase.txt"), overwrite: false, as: user) + } + try Data("x".utf8).write(to: locked.appending(path: "passphrase.txt")) + #expect(throws: SecretOutputError.symbolicLinkParent) { + try SecretOutputWriter.checkDestinationAccess( + linkedFolder.appending(path: "passphrase.txt"), overwrite: true, as: user) + } + #expect(throws: SecretOutputError.dotComponents) { + try SecretOutputWriter.checkDestinationAccess( + URL(fileURLWithPath: base.path + "/x/../passphrase.txt"), overwrite: false, as: user) + } + } + + @Test func destinationCheckRefusesAFileOwnedBySomeoneElse() throws { + let base = try makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: base) } + let output = base.appending(path: "passphrase.txt") + try Data("x".utf8).write(to: output) + // Same process credentials, but the owner the file must belong to differs. + let other = InvokingUser( + name: NSUserName(), uid: geteuid() &+ 1, gid: getegid(), + homeDirectory: FileManager.default.homeDirectoryForCurrentUser) + guard !other.switchesCredentials else { return } + #expect(throws: SecretOutputError.notOwnedByUser) { + try SecretOutputWriter.checkDestinationAccess(output, overwrite: true, as: other) + } + } + private func makeTemporaryDirectory() throws -> URL { let url = FileManager.default.temporaryDirectory.appending( path: "greenbubbles-acquire-writer-tests-\(UUID().uuidString)", diff --git a/scripts/sudo-smoke-test-acquire.sh b/scripts/sudo-smoke-test-acquire.sh index ac5644e..b7e55fb 100755 --- a/scripts/sudo-smoke-test-acquire.sh +++ b/scripts/sudo-smoke-test-acquire.sh @@ -166,6 +166,10 @@ cat >"$profiles" <"$work/u1.out" 2>&1; then @@ -219,13 +239,32 @@ else fail "user: writer" "$(tr '\n' ' ' <"$work/u3.err")" fi +# Issue #50: preflight checks the key destination, and keeps --overwrite. +printf 'existing\n' >"$work/keys/existing.key" +chmod 600 "$work/keys/existing.key" +"$binary" preflight --json --profile smoke --output "$work/keys/existing.key" \ + >"$work/u4.json" 2>/dev/null || true +"$binary" preflight --json --profile smoke --output "$work/keys/existing.key" --overwrite \ + >"$work/u4b.json" 2>/dev/null || true +if blockers_mention "$work/u4.json" "already exists" >"$work/u4.out" 2>&1 \ + && blockers_mention --absent "$work/u4b.json" "already exists" >/dev/null 2>&1 \ + && [[ "$(cat "$work/keys/existing.key")" == "existing" ]]; then + pass "user: preflight reports an existing key file unless --overwrite is given" +else + fail "user: preflight existing key file" "$(tr '\n' ' ' <"$work/u4.out")" +fi + # --- sudo checks --------------------------------------------------------------- if [[ "$use_sudo" -eq 0 ]]; then for check in "sudo: --preserve-env passes the profile location" \ "sudo (a): preflight reads the profile as you" "sudo (a): verify reads databases as you" \ "sudo (b): key written from the profile is yours" "sudo (c): root-owned folder refused" \ - "sudo (d): root-owned file not overwritten"; do + "sudo (d): root-owned file not overwritten" \ + "sudo (e): preflight refuses a root-owned 0700 key folder as you" \ + "sudo (e): capture refuses it before the login step" \ + "sudo (e): preflight refuses a key folder inside root's home" \ + "sudo (f): preflight refuses a root-owned key file even with --overwrite"; do skip "$check" done else @@ -291,6 +330,57 @@ else done fi +if [[ "$use_sudo" -eq 1 ]]; then + # (e) Issue #50: the destination is checked as you before capture starts. + # A root-owned 0700 folder left by an earlier capture blocks preflight, and + # capture stops before asking for the WeChat logout; nothing is created. + sudo /bin/mkdir -m 700 "$work/keys/root-0700" + as_root "$binary" preflight --json --profile rootfolder >"$work/e.json" 2>"$work/e.err" || true + if blockers_mention "$work/e.json" "POSIX error 13" >"$work/e.out" 2>&1 \ + && [[ -z "$(sudo ls -A "$work/keys/root-0700")" ]] \ + && [[ "$(owner_and_mode "$work/keys/root-0700")" == "0 700" ]]; then + pass "sudo (e): preflight refuses a root-owned 0700 key folder as you ($(tr '\n' ' ' <"$work/e.out"))" + else + fail "sudo (e): preflight refuses a root-owned 0700 key folder" "$(cat "$work/e.out" "$work/e.err" | tr '\n' ' ')" + fi + if as_root "$binary" capture --json --profile rootfolder --timeout-seconds 1 \ + >"$work/e2.json" 2>"$work/e2.err"; then + fail "sudo (e): capture refuses it before the login step" "capture succeeded" + elif blockers_mention "$work/e2.json" "POSIX error 13" >"$work/e2.out" 2>&1 \ + && ! grep -q "log out" "$work/e2.err" \ + && [[ -z "$(sudo ls -A "$work/keys/root-0700")" ]]; then + pass "sudo (e): capture refuses it before the login step" + else + fail "sudo (e): capture refuses it before the login step" "$(cat "$work/e2.out" "$work/e2.err" | tr '\n' ' ')" + fi + as_root "$binary" preflight --json --profile rootdir >"$work/e3.json" 2>/dev/null || true + if blockers_mention "$work/e3.json" "POSIX error 13" >"$work/e3.out" 2>&1 \ + && ! sudo test -e "$root_probe"; then + pass "sudo (e): preflight refuses a key folder inside root's home; nothing created" + else + fail "sudo (e): preflight refuses a key folder inside root's home" "$(tr '\n' ' ' <"$work/e3.out")" + fi + + # (f) A root-owned key file in your folder: preflight with --overwrite + # reports it (as the final write would) and leaves it alone. + target="$work/keys/root-owned-644.key" + as_root "$binary" preflight --json --profile smoke --output "$target" --overwrite \ + >"$work/f.json" 2>/dev/null || true + if blockers_mention "$work/f.json" "belongs to another user" >"$work/f.out" 2>&1 \ + && [[ "$(cat "$target")" == "root-owned original" && "$(owner_and_mode "$target")" == "0 644" ]]; then + pass "sudo (f): preflight refuses a root-owned key file even with --overwrite" + else + fail "sudo (f): preflight refuses a root-owned key file" "$(tr '\n' ' ' <"$work/f.out")" + fi + # Clean up as you, not root: the fixtures are entries in your own writable + # keys folder, so unlinking them needs no privilege, and rmdir refuses a + # folder that unexpectedly has contents instead of deleting them. + /bin/rm -f "$work/keys/root-owned-644.key" "$work/keys/root-owned-666.key" \ + || echo "cleanup: could not remove the root-owned key fixtures in $work/keys" >&2 + /bin/rmdir "$work/keys/root-0700" \ + || echo "cleanup: $work/keys/root-0700 is not empty; left in place for inspection" >&2 +fi + echo "" echo "passed: $passed failed: $failed skipped: $skipped" [[ "$failed" -eq 0 ]]