diff --git a/resources/android/ShareFunctions.kt b/resources/android/ShareFunctions.kt index 9962ae3..001091d 100644 --- a/resources/android/ShareFunctions.kt +++ b/resources/android/ShareFunctions.kt @@ -71,6 +71,80 @@ object ShareFunctions { * - filePath: (optional) string - Absolute path to file to share */ class File(private val context: Context) : BridgeFunction { + + // Path confinement + // + // Share.File is exported in the JS bridge, so a web view page can call + // it through `/_native/api/call` with a `filePath` of its choosing. + // Handed an arbitrary readable path, the share intent will vend any + // file the app can read — `.env`, the SQLite database — out through the + // share sheet. That is a file-exfil primitive: user-gated by the sheet + // (the user must pick a target), but still a read-out of a named + // sandbox file. The non-app_storage branch below leans on FileProvider, + // which narrows but does not confine the path. + // + // So a shared file path is confined, not just the method gated: it must + // resolve inside a scratch area (the app cache) or the app's own + // storage (`storage_path('app')`). Secrets like `.env`, the database, + // `public/`, `bootstrap/cache` and `storage/framework` sit outside + // those roots, so a page cannot name them. The legitimate use — sharing + // a file the app captured into the cache or saved under `storage/app` — + // stays inside. + // + // Every path is canonicalised first (canonicalPath resolves symlinks + // and `..`) and only then prefix-checked, so neither `..` nor a symlink + // can walk out of a root. URLs (http/https/ftp) are not file paths and + // are not confined. + // + // These helpers live inside File (not on the object) so the unqualified + // `File(...)` constructor keeps resolving to java.io.File, as it does + // across the rest of this class. The classifier name `File` on its own, + // though, binds to this enclosing class, so the one static-member access + // (`separator`) is spelled out as java.io.File. + + /** A path with symlinks and `..`/`.` resolved; the literal path on failure. */ + private fun canonical(path: String): String = + try { File(path).canonicalPath } catch (e: Exception) { File(path).absolutePath } + + /** True when [path] is [root] itself or sits beneath it; both canonical. */ + private fun isInside(path: String, root: String): Boolean = + path == root || path.startsWith(root + java.io.File.separator) + + /** + * The app's own storage area — where `storage_path('app')` resolves. + * + * `storage_path()` is NOT under the Laravel app tree. `LaravelEnvironment` + * points Laravel at `getDir("storage")/persisted_data/storage` via + * `LARAVEL_STORAGE_PATH`, deliberately outside `…/laravel` so it + * survives an OTA that swaps the extract. This mirrors that exact path, + * so a legitimate `storage_path('app')` file is accepted. + */ + private fun storageAppRoot(): String = + canonical(File(context.getDir("storage", Context.MODE_PRIVATE), "persisted_data/storage/app").path) + + /** The roots a shared file may come from: the cache areas plus storage. */ + private fun shareableRoots(): List { + val roots = mutableListOf(canonical(context.cacheDir.path)) + context.externalCacheDir?.let { roots.add(canonical(it.path)) } + roots.add(storageAppRoot()) + return roots + } + + /** + * Refuse a share whose file path falls outside the allowed roots. + * Returns an error payload to hand straight back, or null to proceed. + */ + private fun confinementError(path: String): Map? { + val real = canonical(path) + + if (shareableRoots().none { isInside(real, it) }) { + Log.w("ShareFunctions.File", "Share refused: file outside the allowed roots") + return mapOf("error" to "File path is not allowed") + } + + return null + } + override fun execute(parameters: Map): Map { val title = parameters["title"] as? String ?: "" val message = parameters["message"] as? String ?: "" @@ -81,6 +155,10 @@ object ShareFunctions { try { cleanupOldShareFiles(context) + if (!filePath.isNullOrEmpty() && !isUrl(filePath)) { + confinementError(filePath)?.let { return it } + } + val intent = Intent(Intent.ACTION_SEND).apply { if (!filePath.isNullOrEmpty()) { val file = File(filePath) diff --git a/resources/ios/ShareFunctions.swift b/resources/ios/ShareFunctions.swift index 525d1a8..e7f55be 100644 --- a/resources/ios/ShareFunctions.swift +++ b/resources/ios/ShareFunctions.swift @@ -7,6 +7,89 @@ import UIKit /// Namespace: "Share.*" enum ShareFunctions { + // MARK: - Path confinement + // + // Share.File is exported in the JS bridge, so a web view page can call it + // through `/_native/api/call` with a `filePath` of its choosing. Handed an + // arbitrary readable path, `UIActivityViewController` will vend any file + // the app can read — `.env`, the SQLite database — out through the share + // sheet. That is a file-exfil primitive: user-gated by the sheet (the user + // must pick a target), but still a read-out of a named sandbox file. + // + // So a shared file path is confined, not just the method gated: it must + // resolve inside a scratch area (temp or caches) or the app's own storage + // (`storage_path('app')`). Secrets like `.env`, the database, `public/`, + // `bootstrap/cache` and `storage/framework` sit outside those roots, so a + // page cannot name them. The legitimate use — sharing a file the app + // captured into temp/caches or saved under `storage/app` — stays inside. + // + // The path is canonicalised first (symlinks and `..` resolved) and only + // then prefix-checked, so neither `..` nor a symlink can walk out of a + // root. URLs (http/https/ftp) are not file paths and are not confined. + + /// A path with every symlink and `..`/`.` resolved. A non-existent path is + /// resolved through its existing parent, so the check still sees where it + /// would land. + private static func canonical(_ path: String) -> String { + let fileManager = FileManager.default + let url = URL(fileURLWithPath: path) + + if fileManager.fileExists(atPath: url.path) { + return url.resolvingSymlinksInPath().standardizedFileURL.path + } + + let parent = url.deletingLastPathComponent().resolvingSymlinksInPath().standardizedFileURL + return parent.appendingPathComponent(url.lastPathComponent).standardizedFileURL.path + } + + /// True when `path` is `root` itself or sits beneath it. Both must already + /// be canonical, so a prefix match is a real containment. + private static func isInside(_ path: String, _ root: String) -> Bool { + !root.isEmpty && (path == root || path.hasPrefix(root + "/")) + } + + /// The app's own storage area — where `storage_path('app')` resolves. + /// + /// On iOS `storage_path()` is NOT under the extracted app. Core points + /// Laravel at Application Support via `LARAVEL_STORAGE_PATH` (set in + /// `NativePHPApp.setupEnvironment`), which the framework reads in + /// `Application::storagePath()`. Derive the root from that same env so a + /// legitimate `storage_path('app')` file is accepted; if it is somehow + /// unset, return "" so the root is simply dropped (fail closed — temp and + /// caches still work, storage sharing is refused rather than wide open). + private static var storageAppRoot: String { + if let raw = getenv("LARAVEL_STORAGE_PATH") { + let storage = String(cString: raw) + if !storage.isEmpty { + return canonical(storage + "/app") + } + } + + return "" + } + + /// The roots a shared file may come from: the scratch areas plus storage. + private static var shareableRoots: [String] { + var roots = [canonical(NSTemporaryDirectory()), storageAppRoot] + if let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first { + roots.append(canonical(caches.path)) + } + return roots.filter { !$0.isEmpty } + } + + /// Refuse a share whose file path falls outside the allowed roots. Returns + /// an error payload to hand straight back, or nil to proceed. + private static func confinementError(path: String) -> [String: Any]? { + let real = canonical(path) + + guard shareableRoots.contains(where: { isInside(real, $0) }) else { + print("Share refused: file outside the allowed roots") + return ["error": "File path is not allowed"] + } + + return nil + } + // MARK: - Share.Url /// Show the native share sheet for URLs @@ -99,6 +182,10 @@ enum ShareFunctions { shareItems.append(filePath) } } else { + if let refusal = ShareFunctions.confinementError(path: filePath) { + return refusal + } + let fileURL = URL(fileURLWithPath: filePath) if FileManager.default.fileExists(atPath: fileURL.path) { diff --git a/tests/ShareConfinementTest.php b/tests/ShareConfinementTest.php new file mode 100644 index 0000000..9ef211f --- /dev/null +++ b/tests/ShareConfinementTest.php @@ -0,0 +1,79 @@ +toBe(1); + + // And it runs before the file reaches the OS share sheet. + $guardAt = strpos($source, $callMarker); + $sheetAt = strpos($source, $shareSheet); + expect($guardAt)->toBeLessThan($sheetAt, 'the share sheet opens before the confinement guard'); +})->with([ + 'iOS' => [$ios, 'ShareFunctions.confinementError(path: filePath)', 'shareItems.append(fileURL)'], + 'Android' => [$android, 'confinementError(filePath)', 'FileProvider.getUriForFile'], +]); + +it('canonicalises the path before checking it, so .. and symlinks cannot escape', function (string $path, string $needle) { + expect(shareFunctionsSource($path))->toContain($needle); +})->with([ + 'iOS resolves symlinks' => [$ios, 'resolvingSymlinksInPath()'], + 'Android resolves via canonicalPath' => [$android, 'canonicalPath'], +]); + +it('allows exactly the scratch and storage roots on both platforms', function (string $path, array $needles) { + $source = shareFunctionsSource($path); + + foreach ($needles as $needle) { + expect($source)->toContain($needle); + } +})->with([ + 'iOS temp + caches + storage' => [$ios, ['NSTemporaryDirectory()', 'cachesDirectory', 'storageAppRoot']], + 'Android cache + external cache + storage' => [$android, ['cacheDir', 'externalCacheDir', 'storageAppRoot']], +]); + +it('anchors the storage root to the real storage_path, not the ephemeral app extract', function (string $path, string $needle) { + // storage_path() on both platforms points outside the swappable app tree + // (iOS: Application Support via LARAVEL_STORAGE_PATH; Android: + // persisted_data/storage). Anchoring the root anywhere under the extracted + // app would reject legitimate storage_path('app') shares. Pin the real + // source of truth. + expect(shareFunctionsSource($path))->toContain($needle); +})->with([ + 'iOS reads LARAVEL_STORAGE_PATH' => [$ios, 'getenv("LARAVEL_STORAGE_PATH")'], + 'Android uses persisted_data/storage' => [$android, 'persisted_data/storage/app'], +]); + +it('does not confine the URL branch, so Share.File of a URL still works', function (string $path, string $urlCheck) { + // A filePath that is actually a URL (http/https/ftp) shares a string, not a + // readable file — no exfil surface — so the guard must skip it. Pin that the + // URL check still exists and is not short-circuited by the guard. + expect(shareFunctionsSource($path))->toContain($urlCheck); +})->with([ + 'iOS keeps isURL' => [$ios, 'if isURL(filePath)'], + 'Android guards on !isUrl' => [$android, '!isUrl(filePath)'], +]);