1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 #include "library_namespaces.h"
17 
18 #include <dirent.h>
19 #include <dlfcn.h>
20 
21 #include <regex>
22 #include <string>
23 #include <vector>
24 
25 #include <android-base/file.h>
26 #include <android-base/logging.h>
27 #include <android-base/macros.h>
28 #include <android-base/properties.h>
29 #include <android-base/strings.h>
30 #include <nativehelper/scoped_utf_chars.h>
31 
32 #include "nativeloader/dlext_namespaces.h"
33 #include "public_libraries.h"
34 #include "utils.h"
35 
36 namespace android::nativeloader {
37 
38 namespace {
39 // The device may be configured to have the vendor libraries loaded to a separate namespace.
40 // For historical reasons this namespace was named sphal but effectively it is intended
41 // to use to load vendor libraries to separate namespace with controlled interface between
42 // vendor and system namespaces.
43 constexpr const char* kVendorNamespaceName = "sphal";
44 constexpr const char* kVndkNamespaceName = "vndk";
45 constexpr const char* kVndkProductNamespaceName = "vndk_product";
46 constexpr const char* kArtNamespaceName = "com_android_art";
47 constexpr const char* kNeuralNetworksNamespaceName = "com_android_neuralnetworks";
48 constexpr const char* kStatsdNamespaceName = "com_android_os_statsd";
49 
50 // classloader-namespace is a linker namespace that is created for the loaded
51 // app. To be specific, it is created for the app classloader. When
52 // System.load() is called from a Java class that is loaded from the
53 // classloader, the classloader-namespace namespace associated with that
54 // classloader is selected for dlopen. The namespace is configured so that its
55 // search path is set to the app-local JNI directory and it is linked to the
56 // system namespace with the names of libs listed in the public.libraries.txt.
57 // This way an app can only load its own JNI libraries along with the public libs.
58 constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
59 // Same thing for vendor APKs.
60 constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
61 // If the namespace is shared then add this suffix to form
62 // "classloader-namespace-shared" or "vendor-classloader-namespace-shared",
63 // respectively. A shared namespace (cf. ANDROID_NAMESPACE_TYPE_SHARED) has
64 // inherited all the libraries of the parent classloader namespace, or the
65 // system namespace for the main app classloader. It is used to give full
66 // access to the platform libraries for apps bundled in the system image,
67 // including their later updates installed in /data.
68 constexpr const char* kSharedNamespaceSuffix = "-shared";
69 
70 // (http://b/27588281) This is a workaround for apps using custom classloaders and calling
71 // System.load() with an absolute path which is outside of the classloader library search path.
72 // This list includes all directories app is allowed to access this way.
73 constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
74 
75 constexpr const char* kVendorLibPath = "/vendor/" LIB;
76 constexpr const char* kProductLibPath = "/product/" LIB ":/system/product/" LIB;
77 
78 const std::regex kVendorDexPathRegex("(^|:)/vendor/");
79 const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
80 
81 // Define origin of APK if it is from vendor partition or product partition
82 using ApkOrigin = enum {
83   APK_ORIGIN_DEFAULT = 0,
84   APK_ORIGIN_VENDOR = 1,
85   APK_ORIGIN_PRODUCT = 2,
86 };
87 
GetParentClassLoader(JNIEnv * env,jobject class_loader)88 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
89   jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
90   jmethodID get_parent =
91       env->GetMethodID(class_loader_class, "getParent", "()Ljava/lang/ClassLoader;");
92 
93   return env->CallObjectMethod(class_loader, get_parent);
94 }
95 
GetApkOriginFromDexPath(JNIEnv * env,jstring dex_path)96 ApkOrigin GetApkOriginFromDexPath(JNIEnv* env, jstring dex_path) {
97   ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
98 
99   if (dex_path != nullptr) {
100     ScopedUtfChars dex_path_utf_chars(env, dex_path);
101 
102     if (std::regex_search(dex_path_utf_chars.c_str(), kVendorDexPathRegex)) {
103       apk_origin = APK_ORIGIN_VENDOR;
104     }
105 
106     if (std::regex_search(dex_path_utf_chars.c_str(), kProductDexPathRegex)) {
107       LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
108                           "Dex path contains both vendor and product partition : %s",
109                           dex_path_utf_chars.c_str());
110 
111       apk_origin = APK_ORIGIN_PRODUCT;
112     }
113   }
114   return apk_origin;
115 }
116 
117 }  // namespace
118 
Initialize()119 void LibraryNamespaces::Initialize() {
120   // Once public namespace is initialized there is no
121   // point in running this code - it will have no effect
122   // on the current list of public libraries.
123   if (initialized_) {
124     return;
125   }
126 
127   // android_init_namespaces() expects all the public libraries
128   // to be loaded so that they can be found by soname alone.
129   //
130   // TODO(dimitry): this is a bit misleading since we do not know
131   // if the vendor public library is going to be opened from /vendor/lib
132   // we might as well end up loading them from /system/lib or /product/lib
133   // For now we rely on CTS test to catch things like this but
134   // it should probably be addressed in the future.
135   for (const auto& soname : android::base::Split(preloadable_public_libraries(), ":")) {
136     LOG_ALWAYS_FATAL_IF(dlopen(soname.c_str(), RTLD_NOW | RTLD_NODELETE) == nullptr,
137                         "Error preloading public library %s: %s", soname.c_str(), dlerror());
138   }
139 }
140 
Create(JNIEnv * env,uint32_t target_sdk_version,jobject class_loader,bool is_shared,jstring dex_path,jstring java_library_path,jstring java_permitted_path)141 Result<NativeLoaderNamespace*> LibraryNamespaces::Create(JNIEnv* env, uint32_t target_sdk_version,
142                                                          jobject class_loader, bool is_shared,
143                                                          jstring dex_path,
144                                                          jstring java_library_path,
145                                                          jstring java_permitted_path) {
146   std::string library_path;  // empty string by default.
147 
148   if (java_library_path != nullptr) {
149     ScopedUtfChars library_path_utf_chars(env, java_library_path);
150     library_path = library_path_utf_chars.c_str();
151   }
152 
153   ApkOrigin apk_origin = GetApkOriginFromDexPath(env, dex_path);
154 
155   // (http://b/27588281) This is a workaround for apps using custom
156   // classloaders and calling System.load() with an absolute path which
157   // is outside of the classloader library search path.
158   //
159   // This part effectively allows such a classloader to access anything
160   // under /data and /mnt/expand
161   std::string permitted_path = kWhitelistedDirectories;
162 
163   if (java_permitted_path != nullptr) {
164     ScopedUtfChars path(env, java_permitted_path);
165     if (path.c_str() != nullptr && path.size() > 0) {
166       permitted_path = permitted_path + ":" + path.c_str();
167     }
168   }
169 
170   LOG_ALWAYS_FATAL_IF(FindNamespaceByClassLoader(env, class_loader) != nullptr,
171                       "There is already a namespace associated with this classloader");
172 
173   std::string system_exposed_libraries = default_public_libraries();
174   std::string namespace_name = kClassloaderNamespaceName;
175   ApkOrigin unbundled_app_origin = APK_ORIGIN_DEFAULT;
176   if ((apk_origin == APK_ORIGIN_VENDOR ||
177        (apk_origin == APK_ORIGIN_PRODUCT &&
178         is_product_vndk_version_defined())) &&
179       !is_shared) {
180     unbundled_app_origin = apk_origin;
181     // For vendor / product apks, give access to the vendor / product lib even though
182     // they are treated as unbundled; the libs and apks are still bundled
183     // together in the vendor / product partition.
184     const char* origin_partition;
185     const char* origin_lib_path;
186     const char* llndk_libraries;
187 
188     switch (apk_origin) {
189       case APK_ORIGIN_VENDOR:
190         origin_partition = "vendor";
191         origin_lib_path = kVendorLibPath;
192         llndk_libraries = llndk_libraries_vendor().c_str();
193         break;
194       case APK_ORIGIN_PRODUCT:
195         origin_partition = "product";
196         origin_lib_path = kProductLibPath;
197         llndk_libraries = llndk_libraries_product().c_str();
198         break;
199       default:
200         origin_partition = "unknown";
201         origin_lib_path = "";
202         llndk_libraries = "";
203     }
204     library_path = library_path + ":" + origin_lib_path;
205     permitted_path = permitted_path + ":" + origin_lib_path;
206 
207     // Also give access to LLNDK libraries since they are available to vendor or product
208     system_exposed_libraries = system_exposed_libraries + ":" + llndk_libraries;
209 
210     // Different name is useful for debugging
211     namespace_name = kVendorClassloaderNamespaceName;
212     ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
213           origin_partition, library_path.c_str());
214   } else {
215     // extended public libraries are NOT available to vendor apks, otherwise it
216     // would be system->vendor violation.
217     if (!extended_public_libraries().empty()) {
218       system_exposed_libraries = system_exposed_libraries + ':' + extended_public_libraries();
219     }
220   }
221 
222   if (is_shared) {
223     // Show in the name that the namespace was created as shared, for debugging
224     // purposes.
225     namespace_name = namespace_name + kSharedNamespaceSuffix;
226   }
227 
228   // Create the app namespace
229   NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
230   // Heuristic: the first classloader with non-empty library_path is assumed to
231   // be the main classloader for app
232   // TODO(b/139178525) remove this heuristic by determining this in LoadedApk (or its
233   // friends) and then passing it down to here.
234   bool is_main_classloader = app_main_namespace_ == nullptr && !library_path.empty();
235   // Policy: the namespace for the main classloader is also used as the
236   // anonymous namespace.
237   bool also_used_as_anonymous = is_main_classloader;
238   // Note: this function is executed with g_namespaces_mutex held, thus no
239   // racing here.
240   auto app_ns = NativeLoaderNamespace::Create(
241       namespace_name, library_path, permitted_path, parent_ns, is_shared,
242       target_sdk_version < 24 /* is_greylist_enabled */, also_used_as_anonymous);
243   if (!app_ns.ok()) {
244     return app_ns.error();
245   }
246   // ... and link to other namespaces to allow access to some public libraries
247   bool is_bridged = app_ns->IsBridged();
248 
249   auto system_ns = NativeLoaderNamespace::GetSystemNamespace(is_bridged);
250   if (!system_ns.ok()) {
251     return system_ns.error();
252   }
253 
254   auto linked = app_ns->Link(*system_ns, system_exposed_libraries);
255   if (!linked.ok()) {
256     return linked.error();
257   }
258 
259   auto art_ns = NativeLoaderNamespace::GetExportedNamespace(kArtNamespaceName, is_bridged);
260   // ART APEX does not exist on host, and under certain build conditions.
261   if (art_ns.ok()) {
262     linked = app_ns->Link(*art_ns, art_public_libraries());
263     if (!linked.ok()) {
264       return linked.error();
265     }
266   }
267 
268   // Give access to NNAPI libraries (apex-updated LLNDK library).
269   auto nnapi_ns =
270       NativeLoaderNamespace::GetExportedNamespace(kNeuralNetworksNamespaceName, is_bridged);
271   if (nnapi_ns.ok()) {
272     linked = app_ns->Link(*nnapi_ns, neuralnetworks_public_libraries());
273     if (!linked.ok()) {
274       return linked.error();
275     }
276   }
277 
278   // Give access to VNDK-SP libraries from the 'vndk' namespace for unbundled vendor apps.
279   if (unbundled_app_origin == APK_ORIGIN_VENDOR && !vndksp_libraries_vendor().empty()) {
280     auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkNamespaceName, is_bridged);
281     if (vndk_ns.ok()) {
282       linked = app_ns->Link(*vndk_ns, vndksp_libraries_vendor());
283       if (!linked.ok()) {
284         return linked.error();
285       }
286     }
287   }
288 
289   // Give access to VNDK-SP libraries from the 'vndk_product' namespace for unbundled product apps.
290   if (unbundled_app_origin == APK_ORIGIN_PRODUCT && !vndksp_libraries_product().empty()) {
291     auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkProductNamespaceName, is_bridged);
292     if (vndk_ns.ok()) {
293       linked = app_ns->Link(*vndk_ns, vndksp_libraries_product());
294       if (!linked.ok()) {
295         return linked.error();
296       }
297     }
298   }
299 
300   // Give access to StatsdAPI libraries
301   auto statsd_ns =
302       NativeLoaderNamespace::GetExportedNamespace(kStatsdNamespaceName, is_bridged);
303   if (statsd_ns.ok()) {
304     linked = app_ns->Link(*statsd_ns, statsd_public_libraries());
305     if (!linked.ok()) {
306       return linked.error();
307     }
308   }
309 
310   if (!vendor_public_libraries().empty()) {
311     auto vendor_ns = NativeLoaderNamespace::GetExportedNamespace(kVendorNamespaceName, is_bridged);
312     // when vendor_ns is not configured, link to the system namespace
313     auto target_ns = vendor_ns.ok() ? vendor_ns : system_ns;
314     if (target_ns.ok()) {
315       linked = app_ns->Link(*target_ns, vendor_public_libraries());
316       if (!linked.ok()) {
317         return linked.error();
318       }
319     }
320   }
321 
322   auto& emplaced = namespaces_.emplace_back(
323       std::make_pair(env->NewWeakGlobalRef(class_loader), *app_ns));
324   if (is_main_classloader) {
325     app_main_namespace_ = &emplaced.second;
326   }
327   return &emplaced.second;
328 }
329 
FindNamespaceByClassLoader(JNIEnv * env,jobject class_loader)330 NativeLoaderNamespace* LibraryNamespaces::FindNamespaceByClassLoader(JNIEnv* env,
331                                                                      jobject class_loader) {
332   auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
333                          [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
334                            return env->IsSameObject(value.first, class_loader);
335                          });
336   if (it != namespaces_.end()) {
337     return &it->second;
338   }
339 
340   return nullptr;
341 }
342 
FindParentNamespaceByClassLoader(JNIEnv * env,jobject class_loader)343 NativeLoaderNamespace* LibraryNamespaces::FindParentNamespaceByClassLoader(JNIEnv* env,
344                                                                            jobject class_loader) {
345   jobject parent_class_loader = GetParentClassLoader(env, class_loader);
346 
347   while (parent_class_loader != nullptr) {
348     NativeLoaderNamespace* ns;
349     if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
350       return ns;
351     }
352 
353     parent_class_loader = GetParentClassLoader(env, parent_class_loader);
354   }
355 
356   return nullptr;
357 }
358 
359 }  // namespace android::nativeloader
360