1 /*
2 * Copyright (C) 2018 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 #include "hidden_api.h"
18
19 #include <atomic>
20
21 #include "art_field-inl.h"
22 #include "art_method-inl.h"
23 #include "base/dumpable.h"
24 #include "base/file_utils.h"
25 #include "class_root-inl.h"
26 #include "compat_framework.h"
27 #include "dex/class_accessor-inl.h"
28 #include "dex/dex_file_loader.h"
29 #include "mirror/class_ext.h"
30 #include "mirror/proxy.h"
31 #include "nativehelper/scoped_local_ref.h"
32 #include "oat/oat_file.h"
33 #include "scoped_thread_state_change.h"
34 #include "stack.h"
35 #include "thread-inl.h"
36 #include "well_known_classes.h"
37
38 namespace art HIDDEN {
39 namespace hiddenapi {
40
41 // Should be the same as dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_P_HIDDEN_APIS,
42 // dalvik.system.VMRuntime.HIDE_MAXTARGETSDK_Q_HIDDEN_APIS, and
43 // dalvik.system.VMRuntime.ALLOW_TEST_API_ACCESS.
44 // Corresponds to bug ids.
45 static constexpr uint64_t kHideMaxtargetsdkPHiddenApis = 149997251;
46 static constexpr uint64_t kHideMaxtargetsdkQHiddenApis = 149994052;
47 static constexpr uint64_t kAllowTestApiAccess = 166236554;
48
49 static constexpr uint64_t kMaxLogAccessesToLogcat = 100;
50
51 // Should be the same as dalvik.system.VMRuntime.PREVENT_META_REFLECTION_BLOCKLIST_ACCESS.
52 // Corresponds to a bug id.
53 static constexpr uint64_t kPreventMetaReflectionBlocklistAccess = 142365358;
54
55 // Set to true if we should always print a warning in logcat for all hidden API accesses, not just
56 // conditionally and unconditionally blocked. This can be set to true for developer preview / beta
57 // builds, but should be false for public release builds.
58 // Note that when flipping this flag, you must also update the expectations of test 674-hiddenapi
59 // as it affects whether or not we warn for unsupported APIs that have been added to the exemptions
60 // list.
61 static constexpr bool kLogAllAccesses = false;
62
63 // Exemptions for logcat warning. Following signatures do not produce a warning as app developers
64 // should not be alerted on the usage of these unsupported APIs. See b/154851649.
65 static const std::vector<std::string> kWarningExemptions = {
66 "Ljava/nio/Buffer;",
67 "Llibcore/io/Memory;",
68 "Lsun/misc/Unsafe;",
69 };
70
71 // TODO(b/377676642): Fix API annotations and delete this.
72 static const std::vector<std::string> kCorePlatformApiExemptions = {
73 // Intra-core APIs that aren't also core platform APIs. These may be used by
74 // the non-updatable ICU module and hence are effectively de-facto core
75 // platform APIs.
76 "Ldalvik/annotation/compat/VersionCodes;",
77 "Ldalvik/annotation/optimization/ReachabilitySensitive;",
78 "Ldalvik/system/BlockGuard/Policy;->onNetwork",
79 "Ljava/nio/charset/CharsetEncoder;-><init>(Ljava/nio/charset/Charset;FF[BZ)V",
80 "Ljava/security/spec/ECParameterSpec;->getCurveName",
81 "Ljava/security/spec/ECParameterSpec;->setCurveName",
82 "Llibcore/api/CorePlatformApi;",
83 "Llibcore/io/AsynchronousCloseMonitor;",
84 "Llibcore/util/NonNull;",
85 "Llibcore/util/Nullable;",
86 "Lsun/security/util/DerEncoder;",
87 "Lsun/security/x509/AlgorithmId;->derEncode",
88 "Lsun/security/x509/AlgorithmId;->get",
89 // These are new system module APIs that are accessed unflagged (cf.
90 // b/400041178 and b/400041556).
91 "Ldalvik/system/VMDebug;->setCurrentProcessName",
92 "Ldalvik/system/VMDebug;->addApplication",
93 "Ldalvik/system/VMDebug;->removeApplication",
94 "Ldalvik/system/VMDebug;->setUserId",
95 "Ldalvik/system/VMDebug;->setWaitingForDebugger",
96 };
97
operator <<(std::ostream & os,AccessMethod value)98 static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
99 switch (value) {
100 case AccessMethod::kCheck:
101 case AccessMethod::kCheckWithPolicy:
102 LOG(FATAL) << "Internal access to hidden API should not be logged";
103 UNREACHABLE();
104 case AccessMethod::kReflection:
105 os << "reflection";
106 break;
107 case AccessMethod::kJNI:
108 os << "JNI";
109 break;
110 case AccessMethod::kLinking:
111 os << "linking";
112 break;
113 }
114 return os;
115 }
116
operator <<(std::ostream & os,Domain domain)117 static inline std::ostream& operator<<(std::ostream& os, Domain domain) {
118 switch (domain) {
119 case Domain::kCorePlatform:
120 os << "core-platform";
121 break;
122 case Domain::kPlatform:
123 os << "platform";
124 break;
125 case Domain::kApplication:
126 os << "app";
127 break;
128 }
129 return os;
130 }
131
operator <<(std::ostream & os,const AccessContext & value)132 static inline std::ostream& operator<<(std::ostream& os, const AccessContext& value)
133 REQUIRES_SHARED(Locks::mutator_lock_) {
134 if (!value.GetClass().IsNull()) {
135 std::string tmp;
136 os << value.GetClass()->GetDescriptor(&tmp);
137 } else if (value.GetDexFile() != nullptr) {
138 os << value.GetDexFile()->GetLocation();
139 } else {
140 os << "<unknown_caller>";
141 }
142 return os;
143 }
144
FormatHiddenApiRuntimeFlags(uint32_t runtime_flags)145 static const char* FormatHiddenApiRuntimeFlags(uint32_t runtime_flags) {
146 switch (runtime_flags & kAccHiddenapiBits) {
147 case 0:
148 return "0";
149 case kAccPublicApi:
150 return "PublicApi";
151 case kAccCorePlatformApi:
152 return "CorePlatformApi";
153 default:
154 return "?";
155 }
156 }
157
DetermineDomainFromLocation(const std::string & dex_location,ObjPtr<mirror::ClassLoader> class_loader)158 static Domain DetermineDomainFromLocation(const std::string& dex_location,
159 ObjPtr<mirror::ClassLoader> class_loader) {
160 // If running with APEX, check `path` against known APEX locations.
161 // These checks will be skipped on target buildbots where ANDROID_ART_ROOT
162 // is set to "/system".
163 if (ArtModuleRootDistinctFromAndroidRoot()) {
164 if (LocationIsOnArtModule(dex_location) || LocationIsOnConscryptModule(dex_location)) {
165 return Domain::kCorePlatform;
166 }
167
168 if (LocationIsOnApex(dex_location)) {
169 return Domain::kPlatform;
170 }
171 }
172
173 if (LocationIsOnSystemFramework(dex_location)) {
174 return Domain::kPlatform;
175 }
176
177 if (LocationIsOnSystemExtFramework(dex_location)) {
178 return Domain::kPlatform;
179 }
180
181 if (class_loader.IsNull()) {
182 if (kIsTargetBuild && !kIsTargetLinux) {
183 // This is unexpected only when running on Android.
184 LOG(WARNING) << "hiddenapi: DexFile " << dex_location
185 << " is in boot class path but is not in a known location";
186 }
187 return Domain::kPlatform;
188 }
189
190 return Domain::kApplication;
191 }
192
InitializeDexFileDomain(const DexFile & dex_file,ObjPtr<mirror::ClassLoader> class_loader)193 void InitializeDexFileDomain(const DexFile& dex_file, ObjPtr<mirror::ClassLoader> class_loader) {
194 Domain dex_domain = DetermineDomainFromLocation(dex_file.GetLocation(), class_loader);
195
196 // Assign the domain unless a more permissive domain has already been assigned.
197 // This may happen when DexFile is initialized as trusted.
198 if (IsDomainAtLeastAsTrustedAs(dex_domain, dex_file.GetHiddenapiDomain())) {
199 dex_file.SetHiddenapiDomain(dex_domain);
200 }
201 }
202
InitializeCorePlatformApiPrivateFields()203 void InitializeCorePlatformApiPrivateFields() {
204 // The following fields in WellKnownClasses correspond to private fields in the Core Platform
205 // API that cannot be otherwise expressed and propagated through tooling (b/144502743).
206 ArtField* private_core_platform_api_fields[] = {
207 WellKnownClasses::java_io_FileDescriptor_descriptor,
208 WellKnownClasses::java_nio_Buffer_address,
209 WellKnownClasses::java_nio_Buffer_elementSizeShift,
210 WellKnownClasses::java_nio_Buffer_limit,
211 WellKnownClasses::java_nio_Buffer_position,
212 };
213
214 ScopedObjectAccess soa(Thread::Current());
215 for (ArtField* field : private_core_platform_api_fields) {
216 const uint32_t access_flags = field->GetAccessFlags();
217 uint32_t new_access_flags = access_flags | kAccCorePlatformApi;
218 DCHECK(new_access_flags != access_flags);
219 field->SetAccessFlags(new_access_flags);
220 }
221 }
222
GetReflectionCallerAccessContext(Thread * self)223 hiddenapi::AccessContext GetReflectionCallerAccessContext(Thread* self)
224 REQUIRES_SHARED(Locks::mutator_lock_) {
225 // Walk the stack and find the first frame not from java.lang.Class,
226 // java.lang.invoke or java.lang.reflect. This is very expensive.
227 // Save this till the last.
228 struct FirstExternalCallerVisitor : public StackVisitor {
229 explicit FirstExternalCallerVisitor(Thread* thread)
230 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
231 caller(nullptr) {}
232
233 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
234 ArtMethod* m = GetMethod();
235 if (m == nullptr) {
236 // Attached native thread. Assume this is *not* boot class path.
237 caller = nullptr;
238 return false;
239 } else if (m->IsRuntimeMethod()) {
240 // Internal runtime method, continue walking the stack.
241 return true;
242 }
243
244 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass();
245 if (declaring_class->IsBootStrapClassLoaded()) {
246 if (declaring_class->IsClassClass()) {
247 return true;
248 }
249
250 // MethodHandles.makeIdentity is doing findStatic to find hidden methods,
251 // where reflection is used.
252 if (m == WellKnownClasses::java_lang_invoke_MethodHandles_makeIdentity) {
253 return false;
254 }
255
256 // Check classes in the java.lang.invoke package. At the time of writing, the
257 // classes of interest are MethodHandles and MethodHandles.Lookup, but this
258 // is subject to change so conservatively cover the entire package.
259 // NB Static initializers within java.lang.invoke are permitted and do not
260 // need further stack inspection.
261 ObjPtr<mirror::Class> lookup_class = GetClassRoot<mirror::MethodHandlesLookup>();
262 if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class)) &&
263 !m->IsClassInitializer()) {
264 return true;
265 }
266 // Check for classes in the java.lang.reflect package, except for java.lang.reflect.Proxy.
267 // java.lang.reflect.Proxy does its own hidden api checks (https://r.android.com/915496),
268 // and walking over this frame would cause a null pointer dereference
269 // (e.g. in 691-hiddenapi-proxy).
270 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>();
271 CompatFramework& compat_framework = Runtime::Current()->GetCompatFramework();
272 if (declaring_class->IsInSamePackage(proxy_class) && declaring_class != proxy_class) {
273 if (compat_framework.IsChangeEnabled(kPreventMetaReflectionBlocklistAccess)) {
274 return true;
275 }
276 }
277 }
278
279 caller = m;
280 return false;
281 }
282
283 ArtMethod* caller;
284 };
285
286 FirstExternalCallerVisitor visitor(self);
287 visitor.WalkStack();
288
289 // Construct AccessContext from the calling class found on the stack.
290 // If the calling class cannot be determined, e.g. unattached threads,
291 // we conservatively assume the caller is trusted.
292 ObjPtr<mirror::Class> caller =
293 (visitor.caller == nullptr) ? nullptr : visitor.caller->GetDeclaringClass();
294 return caller.IsNull() ? AccessContext(/* is_trusted= */ true) : AccessContext(caller);
295 }
296
297 namespace detail {
298
299 // Do not change the values of items in this enum, as they are written to the
300 // event log for offline analysis. Any changes will interfere with that analysis.
301 enum AccessContextFlags {
302 // Accessed member is a field if this bit is set, else a method
303 kMemberIsField = 1 << 0,
304 // Indicates if access was denied to the member, instead of just printing a warning.
305 kAccessDenied = 1 << 1,
306 };
307
MemberSignature(ArtField * field)308 MemberSignature::MemberSignature(ArtField* field) {
309 // Note: `ArtField::GetDeclaringClassDescriptor()` does not support proxy classes.
310 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
311 member_name_ = field->GetNameView();
312 type_signature_ = field->GetTypeDescriptorView();
313 type_ = kField;
314 }
315
MemberSignature(ArtMethod * method)316 MemberSignature::MemberSignature(ArtMethod* method) {
317 DCHECK(method == method->GetInterfaceMethodIfProxy(kRuntimePointerSize))
318 << "Caller should have replaced proxy method with interface method";
319 class_name_ = method->GetDeclaringClassDescriptorView();
320 member_name_ = method->GetNameView();
321 type_signature_ = method->GetSignature().ToString();
322 type_ = kMethod;
323 }
324
MemberSignature(const ClassAccessor::Field & field)325 MemberSignature::MemberSignature(const ClassAccessor::Field& field) {
326 const DexFile& dex_file = field.GetDexFile();
327 const dex::FieldId& field_id = dex_file.GetFieldId(field.GetIndex());
328 class_name_ = dex_file.GetFieldDeclaringClassDescriptor(field_id);
329 member_name_ = dex_file.GetFieldName(field_id);
330 type_signature_ = dex_file.GetFieldTypeDescriptor(field_id);
331 type_ = kField;
332 }
333
MemberSignature(const ClassAccessor::Method & method)334 MemberSignature::MemberSignature(const ClassAccessor::Method& method) {
335 const DexFile& dex_file = method.GetDexFile();
336 const dex::MethodId& method_id = dex_file.GetMethodId(method.GetIndex());
337 class_name_ = dex_file.GetMethodDeclaringClassDescriptor(method_id);
338 member_name_ = dex_file.GetMethodName(method_id);
339 type_signature_ = dex_file.GetMethodSignature(method_id).ToString();
340 type_ = kMethod;
341 }
342
GetSignatureParts() const343 inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
344 if (type_ == kField) {
345 return {class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str()};
346 } else {
347 DCHECK_EQ(type_, kMethod);
348 return {class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str()};
349 }
350 }
351
DoesPrefixMatch(const std::string & prefix) const352 bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
353 size_t pos = 0;
354 for (const char* part : GetSignatureParts()) {
355 size_t count = std::min(prefix.length() - pos, strlen(part));
356 if (prefix.compare(pos, count, part, 0, count) == 0) {
357 pos += count;
358 } else {
359 return false;
360 }
361 }
362 // We have a complete match if all parts match (we exit the loop without
363 // returning) AND we've matched the whole prefix.
364 return pos == prefix.length();
365 }
366
DoesPrefixMatchAny(const std::vector<std::string> & exemptions)367 bool MemberSignature::DoesPrefixMatchAny(const std::vector<std::string>& exemptions) {
368 for (const std::string& exemption : exemptions) {
369 if (DoesPrefixMatch(exemption)) {
370 return true;
371 }
372 }
373 return false;
374 }
375
Dump(std::ostream & os) const376 void MemberSignature::Dump(std::ostream& os) const {
377 for (const char* part : GetSignatureParts()) {
378 os << part;
379 }
380 }
381
LogAccessToLogcat(AccessMethod access_method,ApiList api_list,bool access_denied,uint32_t runtime_flags,const AccessContext & caller_context,const AccessContext & callee_context,EnforcementPolicy policy)382 void MemberSignature::LogAccessToLogcat(AccessMethod access_method,
383 ApiList api_list,
384 bool access_denied,
385 uint32_t runtime_flags,
386 const AccessContext& caller_context,
387 const AccessContext& callee_context,
388 EnforcementPolicy policy) {
389 static std::atomic<uint64_t> logged_access_count_ = 0;
390 if (logged_access_count_ > kMaxLogAccessesToLogcat) {
391 return;
392 }
393 LOG(access_denied ? (policy == EnforcementPolicy::kEnabled ? ERROR : WARNING) : INFO)
394 << "hiddenapi: Accessing hidden " << (type_ == kField ? "field " : "method ")
395 << Dumpable<MemberSignature>(*this)
396 << " (runtime_flags=" << FormatHiddenApiRuntimeFlags(runtime_flags)
397 << ", domain=" << callee_context.GetDomain() << ", api=" << api_list << ") from "
398 << caller_context << " (domain=" << caller_context.GetDomain() << ") using " << access_method
399 << (access_denied ? ": denied" : ": allowed");
400 if (access_denied && api_list.IsTestApi()) {
401 // see b/177047045 for more details about test api access getting denied
402 LOG(WARNING) << "hiddenapi: If this is a platform test consider enabling "
403 << "VMRuntime.ALLOW_TEST_API_ACCESS change id for this package.";
404 }
405 if (logged_access_count_ >= kMaxLogAccessesToLogcat) {
406 LOG(WARNING) << "hiddenapi: Reached maximum number of hidden api access messages.";
407 }
408 ++logged_access_count_;
409 }
410
Equals(const MemberSignature & other)411 bool MemberSignature::Equals(const MemberSignature& other) {
412 return type_ == other.type_ && class_name_ == other.class_name_ &&
413 member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
414 }
415
MemberNameAndTypeMatch(const MemberSignature & other)416 bool MemberSignature::MemberNameAndTypeMatch(const MemberSignature& other) {
417 return member_name_ == other.member_name_ && type_signature_ == other.type_signature_;
418 }
419
LogAccessToEventLog(uint32_t sampled_value,AccessMethod access_method,bool access_denied)420 void MemberSignature::LogAccessToEventLog(uint32_t sampled_value,
421 AccessMethod access_method,
422 bool access_denied) {
423 #ifdef ART_TARGET_ANDROID
424 if (access_method == AccessMethod::kCheck || access_method == AccessMethod::kCheckWithPolicy ||
425 access_method == AccessMethod::kLinking) {
426 // Checks do not correspond to actual accesses, so should be ignored.
427 // Linking warnings come from static analysis/compilation of the bytecode
428 // and can contain false positives (i.e. code that is never run). Hence we
429 // choose to not log those either in the event log.
430 return;
431 }
432 Runtime* runtime = Runtime::Current();
433 if (runtime->IsAotCompiler()) {
434 return;
435 }
436
437 const std::string& package_name = runtime->GetProcessPackageName();
438 std::ostringstream signature_str;
439 Dump(signature_str);
440
441 ScopedObjectAccess soa(Thread::Current());
442 StackHandleScope<2u> hs(soa.Self());
443 Handle<mirror::String> package_str =
444 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), package_name.c_str()));
445 if (soa.Self()->IsExceptionPending()) {
446 soa.Self()->ClearException();
447 LOG(ERROR) << "hiddenapi: Unable to allocate string for package name which called hidden api";
448 }
449 Handle<mirror::String> signature_jstr =
450 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), signature_str.str().c_str()));
451 if (soa.Self()->IsExceptionPending()) {
452 soa.Self()->ClearException();
453 LOG(ERROR) << "hiddenapi: Unable to allocate string for hidden api method signature";
454 }
455 WellKnownClasses::dalvik_system_VMRuntime_hiddenApiUsed
456 ->InvokeStatic<'V', 'I', 'L', 'L', 'I', 'Z'>(soa.Self(),
457 static_cast<jint>(sampled_value),
458 package_str.Get(),
459 signature_jstr.Get(),
460 static_cast<jint>(access_method),
461 access_denied);
462 if (soa.Self()->IsExceptionPending()) {
463 soa.Self()->ClearException();
464 LOG(ERROR) << "hiddenapi: Unable to report hidden api usage";
465 }
466 #else
467 UNUSED(sampled_value);
468 UNUSED(access_method);
469 UNUSED(access_denied);
470 #endif
471 }
472
NotifyHiddenApiListener(AccessMethod access_method)473 void MemberSignature::NotifyHiddenApiListener(AccessMethod access_method) {
474 if (access_method != AccessMethod::kReflection && access_method != AccessMethod::kJNI) {
475 // We can only up-call into Java during reflection and JNI down-calls.
476 return;
477 }
478
479 Runtime* runtime = Runtime::Current();
480 if (!runtime->IsAotCompiler()) {
481 ScopedObjectAccess soa(Thread::Current());
482 StackHandleScope<2u> hs(soa.Self());
483
484 ArtField* consumer_field = WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer;
485 DCHECK(consumer_field->GetDeclaringClass()->IsInitialized());
486 Handle<mirror::Object> consumer_object =
487 hs.NewHandle(consumer_field->GetObject(consumer_field->GetDeclaringClass()));
488
489 // If the consumer is non-null, we call back to it to let it know that we
490 // have encountered an API that's in one of our lists.
491 if (consumer_object != nullptr) {
492 std::ostringstream member_signature_str;
493 Dump(member_signature_str);
494
495 Handle<mirror::String> signature_str = hs.NewHandle(
496 mirror::String::AllocFromModifiedUtf8(soa.Self(), member_signature_str.str().c_str()));
497 // FIXME: Handle OOME. For now, crash immediatelly (do not continue with a pending exception).
498 CHECK(signature_str != nullptr);
499
500 // Call through to Consumer.accept(String memberSignature);
501 WellKnownClasses::java_util_function_Consumer_accept->InvokeInterface<'V', 'L'>(
502 soa.Self(), consumer_object.Get(), signature_str.Get());
503 }
504 }
505 }
506
CanUpdateRuntimeFlags(ArtField *)507 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtField*) { return true; }
508
CanUpdateRuntimeFlags(ArtMethod * method)509 static ALWAYS_INLINE bool CanUpdateRuntimeFlags(ArtMethod* method) {
510 return !method->IsIntrinsic();
511 }
512
513 template <typename T>
MaybeUpdateAccessFlags(Runtime * runtime,T * member,uint32_t flag)514 static ALWAYS_INLINE void MaybeUpdateAccessFlags(Runtime* runtime, T* member, uint32_t flag)
515 REQUIRES_SHARED(Locks::mutator_lock_) {
516 // Update the access flags unless:
517 // (a) `member` is an intrinsic
518 // (b) this is AOT compiler, as we do not want the updated access flags in the boot/app image
519 // (c) deduping warnings has been explicitly switched off.
520 if (CanUpdateRuntimeFlags(member) && !runtime->IsAotCompiler() &&
521 runtime->ShouldDedupeHiddenApiWarnings()) {
522 member->SetAccessFlags(member->GetAccessFlags() | flag);
523 }
524 }
525
GetMemberDexIndex(ArtField * field)526 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtField* field) {
527 return field->GetDexFieldIndex();
528 }
529
GetMemberDexIndex(ArtMethod * method)530 static ALWAYS_INLINE uint32_t GetMemberDexIndex(ArtMethod* method)
531 REQUIRES_SHARED(Locks::mutator_lock_) {
532 // Use the non-obsolete method to avoid DexFile mismatch between
533 // the method index and the declaring class.
534 return method->GetNonObsoleteMethod()->GetDexMethodIndex();
535 }
536
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Field &)> & fn_visit)537 static void VisitMembers(const DexFile& dex_file,
538 const dex::ClassDef& class_def,
539 const std::function<void(const ClassAccessor::Field&)>& fn_visit) {
540 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
541 accessor.VisitFields(fn_visit, fn_visit);
542 }
543
VisitMembers(const DexFile & dex_file,const dex::ClassDef & class_def,const std::function<void (const ClassAccessor::Method &)> & fn_visit)544 static void VisitMembers(const DexFile& dex_file,
545 const dex::ClassDef& class_def,
546 const std::function<void(const ClassAccessor::Method&)>& fn_visit) {
547 ClassAccessor accessor(dex_file, class_def, /* parse_hiddenapi_class_data= */ true);
548 accessor.VisitMethods(fn_visit, fn_visit);
549 }
550
551 template <typename T>
GetDexFlags(T * member)552 uint32_t GetDexFlags(T* member) REQUIRES_SHARED(Locks::mutator_lock_) {
553 static_assert(std::is_same<T, ArtField>::value || std::is_same<T, ArtMethod>::value);
554 constexpr bool kMemberIsField = std::is_same<T, ArtField>::value;
555 using AccessorType = typename std::conditional<std::is_same<T, ArtField>::value,
556 ClassAccessor::Field,
557 ClassAccessor::Method>::type;
558
559 ObjPtr<mirror::Class> declaring_class = member->GetDeclaringClass();
560 DCHECK(!declaring_class.IsNull()) << "Attempting to access a runtime method";
561
562 ApiList flags = ApiList::Invalid();
563
564 // Check if the declaring class has ClassExt allocated. If it does, check if
565 // the pre-JVMTI redefine dex file has been set to determine if the declaring
566 // class has been JVMTI-redefined.
567 ObjPtr<mirror::ClassExt> ext(declaring_class->GetExtData());
568 const DexFile* original_dex = ext.IsNull() ? nullptr : ext->GetPreRedefineDexFile();
569 if (LIKELY(original_dex == nullptr)) {
570 // Class is not redefined. Find the class def, iterate over its members and
571 // find the entry corresponding to this `member`.
572 const dex::ClassDef* class_def = declaring_class->GetClassDef();
573 if (class_def == nullptr) {
574 // ClassDef is not set for proxy classes. Only their fields can ever be inspected.
575 DCHECK(declaring_class->IsProxyClass())
576 << "Only proxy classes are expected not to have a class def";
577 DCHECK(kMemberIsField)
578 << "Interface methods should be inspected instead of proxy class methods";
579 flags = ApiList::Unsupported();
580 } else {
581 uint32_t member_index = GetMemberDexIndex(member);
582 auto fn_visit = [&](const AccessorType& dex_member) {
583 if (dex_member.GetIndex() == member_index) {
584 flags = ApiList::FromDexFlags(dex_member.GetHiddenapiFlags());
585 }
586 };
587 VisitMembers(declaring_class->GetDexFile(), *class_def, fn_visit);
588 }
589 } else {
590 // Class was redefined using JVMTI. We have a pointer to the original dex file
591 // and the class def index of this class in that dex file, but the field/method
592 // indices are lost. Iterate over all members of the class def and find the one
593 // corresponding to this `member` by name and type string comparison.
594 // This is obviously very slow, but it is only used when non-exempt code tries
595 // to access a hidden member of a JVMTI-redefined class.
596 uint16_t class_def_idx = ext->GetPreRedefineClassDefIndex();
597 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
598 const dex::ClassDef& original_class_def = original_dex->GetClassDef(class_def_idx);
599 MemberSignature member_signature(member);
600 auto fn_visit = [&](const AccessorType& dex_member) {
601 MemberSignature cur_signature(dex_member);
602 if (member_signature.MemberNameAndTypeMatch(cur_signature)) {
603 DCHECK(member_signature.Equals(cur_signature));
604 flags = ApiList::FromDexFlags(dex_member.GetHiddenapiFlags());
605 }
606 };
607 VisitMembers(*original_dex, original_class_def, fn_visit);
608 }
609
610 CHECK(flags.IsValid()) << "Could not find hiddenapi flags for "
611 << Dumpable<MemberSignature>(MemberSignature(member));
612 return flags.GetDexFlags();
613 }
614
615 template <typename T>
HandleCorePlatformApiViolation(T * member,ApiList api_list,uint32_t runtime_flags,const AccessContext & caller_context,const AccessContext & callee_context,AccessMethod access_method,EnforcementPolicy policy)616 bool HandleCorePlatformApiViolation(T* member,
617 ApiList api_list,
618 uint32_t runtime_flags,
619 const AccessContext& caller_context,
620 const AccessContext& callee_context,
621 AccessMethod access_method,
622 EnforcementPolicy policy) {
623 DCHECK(policy != EnforcementPolicy::kDisabled)
624 << "Should never enter this function when access checks are completely disabled";
625
626 if (access_method == AccessMethod::kCheck) {
627 // Always return true for internal checks, so the current enforcement policy
628 // won't affect the caller.
629 return true;
630 }
631
632 if (access_method != AccessMethod::kCheckWithPolicy) {
633 LOG(policy == EnforcementPolicy::kEnabled ? ERROR : WARNING)
634 << "hiddenapi: Core platform API violation: "
635 << Dumpable<MemberSignature>(MemberSignature(member))
636 << " (runtime_flags=" << FormatHiddenApiRuntimeFlags(runtime_flags)
637 << ", domain=" << callee_context.GetDomain() << ", api=" << api_list << ") from "
638 << caller_context << " (domain=" << caller_context.GetDomain() << ")"
639 << " using " << access_method;
640
641 // If policy is set to just warn, add kAccCorePlatformApi to access flags of
642 // `member` to avoid reporting the violation again next time.
643 if (policy == EnforcementPolicy::kJustWarn) {
644 MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
645 }
646 }
647
648 // Deny access if enforcement is enabled.
649 return policy == EnforcementPolicy::kEnabled;
650 }
651
652 template <typename T>
ShouldDenyAccessToMemberImpl(T * member,ApiList api_list,uint32_t runtime_flags,const AccessContext & caller_context,const AccessContext & callee_context,AccessMethod access_method)653 bool ShouldDenyAccessToMemberImpl(T* member,
654 ApiList api_list,
655 uint32_t runtime_flags,
656 const AccessContext& caller_context,
657 const AccessContext& callee_context,
658 AccessMethod access_method)
659 REQUIRES_SHARED(Locks::mutator_lock_) {
660 DCHECK(member != nullptr);
661 Runtime* runtime = Runtime::Current();
662 CompatFramework& compatFramework = runtime->GetCompatFramework();
663
664 EnforcementPolicy hiddenApiPolicy = runtime->GetHiddenApiEnforcementPolicy();
665 DCHECK(hiddenApiPolicy != EnforcementPolicy::kDisabled)
666 << "Should never enter this function when access checks are completely disabled";
667
668 MemberSignature member_signature(member);
669
670 // Check for an exemption first. Exempted APIs are treated as SDK.
671 if (member_signature.DoesPrefixMatchAny(runtime->GetHiddenApiExemptions())) {
672 // Avoid re-examining the exemption list next time.
673 // Note this results in no warning for the member, which seems like what one would expect.
674 // Exemptions effectively adds new members to the public API list.
675 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
676 return false;
677 }
678
679 EnforcementPolicy testApiPolicy = runtime->GetTestApiEnforcementPolicy();
680
681 bool deny_access = false;
682 if (hiddenApiPolicy == EnforcementPolicy::kEnabled) {
683 if (api_list.IsTestApi() && (testApiPolicy == EnforcementPolicy::kDisabled ||
684 compatFramework.IsChangeEnabled(kAllowTestApiAccess))) {
685 deny_access = false;
686 } else {
687 switch (api_list.GetMaxAllowedSdkVersion()) {
688 case SdkVersion::kP:
689 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkPHiddenApis);
690 break;
691 case SdkVersion::kQ:
692 deny_access = compatFramework.IsChangeEnabled(kHideMaxtargetsdkQHiddenApis);
693 break;
694 default:
695 deny_access = IsSdkVersionSetAndMoreThan(runtime->GetTargetSdkVersion(),
696 api_list.GetMaxAllowedSdkVersion());
697 }
698 }
699 }
700
701 if (access_method != AccessMethod::kCheck && access_method != AccessMethod::kCheckWithPolicy) {
702 // Warn if blocked signature is being accessed or it is not exempted.
703 if (deny_access || !member_signature.DoesPrefixMatchAny(kWarningExemptions)) {
704 // Print a log message with information about this class member access.
705 // We do this if we're about to deny access, or the app is debuggable.
706 if (kLogAllAccesses || deny_access || runtime->IsJavaDebuggable()) {
707 member_signature.LogAccessToLogcat(access_method,
708 api_list,
709 deny_access,
710 runtime_flags,
711 caller_context,
712 callee_context,
713 hiddenApiPolicy);
714 }
715
716 // If there is a StrictMode listener, notify it about this violation.
717 member_signature.NotifyHiddenApiListener(access_method);
718 }
719
720 // If event log sampling is enabled, report this violation.
721 if (kIsTargetBuild && !kIsTargetLinux) {
722 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
723 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
724 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
725 if (eventLogSampleRate != 0) {
726 const uint32_t sampled_value = static_cast<uint32_t>(std::rand()) & 0xffff;
727 if (sampled_value <= eventLogSampleRate) {
728 member_signature.LogAccessToEventLog(sampled_value, access_method, deny_access);
729 }
730 }
731 }
732
733 // If this access was not denied, flag member as SDK and skip
734 // the warning the next time the member is accessed. Don't update for
735 // non-debuggable apps as this has a memory cost.
736 if (!deny_access && runtime->IsJavaDebuggable()) {
737 MaybeUpdateAccessFlags(runtime, member, kAccPublicApi);
738 }
739 }
740
741 return deny_access;
742 }
743
744 // Need to instantiate these.
745 template uint32_t GetDexFlags<ArtField>(ArtField* member);
746 template uint32_t GetDexFlags<ArtMethod>(ArtMethod* member);
747 template bool HandleCorePlatformApiViolation(ArtField* member,
748 ApiList api_list,
749 uint32_t runtime_flags,
750 const AccessContext& caller_context,
751 const AccessContext& callee_context,
752 AccessMethod access_method,
753 EnforcementPolicy policy);
754 template bool HandleCorePlatformApiViolation(ArtMethod* member,
755 ApiList api_list,
756 uint32_t runtime_flags,
757 const AccessContext& caller_context,
758 const AccessContext& callee_context,
759 AccessMethod access_method,
760 EnforcementPolicy policy);
761 template bool ShouldDenyAccessToMemberImpl<ArtField>(ArtField* member,
762 ApiList api_list,
763 uint32_t runtime_flags,
764 const AccessContext& caller_context,
765 const AccessContext& callee_context,
766 AccessMethod access_method);
767 template bool ShouldDenyAccessToMemberImpl<ArtMethod>(ArtMethod* member,
768 ApiList api_list,
769 uint32_t runtime_flags,
770 const AccessContext& caller_context,
771 const AccessContext& callee_context,
772 AccessMethod access_method);
773
774 } // namespace detail
775
776 template <typename T>
ShouldDenyAccessToMember(T * member,const std::function<AccessContext ()> & fn_get_access_context,AccessMethod access_method)777 bool ShouldDenyAccessToMember(T* member,
778 const std::function<AccessContext()>& fn_get_access_context,
779 AccessMethod access_method) {
780 DCHECK(member != nullptr);
781
782 // First check if we have an explicit sdk checker installed that should be used to
783 // verify access. If so, make the decision based on it.
784 //
785 // This is used during off-device AOT compilation which may want to generate verification
786 // metadata only for a specific list of public SDKs. Note that the check here is made
787 // based on descriptor equality and it's aim to further restrict a symbol that would
788 // otherwise be resolved.
789 //
790 // The check only applies to boot classpaths dex files.
791 Runtime* runtime = Runtime::Current();
792 if (UNLIKELY(runtime->IsAotCompiler())) {
793 if (member->GetDeclaringClass()->IsBootStrapClassLoaded() &&
794 runtime->GetClassLinker()->DenyAccessBasedOnPublicSdk(member)) {
795 return true;
796 }
797 }
798
799 // Get the runtime flags encoded in member's access flags.
800 // Note: this works for proxy methods because they inherit access flags from their
801 // respective interface methods.
802 const uint32_t runtime_flags = GetRuntimeFlags(member);
803
804 // Exit early if member is public API. This flag is also set for non-boot class
805 // path fields/methods.
806 if ((runtime_flags & kAccPublicApi) != 0) {
807 return false;
808 }
809
810 // Determine which domain the caller and callee belong to.
811 // This can be *very* expensive. This is why ShouldDenyAccessToMember
812 // should not be called on every individual access.
813 const AccessContext caller_context = fn_get_access_context();
814 const AccessContext callee_context(member->GetDeclaringClass());
815
816 // Non-boot classpath callers should have exited early.
817 DCHECK(!callee_context.IsApplicationDomain());
818
819 // Check if the caller is always allowed to access members in the callee context.
820 if (caller_context.CanAlwaysAccess(callee_context)) {
821 return false;
822 }
823
824 // Check if this is platform accessing core platform. We may warn if `member` is
825 // not part of core platform API.
826 switch (caller_context.GetDomain()) {
827 case Domain::kApplication: {
828 DCHECK(!callee_context.IsApplicationDomain());
829
830 // Exit early if access checks are completely disabled.
831 EnforcementPolicy policy = runtime->GetHiddenApiEnforcementPolicy();
832 if (policy == EnforcementPolicy::kDisabled) {
833 return false;
834 }
835
836 // If this is a proxy method, look at the interface method instead.
837 member = detail::GetInterfaceMemberIfProxy(member);
838
839 // Decode hidden API access flags from the dex file.
840 // This is an O(N) operation scaling with the number of fields/methods
841 // in the class. Only do this on slow path and only do it once.
842 ApiList api_list = ApiList::FromDexFlags(detail::GetDexFlags(member));
843 DCHECK(api_list.IsValid());
844
845 // Member is hidden and caller is not exempted. Enter slow path.
846 return detail::ShouldDenyAccessToMemberImpl(
847 member, api_list, runtime_flags, caller_context, callee_context, access_method);
848 }
849
850 case Domain::kPlatform: {
851 DCHECK(callee_context.GetDomain() == Domain::kCorePlatform);
852
853 // Member is part of core platform API. Accessing it is allowed.
854 if ((runtime_flags & kAccCorePlatformApi) != 0) {
855 return false;
856 }
857
858 // Allow access if access checks are disabled.
859 EnforcementPolicy policy = Runtime::Current()->GetCorePlatformApiEnforcementPolicy();
860 if (policy == EnforcementPolicy::kDisabled) {
861 return false;
862 }
863
864 // If this is a proxy method, look at the interface method instead.
865 member = detail::GetInterfaceMemberIfProxy(member);
866
867 // Decode hidden API access flags from the dex file. This is a slow path,
868 // like in the kApplication case above.
869 ApiList api_list = ApiList::FromDexFlags(detail::GetDexFlags(member));
870 DCHECK(api_list.IsValid());
871
872 // Max target SDK versions don't matter for platform callers, but they may
873 // still depend on unsupported APIs. Let's compare against the "max" SDK
874 // version to only allow that (and also proper SDK APIs, but they are
875 // typically combined with kCorePlatformApi already).
876 if (api_list.GetMaxAllowedSdkVersion() == SdkVersion::kMax) {
877 // Allow access and attempt to update the access flags to avoid
878 // re-examining the dex flags next time.
879 detail::MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
880 return false;
881 }
882
883 // Check for exemptions.
884 // TODO(b/377676642): Fix API annotations and delete this.
885 detail::MemberSignature member_signature(member);
886 if (member_signature.DoesPrefixMatchAny(kCorePlatformApiExemptions)) {
887 // Avoid re-examining the exemption list next time.
888 detail::MaybeUpdateAccessFlags(Runtime::Current(), member, kAccCorePlatformApi);
889 return false;
890 }
891
892 // Access checks are not disabled, report the violation.
893 // This may also add kAccCorePlatformApi to the access flags of `member`
894 // so as to not warn again on next access.
895 return detail::HandleCorePlatformApiViolation(
896 member, api_list, runtime_flags, caller_context, callee_context, access_method, policy);
897 }
898
899 case Domain::kCorePlatform: {
900 LOG(FATAL) << "CorePlatform domain should be allowed to access all domains";
901 UNREACHABLE();
902 }
903 }
904 }
905
906 // Need to instantiate these.
907 template bool ShouldDenyAccessToMember<ArtField>(
908 ArtField* member,
909 const std::function<AccessContext()>& fn_get_access_context,
910 AccessMethod access_method);
911 template bool ShouldDenyAccessToMember<ArtMethod>(
912 ArtMethod* member,
913 const std::function<AccessContext()>& fn_get_access_context,
914 AccessMethod access_method);
915
916 } // namespace hiddenapi
917 } // namespace art
918