├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── SafeContentResolver-v14 ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── cpp │ ├── CMakeLists.txt │ └── os-compat.c │ └── java │ └── de │ └── cketti │ └── safecontentresolver │ ├── ErrnoException.java │ ├── Os.java │ ├── SafeContentResolverApi14.java │ └── SafeContentResolverCompat.java ├── SafeContentResolver ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── de │ └── cketti │ └── safecontentresolver │ ├── DisallowedProviders.java │ ├── SafeContentResolver.java │ └── SafeContentResolverApi21.java ├── android-mvn-push.gradle ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── build.gradle ├── lint.xml └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── sample.txt │ ├── java │ └── de │ │ └── cketti │ │ └── safecontentresolver │ │ └── sample │ │ ├── MainActivity.java │ │ ├── SampleApplication.java │ │ ├── SampleContentProvider.java │ │ ├── SampleInternalContentProvider.java │ │ └── ShareReceiverActivity.java │ └── res │ ├── layout │ ├── activity_main.xml │ └── activity_share_receiver.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .cxx/ 3 | /.idea/ 4 | .gradle 5 | /local.properties 6 | .DS_Store 7 | /captures 8 | build/ 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | ## Version 1.0.0 5 | 6 | _2020-06-24_ 7 | 8 | * Removed dependency on com.android.support:support-annotations so the library doesn't have to be jetified 9 | when used in an app with AndroidX. 10 | * Updated to ReLinker 1.4.1 11 | * Supported ABIs: armeabi-v7a, arm64-v8a, x86, x86_64 12 | 13 | ## Version 0.9.0 14 | 15 | _2016-08-04_ 16 | 17 | * Use [ReLinker](https://github.com/KeepSafe/ReLinker) to load the os-compat library. This should avoid 18 | `UnsatisfiedLinkError` crashes. 19 | 20 | ## Version 0.1.0 21 | 22 | _2016-04-12_ 23 | 24 | * In addition to files belonging to the app `SafeContentResolver` now blocks access to content providers belonging to 25 | the app. 26 | To allow access to a specific content provider, add the following `` element to the appropriate 27 | `` entry in your manifest: 28 | 29 | ```xml 30 | 31 | 34 | 35 | ``` 36 | 37 | ## Version 0.0.1 38 | 39 | _2016-04-04_ 40 | 41 | * Initial release 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SafeContentResolver 2 | 3 | A replacement for Android's [`ContentResolver`](https://developer.android.com/reference/android/content/ContentResolver.html) 4 | that protects against the *Surreptitious Sharing* attack. 5 | 6 | ## Surreptitious Sharing 7 | 8 | Read all about it in the [corresponding blog post](https://www.ibr.cs.tu-bs.de/news/ibr/surreptitious-sharing-2016-04-04.xml). 9 | 10 | ## Usage 11 | 12 | Replace all occurrences of [`ContentResolver.openInputStream()`](https://developer.android.com/reference/android/content/ContentResolver.html#openInputStream(android.net.Uri)) 13 | where URIs provided by other apps are opened with `SafeContentResolver.openInputStream()`. 14 | 15 | `SafeContentResolver` will refuse to open `file://` URIs pointing to files belonging to your app and `content://` URIs 16 | belonging to content providers of your app. 17 | If you wish to allow access to certain content providers, add the following `` element to the appropriate 18 | `` entries in your manifest: 19 | ```xml 20 | 21 | 24 | 25 | ``` 26 | 27 | The library comes in two flavors `safe-content-resolver-v14` and `safe-content-resolver-v21`. The former includes 28 | native code to be able to invoke the `fstat` system call that is used to retrieve the owner of a file. Starting with 29 | Lollipop (API 21) the framework includes the class [`Os`](https://developer.android.com/reference/android/system/Os.html) 30 | to access this functionality. So `safe-content-resolver-v21` is free of native code and thus much smaller. 31 | 32 | To retrieve an instance of `SafeContentResolver` use: 33 | ```java 34 | SafeContentResolver safeContentResolver = SafeContentResolverCompat.newInstance(context); 35 | ``` 36 | 37 | If your `minSdkVersion` is 21 or higher you only need to include `safe-content-resolver-v21` and use the following code: 38 | ```java 39 | SafeContentResolver safeContentResolver = SafeContentResolver.newInstance(context); 40 | ``` 41 | 42 | ## Include the library 43 | 44 | ```groovy 45 | implementation 'de.cketti.safecontentresolver:safe-content-resolver-v14:1.0.0' 46 | ``` 47 | 48 | Or, if you're using `minSdkVersion` 21 or higher: 49 | 50 | ```groovy 51 | implementation 'de.cketti.safecontentresolver:safe-content-resolver-v21:1.0.0' 52 | ``` 53 | 54 | ## Native code 55 | 56 | `safe-content-resolver-v14` contains native code for the following ABIs: 57 | * armeabi-v7a 58 | * arm64-v8a 59 | * x86 60 | * x86_64 61 | 62 | If you don't want to include all of them in your APK you might want to look into 63 | [ABIs Splits](https://developer.android.com/studio/build/configure-apk-splits.html#configure-abi-split). 64 | 65 | 66 | ## License 67 | 68 | Licensed under the Apache License, Version 2.0 (the "License"); 69 | you may not use this file except in compliance with the License. 70 | You may obtain a copy of the License at 71 | 72 | http://www.apache.org/licenses/LICENSE-2.0 73 | 74 | Unless required by applicable law or agreed to in writing, software 75 | distributed under the License is distributed on an "AS IS" BASIS, 76 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 77 | See the License for the specific language governing permissions and 78 | limitations under the License. 79 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply from: '../android-mvn-push.gradle' 3 | 4 | ext { 5 | artifactId = "safe-content-resolver-v14" 6 | } 7 | 8 | android { 9 | compileSdkVersion rootProject.compileSdkVersion 10 | buildToolsVersion rootProject.buildToolsVersion 11 | 12 | defaultConfig { 13 | minSdkVersion 14 14 | } 15 | 16 | externalNativeBuild { 17 | cmake { 18 | path file('src/main/cpp/CMakeLists.txt') 19 | version "3.10.2" 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | api project(':SafeContentResolver') 26 | implementation 'com.getkeepsafe.relinker:relinker:1.4.1' 27 | implementation 'org.jetbrains:annotations:19.0.0' 28 | } 29 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # For more information about using CMake with Android Studio, read the 2 | # documentation: https://d.android.com/studio/projects/add-native-code.html 3 | 4 | # Sets the minimum version of CMake required to build the native library. 5 | 6 | cmake_minimum_required(VERSION 3.10.2) 7 | 8 | # Declares and names the project. 9 | 10 | project("os-compat") 11 | 12 | # Creates and names a library, sets it as either STATIC 13 | # or SHARED, and provides the relative paths to its source code. 14 | # You can define multiple libraries, and CMake builds them for you. 15 | # Gradle automatically packages shared libraries with your APK. 16 | 17 | add_library( # Sets the name of the library. 18 | os-compat 19 | 20 | # Sets the library as a shared library. 21 | SHARED 22 | 23 | # Provides a relative path to your source file(s). 24 | os-compat.c ) 25 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/cpp/os-compat.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * Copyright (C) 2009 The Android Open Source Project 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | 23 | #define TEMP_FAILURE_RETRY(exp) ({ \ 24 | __typeof__(exp) _rc; \ 25 | do { \ 26 | _rc = (exp); \ 27 | } while (_rc == -1 && errno == EINTR); \ 28 | _rc; }) 29 | 30 | 31 | JNIEXPORT jint JNICALL 32 | Java_de_cketti_safecontentresolver_Os_nativeFstat(JNIEnv *env, jclass type, jint fileDescriptor) { 33 | struct stat sb; 34 | 35 | int rc = TEMP_FAILURE_RETRY(fstat(fileDescriptor, &sb)); 36 | if (rc == -1) { 37 | int error = errno; 38 | jclass errnoExceptionClass = (*env)->FindClass(env, "de/cketti/safecontentresolver/ErrnoException"); 39 | jmethodID constructor = (*env)->GetMethodID(env, errnoExceptionClass, "", "(Ljava/lang/String;I)V"); 40 | jstring functionName = (*env)->NewStringUTF(env, "fstat"); 41 | jobject exception = (*env)->NewObject(env, errnoExceptionClass, constructor, functionName, error); 42 | (*env)->Throw(env, exception); 43 | return 0; 44 | } 45 | 46 | return sb.st_uid; 47 | } 48 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/java/de/cketti/safecontentresolver/ErrnoException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package de.cketti.safecontentresolver; 17 | 18 | 19 | class ErrnoException extends Exception { 20 | private final String functionName; 21 | public final int errno; 22 | 23 | 24 | public ErrnoException(String functionName, int errno) { 25 | this.functionName = functionName; 26 | this.errno = errno; 27 | } 28 | 29 | @Override 30 | public String getMessage() { 31 | return functionName + " failed: " + errno; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/java/de/cketti/safecontentresolver/Os.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package de.cketti.safecontentresolver; 17 | 18 | 19 | import android.content.Context; 20 | 21 | import com.getkeepsafe.relinker.MissingLibraryException; 22 | import com.getkeepsafe.relinker.ReLinker; 23 | 24 | 25 | class Os { 26 | private static final String LIBRARY_NAME = "os-compat"; 27 | 28 | private static Context context; 29 | private static boolean libraryNeedsLoading = true; 30 | private static UnsupportedOperationException loadFailedException; 31 | 32 | 33 | synchronized static void init(Context context) { 34 | if (context == null) { 35 | throw new NullPointerException("Argument 'context' must not be null"); 36 | } 37 | 38 | // Only get the context here. Load the library before doing the actual work (hopefully in a background thread). 39 | if (Os.context == null) { 40 | Os.context = context.getApplicationContext(); 41 | } 42 | } 43 | 44 | static int fstat(int fileDescriptor) throws ErrnoException, UnsupportedOperationException { 45 | synchronized (Os.class) { 46 | if (context == null) { 47 | throw new IllegalStateException("Call Os.init(Context) before attempting to call Os.fstat()"); 48 | } 49 | 50 | if (libraryNeedsLoading) { 51 | loadLibrary(); 52 | } else if (loadFailedException != null) { 53 | throw loadFailedException; 54 | } 55 | } 56 | 57 | return nativeFstat(fileDescriptor); 58 | } 59 | 60 | private static void loadLibrary() { 61 | libraryNeedsLoading = false; 62 | try { 63 | ReLinker.loadLibrary(context, LIBRARY_NAME); 64 | } catch (MissingLibraryException | UnsatisfiedLinkError e) { 65 | loadFailedException = new UnsupportedOperationException("Failed to load native library " + LIBRARY_NAME, e); 66 | throw loadFailedException; 67 | } 68 | } 69 | 70 | private static native int nativeFstat(int fileDescriptor) throws ErrnoException; 71 | } 72 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/java/de/cketti/safecontentresolver/SafeContentResolverApi14.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package de.cketti.safecontentresolver; 17 | 18 | 19 | import java.io.FileDescriptor; 20 | import java.io.FileNotFoundException; 21 | import java.lang.reflect.Field; 22 | 23 | import android.content.Context; 24 | 25 | import org.jetbrains.annotations.NotNull; 26 | 27 | 28 | class SafeContentResolverApi14 extends SafeContentResolver { 29 | SafeContentResolverApi14(Context context) { 30 | super(context); 31 | Os.init(context); 32 | } 33 | 34 | @Override 35 | protected int getFileUidOrThrow(@NotNull FileDescriptor fileDescriptor) throws FileNotFoundException { 36 | try { 37 | int systemFileDescriptor = extractSystemFileDescriptor(fileDescriptor); 38 | 39 | return Os.fstat(systemFileDescriptor); 40 | } catch (ErrnoException | UnsupportedOperationException e) { 41 | throw new FileNotFoundException(e.getMessage()); 42 | } 43 | } 44 | 45 | private int extractSystemFileDescriptor(FileDescriptor fileDescriptor) throws FileNotFoundException { 46 | Field descriptor; 47 | try { 48 | descriptor = fileDescriptor.getClass().getDeclaredField("descriptor"); 49 | } catch (NoSuchFieldException e) { 50 | throw new FileNotFoundException("Couldn't find field that holds system file descriptor"); 51 | } 52 | 53 | descriptor.setAccessible(true); 54 | 55 | try { 56 | return descriptor.getInt(fileDescriptor); 57 | } catch (IllegalAccessException e) { 58 | throw new FileNotFoundException("Couldn't read system file descriptor"); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /SafeContentResolver-v14/src/main/java/de/cketti/safecontentresolver/SafeContentResolverCompat.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package de.cketti.safecontentresolver; 17 | 18 | 19 | import android.content.ContentResolver; 20 | import android.content.Context; 21 | import android.os.Build; 22 | 23 | import org.jetbrains.annotations.NotNull; 24 | 25 | 26 | /** 27 | * Helper for creating a {@code SafeContentResolver} instance. 28 | * 29 | *

30 | * The functionality to retrieve the User ID that owns a file was added to the framework in API 21. On versions prior 31 | * to that this library uses a small native code module to ask the operating system for the UID. 32 | *

33 | * This helper takes care of instantiating the appropriate implementation for the Android version the app is running 34 | * on. 35 | *

36 | */ 37 | public final class SafeContentResolverCompat { 38 | 39 | /** 40 | * Create a {@code SafeContentResolver} instance appropriate for the Android version the app is running on. 41 | * 42 | * @param context 43 | * {@link Context} used to retrieve a {@link ContentResolver} instance and the list of content providers 44 | * of this application. 45 | */ 46 | @NotNull 47 | public static SafeContentResolver newInstance(@NotNull Context context) { 48 | //noinspection ConstantConditions 49 | if (context == null) { 50 | throw new NullPointerException("Argument 'context' must not be null"); 51 | } 52 | 53 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 54 | return new SafeContentResolverApi14(context); 55 | } else { 56 | return new SafeContentResolverApi21(context); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /SafeContentResolver/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply from: '../android-mvn-push.gradle' 3 | 4 | ext { 5 | artifactId = "safe-content-resolver-v21" 6 | } 7 | 8 | android { 9 | compileSdkVersion rootProject.compileSdkVersion 10 | buildToolsVersion rootProject.buildToolsVersion 11 | 12 | defaultConfig { 13 | minSdkVersion 21 14 | } 15 | } 16 | 17 | dependencies { 18 | implementation 'org.jetbrains:annotations:19.0.0' 19 | } 20 | -------------------------------------------------------------------------------- /SafeContentResolver/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /SafeContentResolver/src/main/java/de/cketti/safecontentresolver/DisallowedProviders.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package de.cketti.safecontentresolver; 17 | 18 | 19 | import java.util.Collections; 20 | import java.util.HashSet; 21 | import java.util.Set; 22 | 23 | import android.content.Context; 24 | import android.content.pm.PackageInfo; 25 | import android.content.pm.PackageManager; 26 | import android.content.pm.PackageManager.NameNotFoundException; 27 | import android.content.pm.ProviderInfo; 28 | import android.os.Bundle; 29 | 30 | 31 | /** 32 | * Stores a (lazily built) list of all of the app's content providers that are not explicitly allowed to be accessed 33 | * using SafeContentResolver. 34 | */ 35 | class DisallowedProviders { 36 | private static final String META_DATA_KEY_ALLOW_INTERNAL_ACCESS = 37 | "de.cketti.safecontentresolver.ALLOW_INTERNAL_ACCESS"; 38 | 39 | 40 | private final Context context; 41 | private Set disallowedAuthorities; 42 | 43 | 44 | DisallowedProviders(Context context) { 45 | this.context = context; 46 | } 47 | 48 | synchronized boolean isDisallowed(String authority) { 49 | if (disallowedAuthorities == null) { 50 | disallowedAuthorities = findDisallowedContentProviderAuthorities(); 51 | } 52 | 53 | return disallowedAuthorities.contains(authority); 54 | } 55 | 56 | private Set findDisallowedContentProviderAuthorities() { 57 | ProviderInfo[] providers = getProviderInfo(context); 58 | 59 | Set disallowedAuthorities = new HashSet<>(providers.length); 60 | for (ProviderInfo providerInfo : providers) { 61 | if (!isContentProviderAllowed(providerInfo)) { 62 | String[] authorities = providerInfo.authority.split(";"); 63 | Collections.addAll(disallowedAuthorities, authorities); 64 | } 65 | } 66 | 67 | return disallowedAuthorities; 68 | } 69 | 70 | private ProviderInfo[] getProviderInfo(Context context) { 71 | try { 72 | PackageManager packageManager = context.getPackageManager(); 73 | String packageName = context.getPackageName(); 74 | PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 75 | PackageManager.GET_PROVIDERS | PackageManager.GET_META_DATA); 76 | 77 | ProviderInfo[] providers = packageInfo.providers; 78 | return providers != null ? providers : new ProviderInfo[0]; 79 | } catch (NameNotFoundException e) { 80 | throw new RuntimeException(e); 81 | } 82 | } 83 | 84 | private boolean isContentProviderAllowed(ProviderInfo providerInfo) { 85 | Bundle metaData = providerInfo.metaData; 86 | return metaData != null && metaData.getBoolean(META_DATA_KEY_ALLOW_INTERNAL_ACCESS, false); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /SafeContentResolver/src/main/java/de/cketti/safecontentresolver/SafeContentResolver.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * Copyright (C) 2016 Dominik Schürmann 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package de.cketti.safecontentresolver; 18 | 19 | 20 | import java.io.File; 21 | import java.io.FileDescriptor; 22 | import java.io.FileNotFoundException; 23 | import java.io.IOException; 24 | import java.io.InputStream; 25 | 26 | import android.content.ContentResolver; 27 | import android.content.Context; 28 | import android.content.Intent; 29 | import android.content.res.AssetFileDescriptor; 30 | import android.net.Uri; 31 | import android.os.ParcelFileDescriptor; 32 | 33 | import org.jetbrains.annotations.NotNull; 34 | import org.jetbrains.annotations.Nullable; 35 | 36 | 37 | /** 38 | * A replacement for {@code ContentResolver} that protects against the Surreptitious Sharing attack when 39 | * opening {@code file://} URIs. 40 | * 41 | *

42 | * When performing a Surreptitious Sharing attack a malicious app tries to trick the user into sending a file private 43 | * to the target app to an attacker. 44 | *

45 | * Example:
46 | * An {@link Intent#ACTION_SEND} intent that contains the attacker's email address as recipient and a {@code file://} 47 | * URI pointing to the file the email client uses to store account passwords. The attacking app itself doesn't have 48 | * access to this file because Android's security model prevents that. However, the email client has no trouble 49 | * opening a file that belongs to itself. If the user believes this to be a legitimate email with a legitimate 50 | * attachment, e.g. because the malicious app asked them to send a bug report, they will send the email and thereby 51 | * unknowingly expose their email account passwords to the attacker. 52 | *

53 | * If your app is a receiver of such {@code Intents} and you want to protect against this attack, replace all 54 | * occurrences of {@link ContentResolver#openInputStream(Uri)} with {@link SafeContentResolver#openInputStream(Uri)} 55 | * from this class. {@code SafeContentResolver} will refuse to open {@code file://} URIs pointing to files belonging to 56 | * this app and {@code content://} URIs belonging to {@code ContentProvider}s of this app. 57 | *

58 | * If you wish to allow access to certain content providers of your app, add the following {@code } element 59 | * to the appropriate {@code } entries in your manifest: 60 | *

61 | *

 62 |  * <provider …>
 63 |  *    <meta-data
 64 |  *        android:name="de.cketti.safecontentresolver.ALLOW_INTERNAL_ACCESS"
 65 |  *        android:value="true" />
 66 |  * </provider>
 67 |  * 
68 | *

69 | * On older Android versions apps have the ability to create hard 70 | * links to files they don't have read or write access to. That means we can't simply check the absolute file path 71 | * to learn if a file is stored in our own app-private directory. Instead, we use the {@code fstat} system call to 72 | * retrieve the User ID the file belongs to. And if it's identical to the UID of this process, access is denied. 73 | *

74 | */ 75 | public abstract class SafeContentResolver { 76 | private final ContentResolver contentResolver; 77 | private final DisallowedProviders disallowedProviders; 78 | 79 | 80 | /** 81 | * Create a {@link SafeContentResolver} instance. 82 | * 83 | * @param context 84 | * {@link Context} used to retrieve a {@link ContentResolver} instance and the list of content providers 85 | * of this application. 86 | */ 87 | @NotNull 88 | public static SafeContentResolver newInstance(@NotNull Context context) { 89 | //noinspection ConstantConditions 90 | if (context == null) { 91 | throw new NullPointerException("Argument 'context' must not be null."); 92 | } 93 | 94 | return new SafeContentResolverApi21(context); 95 | } 96 | 97 | protected SafeContentResolver(@NotNull Context context) { 98 | this.contentResolver = context.getContentResolver(); 99 | this.disallowedProviders = new DisallowedProviders(context); 100 | } 101 | 102 | /** 103 | * Open a stream to the content associated with a URI. 104 | * 105 | *

106 | * If the provided URI is not a {@code file://} URI, {@link ContentResolver#openInputStream(Uri)} is used to open a 107 | * stream. If it is a {@code file://}, this method makes sure the file isn't owned by this app. 108 | *

109 | * 110 | * @param uri 111 | * The URI pointing to the content to access. 112 | * 113 | * @return {@code InputStream} to access the content. 114 | * 115 | * @throws FileNotFoundException 116 | * If the provided URI could not be opened or if it points to a file owned by this app. 117 | */ 118 | @Nullable 119 | public InputStream openInputStream(@NotNull Uri uri) throws FileNotFoundException { 120 | //noinspection ConstantConditions 121 | if (uri == null) { 122 | throw new NullPointerException("Argument 'uri' must not be null"); 123 | } 124 | 125 | String scheme = uri.getScheme(); 126 | if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { 127 | String authority = uri.getAuthority(); 128 | if (disallowedProviders.isDisallowed(authority)) { 129 | throw new FileNotFoundException("content URI is owned by the application itself. " + 130 | "Content provider is not explicitly allowed: " + authority); 131 | } 132 | } 133 | 134 | if (!ContentResolver.SCHEME_FILE.equals(scheme)) { 135 | return contentResolver.openInputStream(uri); 136 | } 137 | 138 | File file = new File(uri.getPath()); 139 | ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); 140 | FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); 141 | 142 | int fileUid = getFileUidOrThrow(fileDescriptor); 143 | if (fileUid == android.os.Process.myUid()) { 144 | throw new FileNotFoundException("File is owned by the application itself"); 145 | } 146 | 147 | AssetFileDescriptor fd = new AssetFileDescriptor(parcelFileDescriptor, 0, -1); 148 | try { 149 | return fd.createInputStream(); 150 | } catch (IOException e) { 151 | throw new FileNotFoundException("Unable to create stream"); 152 | } 153 | } 154 | 155 | protected abstract int getFileUidOrThrow(@NotNull FileDescriptor fileDescriptor) throws FileNotFoundException; 156 | } 157 | -------------------------------------------------------------------------------- /SafeContentResolver/src/main/java/de/cketti/safecontentresolver/SafeContentResolverApi21.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 cketti 3 | * Copyright (C) 2016 Dominik Schürmann 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | package de.cketti.safecontentresolver; 18 | 19 | 20 | import java.io.FileDescriptor; 21 | import java.io.FileNotFoundException; 22 | 23 | import android.content.Context; 24 | import android.system.Os; 25 | import android.system.StructStat; 26 | 27 | import org.jetbrains.annotations.NotNull; 28 | 29 | 30 | final class SafeContentResolverApi21 extends SafeContentResolver { 31 | SafeContentResolverApi21(Context context) { 32 | super(context); 33 | } 34 | 35 | @Override 36 | protected int getFileUidOrThrow(@NotNull FileDescriptor fileDescriptor) throws FileNotFoundException { 37 | try { 38 | StructStat st = Os.fstat(fileDescriptor); 39 | return st.st_uid; 40 | } catch (android.system.ErrnoException e) { 41 | throw new FileNotFoundException(e.getMessage()); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /android-mvn-push.gradle: -------------------------------------------------------------------------------- 1 | if (!(hasProperty("nexusUsername") && hasProperty("nexusPassword"))) { 2 | return; 3 | } 4 | 5 | apply plugin: 'maven' 6 | apply plugin: 'signing' 7 | 8 | afterEvaluate { project -> 9 | project.version = rootProject.pom.version 10 | project.group = rootProject.pom.group 11 | 12 | uploadArchives { 13 | repositories { 14 | mavenDeployer { 15 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 16 | 17 | pom.artifactId = project.artifactId 18 | 19 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 20 | authentication(userName: nexusUsername, password: nexusPassword) 21 | } 22 | 23 | pom.project { 24 | name rootProject.pom.name 25 | packaging 'aar' 26 | description rootProject.pom.description 27 | url rootProject.pom.url 28 | 29 | scm { 30 | url rootProject.pom.scmUrl 31 | connection rootProject.pom.scmConnection 32 | developerConnection rootProject.pom.scmDevConnection 33 | } 34 | 35 | licenses { 36 | license { 37 | name rootProject.pom.licenseName 38 | url rootProject.pom.licenseUrl 39 | distribution rootProject.pom.licenseDist 40 | } 41 | } 42 | 43 | developers { 44 | developer { 45 | id rootProject.pom.developerId 46 | name rootProject.pom.developerName 47 | } 48 | } 49 | } 50 | } 51 | } 52 | } 53 | 54 | signing { 55 | required { gradle.taskGraph.hasTask("uploadArchives") } 56 | sign configurations.archives 57 | } 58 | 59 | task androidJavadocs(type: Javadoc) { 60 | source = android.sourceSets.main.java.srcDirs 61 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 62 | 63 | options { 64 | linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference" 65 | } 66 | } 67 | 68 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 69 | classifier = 'javadoc' 70 | from androidJavadocs.destinationDir 71 | } 72 | 73 | task androidSourcesJar(type: Jar) { 74 | classifier = 'sources' 75 | from android.sourceSets.main.java.srcDirs 76 | } 77 | 78 | artifacts { 79 | archives androidSourcesJar 80 | archives androidJavadocsJar 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | mavenCentral() 7 | jcenter() 8 | } 9 | dependencies { 10 | classpath "com.android.tools.build:gradle:4.0.0" 11 | 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | mavenCentral() 21 | jcenter() 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | 29 | ext { 30 | pom = [ 31 | group: "de.cketti.safecontentresolver", 32 | name: "SafeContentResolver", 33 | version: "1.0.0", 34 | description: "A replacement for Android's ContentResolver to safely open URIs provided by other apps", 35 | url: "https://github.com/cketti/SafeContentResolver", 36 | 37 | scmUrl: "https://github.com/cketti/SafeContentResolver", 38 | scmConnection: "scm:git@github.com:cketti/SafeContentResolver.git", 39 | scmDevConnection: "scm:git@github.com:cketti/SafeContentResolver.git", 40 | 41 | licenseName: "The Apache Software License, Version 2.0", 42 | licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.txt", 43 | licenseDist: "repo", 44 | 45 | developerId: "cketti", 46 | developerName: "cketti" 47 | ] 48 | 49 | compileSdkVersion = 29 50 | buildToolsVersion = "29.0.3" 51 | } 52 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | android.enableJetifier=false 19 | android.useAndroidX=true 20 | org.gradle.parallel=true 21 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cketti/SafeContentResolver/714d2ab8e97b32b1260594eaa21bb806d9904a80/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion rootProject.compileSdkVersion 5 | buildToolsVersion rootProject.buildToolsVersion 6 | 7 | defaultConfig { 8 | applicationId "de.cketti.safecontentresolver.sample" 9 | 10 | minSdkVersion 14 11 | targetSdkVersion 29 12 | 13 | versionCode 1 14 | versionName "1.0" 15 | } 16 | 17 | aaptOptions { 18 | noCompress 'txt' 19 | } 20 | } 21 | 22 | dependencies { 23 | implementation project(':SafeContentResolver-v14') 24 | implementation 'androidx.appcompat:appcompat:1.1.0' 25 | implementation 'com.squareup.okio:okio:1.17.5' 26 | } 27 | -------------------------------------------------------------------------------- /sample/lint.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 33 | 34 | 37 | 38 | 39 | 40 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /sample/src/main/assets/sample.txt: -------------------------------------------------------------------------------- 1 | sample data 2 | -------------------------------------------------------------------------------- /sample/src/main/java/de/cketti/safecontentresolver/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package de.cketti.safecontentresolver.sample; 2 | 3 | import java.io.File; 4 | 5 | import android.content.Intent; 6 | import android.net.Uri; 7 | import androidx.appcompat.app.AppCompatActivity; 8 | import android.os.Bundle; 9 | import android.view.View; 10 | import android.view.View.OnClickListener; 11 | 12 | 13 | public class MainActivity extends AppCompatActivity { 14 | 15 | @Override 16 | protected void onCreate(Bundle savedInstanceState) { 17 | super.onCreate(savedInstanceState); 18 | setContentView(R.layout.activity_main); 19 | 20 | findViewById(R.id.shareFileButton).setOnClickListener(new OnClickListener() { 21 | @Override 22 | public void onClick(View v) { 23 | shareInternalFile(); 24 | } 25 | }); 26 | findViewById(R.id.shareAllowedContentButton).setOnClickListener(new OnClickListener() { 27 | @Override 28 | public void onClick(View v) { 29 | shareAllowedContent(); 30 | } 31 | }); 32 | findViewById(R.id.shareBlockedContentButton).setOnClickListener(new OnClickListener() { 33 | @Override 34 | public void onClick(View v) { 35 | shareBlockedContent(); 36 | } 37 | }); 38 | } 39 | 40 | private void shareInternalFile() { 41 | File internalFile = SampleApplication.getInternalFile(getApplicationContext()); 42 | Uri streamUri = Uri.fromFile(internalFile); 43 | 44 | Intent shareIntent = new Intent(Intent.ACTION_SEND); 45 | shareIntent.setType("x-test/madeup"); 46 | shareIntent.putExtra(Intent.EXTRA_STREAM, streamUri); 47 | shareIntent.setPackage(getPackageName()); 48 | 49 | startActivity(shareIntent); 50 | } 51 | 52 | private void shareAllowedContent() { 53 | Intent shareIntent = new Intent(Intent.ACTION_SEND); 54 | shareIntent.setType("x-test/madeup"); 55 | Uri contentUri = Uri.parse("content://" + SampleContentProvider.AUTHORITY + "/dummy"); 56 | shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); 57 | shareIntent.setPackage(getPackageName()); 58 | 59 | startActivity(shareIntent); 60 | } 61 | 62 | private void shareBlockedContent() { 63 | Intent shareIntent = new Intent(Intent.ACTION_SEND); 64 | shareIntent.setType("x-test/madeup"); 65 | Uri contentUri = Uri.parse("content://" + SampleInternalContentProvider.AUTHORITY + "/dummy"); 66 | shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); 67 | shareIntent.setPackage(getPackageName()); 68 | 69 | startActivity(shareIntent); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /sample/src/main/java/de/cketti/safecontentresolver/sample/SampleApplication.java: -------------------------------------------------------------------------------- 1 | package de.cketti.safecontentresolver.sample; 2 | 3 | 4 | import java.io.File; 5 | import java.io.IOException; 6 | 7 | import android.app.Application; 8 | import android.content.Context; 9 | import android.os.Build; 10 | import android.os.StrictMode; 11 | 12 | import okio.BufferedSink; 13 | import okio.Okio; 14 | 15 | 16 | public class SampleApplication extends Application { 17 | private static final String INTERNAL_FILE_NAME = "internal.dat"; 18 | 19 | 20 | @Override 21 | public void onCreate() { 22 | super.onCreate(); 23 | 24 | disableFileUriExposedException(); 25 | createInternalFileIfNecessary(); 26 | } 27 | 28 | private void disableFileUriExposedException() { 29 | // We're lazy and just disable all StrictMode.VmPolicy checks 30 | StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().build()); 31 | } 32 | 33 | private void createInternalFileIfNecessary() { 34 | File internalFile = getInternalFile(this); 35 | if (!internalFile.exists()) { 36 | createInternalFile(internalFile); 37 | writeSecretToInternalFile(internalFile); 38 | } 39 | } 40 | 41 | private void createInternalFile(File internalFile) { 42 | try { 43 | boolean success = internalFile.createNewFile(); 44 | if (!success) { 45 | throw new RuntimeException("File wasn't created"); 46 | } 47 | } catch (IOException e) { 48 | throw new RuntimeException("Error creating file", e); 49 | } 50 | } 51 | 52 | private void writeSecretToInternalFile(File internalFile) { 53 | try { 54 | BufferedSink bufferedSink = Okio.buffer(Okio.sink(internalFile)); 55 | try { 56 | bufferedSink.writeUtf8("secret"); 57 | } finally { 58 | bufferedSink.close(); 59 | } 60 | } catch (IOException e) { 61 | throw new RuntimeException("Error writing file", e); 62 | } 63 | } 64 | 65 | static File getInternalFile(Context context) { 66 | File filesDir = context.getFilesDir(); 67 | return new File(filesDir, INTERNAL_FILE_NAME); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /sample/src/main/java/de/cketti/safecontentresolver/sample/SampleContentProvider.java: -------------------------------------------------------------------------------- 1 | package de.cketti.safecontentresolver.sample; 2 | 3 | 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | 7 | import android.content.ContentProvider; 8 | import android.content.ContentValues; 9 | import android.content.res.AssetFileDescriptor; 10 | import android.content.res.AssetManager; 11 | import android.database.Cursor; 12 | import android.net.Uri; 13 | import androidx.annotation.Nullable; 14 | 15 | 16 | public class SampleContentProvider extends ContentProvider { 17 | public static final String AUTHORITY = "de.cketti.safecontentresolver.sample"; 18 | 19 | @Override 20 | public boolean onCreate() { 21 | return true; 22 | } 23 | 24 | @Nullable 25 | @Override 26 | public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { 27 | AssetManager assetManager = getContext().getAssets(); 28 | try { 29 | return assetManager.openFd("sample.txt"); 30 | } catch (IOException e) { 31 | throw new FileNotFoundException("Error: " + e.getMessage()); 32 | } 33 | } 34 | 35 | @Override 36 | public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { 37 | return null; 38 | } 39 | 40 | @Override 41 | public String getType(Uri uri) { 42 | return null; 43 | } 44 | 45 | @Override 46 | public Uri insert(Uri uri, ContentValues values) { 47 | return null; 48 | } 49 | 50 | @Override 51 | public int delete(Uri uri, String selection, String[] selectionArgs) { 52 | return 0; 53 | } 54 | 55 | @Override 56 | public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { 57 | return 0; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /sample/src/main/java/de/cketti/safecontentresolver/sample/SampleInternalContentProvider.java: -------------------------------------------------------------------------------- 1 | package de.cketti.safecontentresolver.sample; 2 | 3 | 4 | public class SampleInternalContentProvider extends SampleContentProvider { 5 | public static final String AUTHORITY = "de.cketti.safecontentresolver.sample.internal"; 6 | } 7 | -------------------------------------------------------------------------------- /sample/src/main/java/de/cketti/safecontentresolver/sample/ShareReceiverActivity.java: -------------------------------------------------------------------------------- 1 | package de.cketti.safecontentresolver.sample; 2 | 3 | 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | 8 | import android.content.Intent; 9 | import android.net.Uri; 10 | import androidx.appcompat.app.AppCompatActivity; 11 | import android.os.Bundle; 12 | import android.widget.TextView; 13 | 14 | import de.cketti.safecontentresolver.SafeContentResolver; 15 | import de.cketti.safecontentresolver.SafeContentResolverCompat; 16 | import okio.BufferedSource; 17 | import okio.Okio; 18 | 19 | 20 | public class ShareReceiverActivity extends AppCompatActivity { 21 | private TextView extraStreamValue; 22 | private TextView extraStreamContentsTraditional; 23 | private TextView extraStreamContentsSafe; 24 | 25 | 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | setContentView(R.layout.activity_share_receiver); 30 | 31 | extraStreamValue = (TextView) findViewById(R.id.extraStreamValue); 32 | extraStreamContentsTraditional = (TextView) findViewById(R.id.extraStreamContentsTraditional); 33 | extraStreamContentsSafe = (TextView) findViewById(R.id.extraStreamContentsSafe); 34 | 35 | Intent intent = getIntent(); 36 | if (Intent.ACTION_SEND.equals(intent.getAction())) { 37 | displaySendIntent(intent); 38 | } else { 39 | finish(); 40 | } 41 | } 42 | 43 | private void displaySendIntent(Intent intent) { 44 | Uri streamUri = intent.getParcelableExtra(Intent.EXTRA_STREAM); 45 | 46 | String streamUriValue = streamUri.toString(); 47 | extraStreamValue.setText(streamUriValue); 48 | 49 | try { 50 | String streamContents = readStreamContentsTraditional(streamUri); 51 | extraStreamContentsTraditional.setText(String.format("\"%s\"", streamContents.trim())); 52 | } catch (FileNotFoundException e) { 53 | extraStreamContentsTraditional.setText("Error opening file: " + e.getMessage()); 54 | } catch (IOException e) { 55 | extraStreamContentsTraditional.setText("Error reading file: " + e.getMessage()); 56 | } 57 | 58 | try { 59 | String streamContents = readStreamContentsSafe(streamUri); 60 | extraStreamContentsSafe.setText(String.format("\"%s\"", streamContents.trim())); 61 | } catch (FileNotFoundException e) { 62 | extraStreamContentsSafe.setText("Error opening file: " + e.getMessage()); 63 | } catch (IOException e) { 64 | extraStreamContentsSafe.setText("Error reading file: " + e.getMessage()); 65 | } 66 | } 67 | 68 | private String readStreamContentsTraditional(Uri streamUri) throws IOException { 69 | InputStream inputStream = getContentResolver().openInputStream(streamUri); 70 | return readStreamContents(inputStream); 71 | } 72 | 73 | private String readStreamContentsSafe(Uri streamUri) throws IOException { 74 | SafeContentResolver safeContentResolver = SafeContentResolverCompat.newInstance(this); 75 | InputStream inputStream = safeContentResolver.openInputStream(streamUri); 76 | return readStreamContents(inputStream); 77 | } 78 | 79 | private String readStreamContents(InputStream inputStream) throws IOException { 80 | if (inputStream == null) { 81 | throw new FileNotFoundException("openInputStreamForFile() returned null"); 82 | } 83 | 84 | BufferedSource bufferedSource = Okio.buffer(Okio.source(inputStream)); 85 | try { 86 | return bufferedSource.readUtf8(); 87 | } finally { 88 | bufferedSource.close(); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 |