https://developer.android.com/privacy-and-security/risks/untrustworthy-contentprovider-provided-filename Android Developers * Essentials * Modern Android * Quickly bring your app to life with less code, using a modern declarative approach to UI, and the simplicity of Kotlin. * Explore Modern Android * Adopt Compose for teams * Get started * Start by creating your first app. Go deeper with our training courses or explore app development on your own. * Hello world * Training courses * Tutorials * Kotlin for Android * Monetization with Play /[?] * Extend by device * Build apps that give your users seamless experiences from phones to tablets, watches, and more. * Large screens (e.g., tablets) * Wear OS * Android for Cars * Android TV * ChromeOS * Cross-device SDK * Build by category * Learn to build for your use case by following Google's prescriptive and opinionated guidance. * Games * Media apps * Health & Fitness * Enterprise apps * Get the latest * Stay in touch with the latest releases throughout the year, join our preview programs, and give us your feedback. * Platform releases * Android Studio preview * Jetpack & Compose libraries * Wear OS preview * Privacy Sandbox Design & Plan * Kits & more * Get one of our Figma kits for Android, Material Design, or Wear OS, and start designing your app's UI today. * Go to Android & Material kits * Go to Wear OS kits * UI Design * Design a beautiful user interface using Android best practices. * Design for Android * Mobile * Large screens (e.g., tablets) * Wear OS * Android TV * Architecture * Design robust, testable, and maintainable app logic and services. * Introduction * Libraries * Navigation * Modularization * Testing * Quality * Plan for app quality and align with Play store guidelines. * Overview * Core value * User experience * Technical quality * Privacy & security * Build for Billions * Create the best experience for entry-level devices * Overview * About new markets * Android (Go edition) Develop * Gemini is here * Gemini in Android Studio is your AI development companion for Android development. * Learn more * Get Android Studio * Core areas * Get the samples and docs for the features you need. * Samples * User interfaces * Permissions * Background work * Data and files * User identity * All core areas [?] * Tools and workflow * Use the IDE to write and build your app, or create your own pipeline. * Write and debug code * Build projects * Test your app * Performance * Command-line tools * Gradle plugin API * Device tech * Write code for form factors. Connect devices and share data. * Large screens (e.g., tablets) * Wear OS * Android Health * Cross-device SDK * Android for Cars * Android TV * ChromeOS * Libraries * Browse API reference documentation with all the details. * Android platform * Jetpack libraries * Compose libraries * Google Play services /[?] * Google Play SDK index /[?] Google Play Community [ ] * English * Deutsch * Espanol - America Latina * Francais * Indonesia * Polski * Portugues - Brasil * Tieng Viet * Zhong Wen - Jian Ti * Ri Ben Yu * hangugeo Android Studio Sign in * App quality Overview Core value User experience Technical quality Privacy & Security [ ] Android Developers * * Essentials + More * Design & Plan + More + Overview + Core value + User experience + Technical quality + Privacy & Security * Develop + More * Google Play * Community * Android Studio * Overview * Privacy + Privacy guidelines + Minimize your permission requests + Handle data safely o Declare your app's data use o Audit access to data + Privacy Sandbox on Android o Documentation o API reference [?] * Security + Security guidelines + Improve your app's security + About the app security improvement program + Understand common security risks o Common risks o android:debuggable o android:exported o Backup Leaks o Cleartext / Plaintext HTTP o Content resolvers o Custom Permission Typos o Hardcoded Cryptographic Secrets o Implicit Intent hijacking o Improperly Exposed Directories to FileProvider o Improperly trusting ContentProvider-provided filename o Insecure API or Library o Insecure broadcast receivers o Insecure DNS Setup o Intent redirection o Log Info Disclosure o Path traversal o Pending intents o SQL injection o Sticky Broadcasts o StrandHogg Attack / Task Affinity Vulnerability o Tapjacking o Test and debug features o Unsafe HostnameVerifier o Unsafe TrustManager o Weak PRNG o Webviews - Unsafe URI Loading o Zip Path Traversal + Protect your app with the Play Integrity API + Avoid known threat URLs + Challenge malicious traffic with reCAPTCHA + About the SafetyNet Attestation deprecation + Verify hardware-backed key pairs + Work with cryptography + Work with the Android Keystore System + Run embedded DEX code directly from APK + Protect data sent over a network o About security with network protocols o Customize your network security settings o Update your security provider to protect against SSL exploits o Confirm user intentions for sensitive transactions + Perform actions before initial device unlock * Modern Android * Explore Modern Android * Adopt Compose for teams * Get started * Hello world * Training courses * Tutorials * Kotlin for Android * Monetization with Play /[?] * Extend by device * Large screens (e.g., tablets) * Wear OS * Android for Cars * Android TV * ChromeOS * Cross-device SDK * Build by category * Games * Media apps * Health & Fitness * Enterprise apps * Get the latest * Platform releases * Android Studio preview * Jetpack & Compose libraries * Wear OS preview * Privacy Sandbox * Kits & more * Go to Android & Material kits * Go to Wear OS kits * UI Design * Design for Android * Mobile * Large screens (e.g., tablets) * Wear OS * Android TV * Architecture * Introduction * Libraries * Navigation * Modularization * Testing * Quality * Overview * Core value * User experience * Technical quality * Privacy & security * Build for Billions * Overview * About new markets * Android (Go edition) * Gemini is here * Learn more * Get Android Studio * Core areas * Samples * User interfaces * Permissions * Background work * Data and files * User identity * All core areas [?] * Tools and workflow * Write and debug code * Build projects * Test your app * Performance * Command-line tools * Gradle plugin API * Device tech * Large screens (e.g., tablets) * Wear OS * Android Health * Cross-device SDK * Android for Cars * Android TV * ChromeOS * Libraries * Android platform * Jetpack libraries * Compose libraries * Google Play services /[?] * Google Play SDK index /[?] * Android Developers * Design & Plan * App quality * Privacy & Security Improperly trusting ContentProvider-provided filename Stay organized with collections Save and categorize content based on your preferences. OWASP category: MASVS-CODE: Code Quality Overview FileProvider, a subclass of ContentProvider, is intended to provide a secure method for an application ("server application") to share files with another application ("client application"). However, if the client application does not properly handle the filename provided by the server application, an attacker-controlled server application may be able to implement its own malicious FileProvider to overwrite files in the client application's app-specific storage. Impact If an attacker can overwrite an application's files, this can lead to malicious code execution (by overwriting the application's code), or allow otherwise modifying the application's behavior (for example, by overwriting the application's shared preferences or other configuration files). Mitigations Don't Trust User Input Prefer working without user input when using file system calls by generating a unique filename when writing the received file to storage. In other words: When the client application writes the received file to storage, it should ignore the filename provided by the server application and instead use its own internally generated unique identifier as the filename. This example builds upon the code found at https:// developer.android.com/training/secure-file-sharing/request-file: Kotlin // Code in // https://developer.android.com/training/secure-file-sharing/request-file#OpenFile // used to obtain file descriptor (fd) try { val inputStream = FileInputStream(fd) val tempFile = File.createTempFile("temp", null, cacheDir) val outputStream = FileOutputStream(tempFile) val buf = ByteArray(1024) var len: Int len = inputStream.read(buf) while (len > 0) { if (len != -1) { outputStream.write(buf, 0, len) len = inputStream.read(buf) } } inputStream.close() outputStream.close() } catch (e: IOException) { e.printStackTrace() Log.e("MainActivity", "File copy error.") return } Java // Code in // https://developer.android.com/training/secure-file-sharing/request-file#OpenFile // used to obtain file descriptor (fd) FileInputStream inputStream = new FileInputStream(fd); // Create a temporary file File tempFile = File.createTempFile("temp", null, getCacheDir()); // Copy the contents of the file to the temporary file try { OutputStream outputStream = new FileOutputStream(tempFile)) byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); Log.e("MainActivity", "File copy error."); return; } Sanitize Provided Filenames Sanitize the provided filename when writing the received file to storage. This mitigation is less desirable than the preceding mitigation because it can be challenging to handle all potential cases. Nonetheless: If generating a unique filename is not practical, the client application should sanitize the provided filename. Sanitization includes: * Sanitizing path traversal characters in the filename * Performing a canonicalization to confirm there are no path traversals This example code builds upon the guidance on retrieving file information: Kotlin protected fun sanitizeFilename(displayName: String): String { val badCharacters = arrayOf("..", "/") val segments = displayName.split("/") var fileName = segments[segments.size - 1] for (suspString in badCharacters) { fileName = fileName.replace(suspString, "_") } return fileName } val displayName = returnCursor.getString(nameIndex) val fileName = sanitizeFilename(displayName) val filePath = File(context.filesDir, fileName).path // saferOpenFile defined in Android developer documentation val outputFile = saferOpenFile(filePath, context.filesDir.canonicalPath) // fd obtained using Requesting a shared file from Android developer // documentation val inputStream = FileInputStream(fd) // Copy the contents of the file to the new file try { val outputStream = FileOutputStream(outputFile) val buffer = ByteArray(1024) var length: Int while (inputStream.read(buffer).also { length = it } > 0) { outputStream.write(buffer, 0, length) } } catch (e: IOException) { // Handle exception } Java protected String sanitizeFilename(String displayName) { String[] badCharacters = new String[] { "..", "/" }; String[] segments = displayName.split("/"); String fileName = segments[segments.length - 1]; for (String suspString : badCharacters) { fileName = fileName.replace(suspString, "_"); } return fileName; } String displayName = returnCursor.getString(nameIndex); String fileName = sanitizeFilename(displayName); String filePath = new File(context.getFilesDir(), fileName).getPath(); // saferOpenFile defined in Android developer documentation File outputFile = saferOpenFile(filePath, context.getFilesDir().getCanonicalPath()); // fd obtained using Requesting a shared file from Android developer // documentation FileInputStream inputStream = new FileInputStream(fd); // Copy the contents of the file to the new file try { OutputStream outputStream = new FileOutputStream(outputFile)) byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } } catch (IOException e) { // Handle exception } Contributors: Dimitrios Valsamaras and Michael Peck of Microsoft Threat Intelligence Resources * Dirty Stream Attack: Turning Android Share Targets Into Attack Vectors * Secure File Sharing * Request a Shared File documentation * Retrieve Info * FileProvider * Path Traversal * CWE-73 External Control of Filename or Path Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates. Last updated 2024-02-07 UTC. [{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }] * X X Follow @AndroidDev on X * YouTube YouTube Check out Android Developers on YouTube * LinkedIn LinkedIn Connect with the Android Developers community on LinkedIn * More Android + Android + Android for Enterprise + Security + Source + News + Blog + Podcasts * Discover + Gaming + Machine Learning + Health & Fitness + Camera & Media + Privacy + 5G * Android Devices + Large screens + Wear OS + ChromeOS devices + Android for cars + Android TV * Releases + Android 14 + Android 13 + Android 12 + Android 11 + Android 10 + Pie + Oreo + Nougat * Documentation and Downloads + Android Studio guide + Developers guides + API reference + Download Studio + Android NDK * Support + Report platform bug + Report documentation bug + Google Play support + Join research studies Google Developers * Android * Chrome * Firebase * Google Cloud Platform * All products * Privacy * License * Brand guidelines * Manage cookies * Get news and tips by email Subscribe * English * Deutsch * Espanol - America Latina * Francais * Indonesia * Polski * Portugues - Brasil * Tieng Viet * Zhong Wen - Jian Ti * Ri Ben Yu * hangugeo