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 
17 #if defined(ART_TARGET_ANDROID)
18 
19 #include "library_namespaces.h"
20 
21 #include <dirent.h>
22 #include <dlfcn.h>
23 
24 #include <regex>
25 #include <string>
26 #include <vector>
27 
28 #include <android-base/file.h>
29 #include <android-base/logging.h>
30 #include <android-base/macros.h>
31 #include <android-base/result.h>
32 #include <android-base/strings.h>
33 #include <nativehelper/scoped_utf_chars.h>
34 
35 #include "nativeloader/dlext_namespaces.h"
36 #include "public_libraries.h"
37 #include "utils.h"
38 
39 namespace android::nativeloader {
40 
41 namespace {
42 
43 constexpr const char* kApexPath = "/apex/";
44 
45 // The device may be configured to have the vendor libraries loaded to a separate namespace.
46 // For historical reasons this namespace was named sphal but effectively it is intended
47 // to use to load vendor libraries to separate namespace with controlled interface between
48 // vendor and system namespaces.
49 constexpr const char* kVendorNamespaceName = "sphal";
50 constexpr const char* kVndkNamespaceName = "vndk";
51 constexpr const char* kVndkProductNamespaceName = "vndk_product";
52 
53 // classloader-namespace is a linker namespace that is created for the loaded
54 // app. To be specific, it is created for the app classloader. When
55 // System.load() is called from a Java class that is loaded from the
56 // classloader, the classloader-namespace namespace associated with that
57 // classloader is selected for dlopen. The namespace is configured so that its
58 // search path is set to the app-local JNI directory and it is linked to the
59 // system namespace with the names of libs listed in the public.libraries.txt.
60 // This way an app can only load its own JNI libraries along with the public libs.
61 constexpr const char* kClassloaderNamespaceName = "classloader-namespace";
62 // Same thing for vendor APKs.
63 constexpr const char* kVendorClassloaderNamespaceName = "vendor-classloader-namespace";
64 // If the namespace is shared then add this suffix to form
65 // "classloader-namespace-shared" or "vendor-classloader-namespace-shared",
66 // respectively. A shared namespace (cf. ANDROID_NAMESPACE_TYPE_SHARED) has
67 // inherited all the libraries of the parent classloader namespace, or the
68 // system namespace for the main app classloader. It is used to give full
69 // access to the platform libraries for apps bundled in the system image,
70 // including their later updates installed in /data.
71 constexpr const char* kSharedNamespaceSuffix = "-shared";
72 
73 // (http://b/27588281) This is a workaround for apps using custom classloaders and calling
74 // System.load() with an absolute path which is outside of the classloader library search path.
75 // This list includes all directories app is allowed to access this way.
76 constexpr const char* kWhitelistedDirectories = "/data:/mnt/expand";
77 
78 constexpr const char* kVendorLibPath = "/vendor/" LIB;
79 constexpr const char* kProductLibPath = "/product/" LIB ":/system/product/" LIB;
80 
81 const std::regex kVendorDexPathRegex("(^|:)/vendor/");
82 const std::regex kProductDexPathRegex("(^|:)(/system)?/product/");
83 
84 // Define origin of APK if it is from vendor partition or product partition
85 using ApkOrigin = enum {
86   APK_ORIGIN_DEFAULT = 0,
87   APK_ORIGIN_VENDOR = 1,
88   APK_ORIGIN_PRODUCT = 2,
89 };
90 
GetParentClassLoader(JNIEnv * env,jobject class_loader)91 jobject GetParentClassLoader(JNIEnv* env, jobject class_loader) {
92   jclass class_loader_class = env->FindClass("java/lang/ClassLoader");
93   jmethodID get_parent =
94       env->GetMethodID(class_loader_class, "getParent", "()Ljava/lang/ClassLoader;");
95 
96   return env->CallObjectMethod(class_loader, get_parent);
97 }
98 
GetApkOriginFromDexPath(const std::string & dex_path)99 ApkOrigin GetApkOriginFromDexPath(const std::string& dex_path) {
100   ApkOrigin apk_origin = APK_ORIGIN_DEFAULT;
101   if (std::regex_search(dex_path, kVendorDexPathRegex)) {
102     apk_origin = APK_ORIGIN_VENDOR;
103   }
104   if (std::regex_search(dex_path, kProductDexPathRegex)) {
105     LOG_ALWAYS_FATAL_IF(apk_origin == APK_ORIGIN_VENDOR,
106                         "Dex path contains both vendor and product partition : %s",
107                         dex_path.c_str());
108 
109     apk_origin = APK_ORIGIN_PRODUCT;
110   }
111   return apk_origin;
112 }
113 
114 }  // namespace
115 
Initialize()116 void LibraryNamespaces::Initialize() {
117   // Once public namespace is initialized there is no
118   // point in running this code - it will have no effect
119   // on the current list of public libraries.
120   if (initialized_) {
121     return;
122   }
123 
124   // Load the preloadable public libraries. Since libnativeloader is in the
125   // com_android_art namespace, use OpenSystemLibrary rather than dlopen to
126   // ensure the libraries are loaded in the system namespace.
127   //
128   // TODO(dimitry): this is a bit misleading since we do not know
129   // if the vendor public library is going to be opened from /vendor/lib
130   // we might as well end up loading them from /system/lib or /product/lib
131   // For now we rely on CTS test to catch things like this but
132   // it should probably be addressed in the future.
133   for (const std::string& soname : android::base::Split(preloadable_public_libraries(), ":")) {
134     void* handle = OpenSystemLibrary(soname.c_str(), RTLD_NOW | RTLD_NODELETE);
135     LOG_ALWAYS_FATAL_IF(handle == nullptr,
136                         "Error preloading public library %s: %s", soname.c_str(), dlerror());
137   }
138 }
139 
140 // "ALL" is a magic name that allows all public libraries even when the
141 // target SDK is > 30. Currently this is used for (Java) shared libraries
142 // which don't use <uses-native-library>
143 // TODO(b/142191088) remove this hack
144 static constexpr const char LIBRARY_ALL[] = "ALL";
145 
146 // Returns the colon-separated list of library names by filtering uses_libraries from
147 // public_libraries. The returned names will actually be available to the app. If the app is pre-S
148 // (<= 30), the filtering is not done; the entire public_libraries are provided.
filter_public_libraries(uint32_t target_sdk_version,const std::vector<std::string> & uses_libraries,const std::string & public_libraries)149 static const std::string filter_public_libraries(
150     uint32_t target_sdk_version, const std::vector<std::string>& uses_libraries,
151     const std::string& public_libraries) {
152   // Apps targeting Android 11 or earlier gets all public libraries
153   if (target_sdk_version <= 30) {
154     return public_libraries;
155   }
156   if (std::find(uses_libraries.begin(), uses_libraries.end(), LIBRARY_ALL) !=
157       uses_libraries.end()) {
158     return public_libraries;
159   }
160   std::vector<std::string> filtered;
161   std::vector<std::string> orig = android::base::Split(public_libraries, ":");
162   for (const auto& lib : uses_libraries) {
163     if (std::find(orig.begin(), orig.end(), lib) != orig.end()) {
164       filtered.emplace_back(lib);
165     }
166   }
167   return android::base::Join(filtered, ":");
168 }
169 
Create(JNIEnv * env,uint32_t target_sdk_version,jobject class_loader,bool is_shared,jstring dex_path_j,jstring java_library_path,jstring java_permitted_path,jstring uses_library_list)170 Result<NativeLoaderNamespace*> LibraryNamespaces::Create(JNIEnv* env, uint32_t target_sdk_version,
171                                                          jobject class_loader, bool is_shared,
172                                                          jstring dex_path_j,
173                                                          jstring java_library_path,
174                                                          jstring java_permitted_path,
175                                                          jstring uses_library_list) {
176   std::string library_path;  // empty string by default.
177   std::string dex_path;
178 
179   if (java_library_path != nullptr) {
180     ScopedUtfChars library_path_utf_chars(env, java_library_path);
181     library_path = library_path_utf_chars.c_str();
182   }
183 
184   if (dex_path_j != nullptr) {
185     ScopedUtfChars dex_path_chars(env, dex_path_j);
186     dex_path = dex_path_chars.c_str();
187   }
188 
189   std::vector<std::string> uses_libraries;
190   if (uses_library_list != nullptr) {
191     ScopedUtfChars names(env, uses_library_list);
192     uses_libraries = android::base::Split(names.c_str(), ":");
193   } else {
194     // uses_library_list could be nullptr when System.loadLibrary is called from a
195     // custom classloader. In that case, we don't know the list of public
196     // libraries because we don't know which apk the classloader is for. Only
197     // choices we can have are 1) allowing all public libs (as before), or 2)
198     // not allowing all but NDK libs. Here we take #1 because #2 would surprise
199     // developers unnecessarily.
200     // TODO(b/142191088) finalize the policy here. We could either 1) allow all
201     // public libs, 2) disallow any lib, or 3) use the libs that were granted to
202     // the first (i.e. app main) classloader.
203     uses_libraries.emplace_back(LIBRARY_ALL);
204   }
205 
206   ApkOrigin apk_origin = GetApkOriginFromDexPath(dex_path);
207 
208   // (http://b/27588281) This is a workaround for apps using custom
209   // classloaders and calling System.load() with an absolute path which
210   // is outside of the classloader library search path.
211   //
212   // This part effectively allows such a classloader to access anything
213   // under /data and /mnt/expand
214   std::string permitted_path = kWhitelistedDirectories;
215 
216   if (java_permitted_path != nullptr) {
217     ScopedUtfChars path(env, java_permitted_path);
218     if (path.c_str() != nullptr && path.size() > 0) {
219       permitted_path = permitted_path + ":" + path.c_str();
220     }
221   }
222 
223   LOG_ALWAYS_FATAL_IF(FindNamespaceByClassLoader(env, class_loader) != nullptr,
224                       "There is already a namespace associated with this classloader");
225 
226   std::string system_exposed_libraries = default_public_libraries();
227   std::string namespace_name = kClassloaderNamespaceName;
228   ApkOrigin unbundled_app_origin = APK_ORIGIN_DEFAULT;
229   if ((apk_origin == APK_ORIGIN_VENDOR ||
230        (apk_origin == APK_ORIGIN_PRODUCT &&
231         is_product_vndk_version_defined())) &&
232       !is_shared) {
233     unbundled_app_origin = apk_origin;
234     // For vendor / product apks, give access to the vendor / product lib even though
235     // they are treated as unbundled; the libs and apks are still bundled
236     // together in the vendor / product partition.
237     const char* origin_partition;
238     const char* origin_lib_path;
239     const char* llndk_libraries;
240 
241     switch (apk_origin) {
242       case APK_ORIGIN_VENDOR:
243         origin_partition = "vendor";
244         origin_lib_path = kVendorLibPath;
245         llndk_libraries = llndk_libraries_vendor().c_str();
246         break;
247       case APK_ORIGIN_PRODUCT:
248         origin_partition = "product";
249         origin_lib_path = kProductLibPath;
250         llndk_libraries = llndk_libraries_product().c_str();
251         break;
252       default:
253         origin_partition = "unknown";
254         origin_lib_path = "";
255         llndk_libraries = "";
256     }
257     library_path = library_path + ":" + origin_lib_path;
258     permitted_path = permitted_path + ":" + origin_lib_path;
259 
260     // Also give access to LLNDK libraries since they are available to vendor or product
261     system_exposed_libraries = system_exposed_libraries + ":" + llndk_libraries;
262 
263     // Different name is useful for debugging
264     namespace_name = kVendorClassloaderNamespaceName;
265     ALOGD("classloader namespace configured for unbundled %s apk. library_path=%s",
266           origin_partition, library_path.c_str());
267   } else {
268     auto libs = filter_public_libraries(target_sdk_version, uses_libraries,
269                                         extended_public_libraries());
270     // extended public libraries are NOT available to vendor apks, otherwise it
271     // would be system->vendor violation.
272     if (!libs.empty()) {
273       system_exposed_libraries = system_exposed_libraries + ':' + libs;
274     }
275   }
276 
277   if (is_shared) {
278     // Show in the name that the namespace was created as shared, for debugging
279     // purposes.
280     namespace_name = namespace_name + kSharedNamespaceSuffix;
281   }
282 
283   // Create the app namespace
284   NativeLoaderNamespace* parent_ns = FindParentNamespaceByClassLoader(env, class_loader);
285   // Heuristic: the first classloader with non-empty library_path is assumed to
286   // be the main classloader for app
287   // TODO(b/139178525) remove this heuristic by determining this in LoadedApk (or its
288   // friends) and then passing it down to here.
289   bool is_main_classloader = app_main_namespace_ == nullptr && !library_path.empty();
290   // Policy: the namespace for the main classloader is also used as the
291   // anonymous namespace.
292   bool also_used_as_anonymous = is_main_classloader;
293   // Note: this function is executed with g_namespaces_mutex held, thus no
294   // racing here.
295   auto app_ns = NativeLoaderNamespace::Create(
296       namespace_name, library_path, permitted_path, parent_ns, is_shared,
297       target_sdk_version < 24 /* is_exempt_list_enabled */, also_used_as_anonymous);
298   if (!app_ns.ok()) {
299     return app_ns.error();
300   }
301   // ... and link to other namespaces to allow access to some public libraries
302   bool is_bridged = app_ns->IsBridged();
303 
304   auto system_ns = NativeLoaderNamespace::GetSystemNamespace(is_bridged);
305   if (!system_ns.ok()) {
306     return system_ns.error();
307   }
308 
309   auto linked = app_ns->Link(&system_ns.value(), system_exposed_libraries);
310   if (!linked.ok()) {
311     return linked.error();
312   }
313 
314   for (const auto&[apex_ns_name, public_libs] : apex_public_libraries()) {
315     auto ns = NativeLoaderNamespace::GetExportedNamespace(apex_ns_name, is_bridged);
316     // Even if APEX namespace is visible, it may not be available to bridged.
317     if (ns.ok()) {
318       linked = app_ns->Link(&ns.value(), public_libs);
319       if (!linked.ok()) {
320         return linked.error();
321       }
322     }
323   }
324 
325   // Give access to VNDK-SP libraries from the 'vndk' namespace for unbundled vendor apps.
326   if (unbundled_app_origin == APK_ORIGIN_VENDOR && !vndksp_libraries_vendor().empty()) {
327     auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkNamespaceName, is_bridged);
328     if (vndk_ns.ok()) {
329       linked = app_ns->Link(&vndk_ns.value(), vndksp_libraries_vendor());
330       if (!linked.ok()) {
331         return linked.error();
332       }
333     }
334   }
335 
336   // Give access to VNDK-SP libraries from the 'vndk_product' namespace for unbundled product apps.
337   if (unbundled_app_origin == APK_ORIGIN_PRODUCT && !vndksp_libraries_product().empty()) {
338     auto vndk_ns = NativeLoaderNamespace::GetExportedNamespace(kVndkProductNamespaceName, is_bridged);
339     if (vndk_ns.ok()) {
340       linked = app_ns->Link(&vndk_ns.value(), vndksp_libraries_product());
341       if (!linked.ok()) {
342         return linked.error();
343       }
344     }
345   }
346 
347   for (const std::string& each_jar_path : android::base::Split(dex_path, ":")) {
348     auto apex_ns_name = FindApexNamespaceName(each_jar_path);
349     if (apex_ns_name.ok()) {
350       const auto& jni_libs = apex_jni_libraries(*apex_ns_name);
351       if (jni_libs != "") {
352         auto apex_ns = NativeLoaderNamespace::GetExportedNamespace(*apex_ns_name, is_bridged);
353         if (apex_ns.ok()) {
354           linked = app_ns->Link(&apex_ns.value(), jni_libs);
355           if (!linked.ok()) {
356             return linked.error();
357           }
358         }
359       }
360     }
361   }
362 
363   auto vendor_libs = filter_public_libraries(target_sdk_version, uses_libraries,
364                                              vendor_public_libraries());
365   if (!vendor_libs.empty()) {
366     auto vendor_ns = NativeLoaderNamespace::GetExportedNamespace(kVendorNamespaceName, is_bridged);
367     // when vendor_ns is not configured, link to the system namespace
368     auto target_ns = vendor_ns.ok() ? vendor_ns : system_ns;
369     if (target_ns.ok()) {
370       linked = app_ns->Link(&target_ns.value(), vendor_libs);
371       if (!linked.ok()) {
372         return linked.error();
373       }
374     }
375   }
376 
377   auto& emplaced = namespaces_.emplace_back(
378       std::make_pair(env->NewWeakGlobalRef(class_loader), *app_ns));
379   if (is_main_classloader) {
380     app_main_namespace_ = &emplaced.second;
381   }
382   return &emplaced.second;
383 }
384 
FindNamespaceByClassLoader(JNIEnv * env,jobject class_loader)385 NativeLoaderNamespace* LibraryNamespaces::FindNamespaceByClassLoader(JNIEnv* env,
386                                                                      jobject class_loader) {
387   auto it = std::find_if(namespaces_.begin(), namespaces_.end(),
388                          [&](const std::pair<jweak, NativeLoaderNamespace>& value) {
389                            return env->IsSameObject(value.first, class_loader);
390                          });
391   if (it != namespaces_.end()) {
392     return &it->second;
393   }
394 
395   return nullptr;
396 }
397 
FindParentNamespaceByClassLoader(JNIEnv * env,jobject class_loader)398 NativeLoaderNamespace* LibraryNamespaces::FindParentNamespaceByClassLoader(JNIEnv* env,
399                                                                            jobject class_loader) {
400   jobject parent_class_loader = GetParentClassLoader(env, class_loader);
401 
402   while (parent_class_loader != nullptr) {
403     NativeLoaderNamespace* ns;
404     if ((ns = FindNamespaceByClassLoader(env, parent_class_loader)) != nullptr) {
405       return ns;
406     }
407 
408     parent_class_loader = GetParentClassLoader(env, parent_class_loader);
409   }
410 
411   return nullptr;
412 }
413 
FindApexNamespaceName(const std::string & location)414 base::Result<std::string> FindApexNamespaceName(const std::string& location) {
415   // Lots of implicit assumptions here: we expect `location` to be of the form:
416   // /apex/modulename/...
417   //
418   // And we extract from it 'modulename', and then apply mangling rule to get namespace name for it.
419   if (android::base::StartsWith(location, kApexPath)) {
420     size_t start_index = strlen(kApexPath);
421     size_t slash_index = location.find_first_of('/', start_index);
422     LOG_ALWAYS_FATAL_IF((slash_index == std::string::npos),
423                         "Error finding namespace of apex: no slash in path %s", location.c_str());
424     std::string name = location.substr(start_index, slash_index - start_index);
425     std::replace(name.begin(), name.end(), '.', '_');
426     return name;
427   }
428   return base::Error();
429 }
430 
431 }  // namespace android::nativeloader
432 
433 #endif  // defined(ART_TARGET_ANDROID)
434