blob: b732a0006698e2c69b51f27d349cc1fe9d7912df [file] [log] [blame]
Andreas Gampe80f5fe52018-03-28 16:23:24 -07001/*
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
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010017#include <metricslogger/metrics_logger.h>
Mathew Inwood73ddda42018-04-03 15:32:32 +010018
Andreas Gampe80f5fe52018-03-28 16:23:24 -070019#include "hidden_api.h"
20
Narayan Kamathe453a8d2018-04-03 15:23:46 +010021#include <nativehelper/scoped_local_ref.h>
22
Andreas Gampe80f5fe52018-03-28 16:23:24 -070023#include "base/dumpable.h"
Narayan Kamathe453a8d2018-04-03 15:23:46 +010024#include "thread-current-inl.h"
25#include "well_known_classes.h"
Andreas Gampe80f5fe52018-03-28 16:23:24 -070026
Mathew Inwood2d4d62f2018-04-12 13:56:37 +010027using android::metricslogger::ComplexEventLogger;
28using android::metricslogger::ACTION_HIDDEN_API_ACCESSED;
29using android::metricslogger::FIELD_HIDDEN_API_ACCESS_METHOD;
30using android::metricslogger::FIELD_HIDDEN_API_ACCESS_DENIED;
31using android::metricslogger::FIELD_HIDDEN_API_SIGNATURE;
32
Andreas Gampe80f5fe52018-03-28 16:23:24 -070033namespace art {
34namespace hiddenapi {
35
Mathew Inwood27199e62018-04-11 16:08:21 +010036// Set to true if we should always print a warning in logcat for all hidden API accesses, not just
37// dark grey and black. This can be set to true for developer preview / beta builds, but should be
38// false for public release builds.
39static constexpr bool kLogAllAccesses = true;
40
Andreas Gampe80f5fe52018-03-28 16:23:24 -070041static inline std::ostream& operator<<(std::ostream& os, AccessMethod value) {
42 switch (value) {
David Brazdil54a99cf2018-04-05 16:57:32 +010043 case kNone:
44 LOG(FATAL) << "Internal access to hidden API should not be logged";
45 UNREACHABLE();
Andreas Gampe80f5fe52018-03-28 16:23:24 -070046 case kReflection:
47 os << "reflection";
48 break;
49 case kJNI:
50 os << "JNI";
51 break;
52 case kLinking:
53 os << "linking";
54 break;
55 }
56 return os;
57}
58
59static constexpr bool EnumsEqual(EnforcementPolicy policy, HiddenApiAccessFlags::ApiList apiList) {
60 return static_cast<int>(policy) == static_cast<int>(apiList);
61}
62
63// GetMemberAction-related static_asserts.
64static_assert(
Andreas Gampe80f5fe52018-03-28 16:23:24 -070065 EnumsEqual(EnforcementPolicy::kDarkGreyAndBlackList, HiddenApiAccessFlags::kDarkGreylist) &&
66 EnumsEqual(EnforcementPolicy::kBlacklistOnly, HiddenApiAccessFlags::kBlacklist),
67 "Mismatch between EnforcementPolicy and ApiList enums");
68static_assert(
Mathew Inwood68693692018-04-05 16:10:25 +010069 EnforcementPolicy::kJustWarn < EnforcementPolicy::kDarkGreyAndBlackList &&
Andreas Gampe80f5fe52018-03-28 16:23:24 -070070 EnforcementPolicy::kDarkGreyAndBlackList < EnforcementPolicy::kBlacklistOnly,
71 "EnforcementPolicy values ordering not correct");
72
73namespace detail {
74
75MemberSignature::MemberSignature(ArtField* field) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010076 class_name_ = field->GetDeclaringClass()->GetDescriptor(&tmp_);
77 member_name_ = field->GetName();
78 type_signature_ = field->GetTypeDescriptor();
79 type_ = kField;
Andreas Gampe80f5fe52018-03-28 16:23:24 -070080}
81
82MemberSignature::MemberSignature(ArtMethod* method) {
Mathew Inwood73ddda42018-04-03 15:32:32 +010083 class_name_ = method->GetDeclaringClass()->GetDescriptor(&tmp_);
84 member_name_ = method->GetName();
85 type_signature_ = method->GetSignature().ToString();
86 type_ = kMethod;
87}
88
89inline std::vector<const char*> MemberSignature::GetSignatureParts() const {
90 if (type_ == kField) {
91 return { class_name_.c_str(), "->", member_name_.c_str(), ":", type_signature_.c_str() };
92 } else {
93 DCHECK_EQ(type_, kMethod);
94 return { class_name_.c_str(), "->", member_name_.c_str(), type_signature_.c_str() };
95 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -070096}
97
98bool MemberSignature::DoesPrefixMatch(const std::string& prefix) const {
99 size_t pos = 0;
Mathew Inwood73ddda42018-04-03 15:32:32 +0100100 for (const char* part : GetSignatureParts()) {
101 size_t count = std::min(prefix.length() - pos, strlen(part));
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700102 if (prefix.compare(pos, count, part, 0, count) == 0) {
103 pos += count;
104 } else {
105 return false;
106 }
107 }
108 // We have a complete match if all parts match (we exit the loop without
109 // returning) AND we've matched the whole prefix.
110 return pos == prefix.length();
111}
112
113bool MemberSignature::IsExempted(const std::vector<std::string>& exemptions) {
114 for (const std::string& exemption : exemptions) {
115 if (DoesPrefixMatch(exemption)) {
116 return true;
117 }
118 }
119 return false;
120}
121
122void MemberSignature::Dump(std::ostream& os) const {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100123 for (const char* part : GetSignatureParts()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700124 os << part;
125 }
126}
127
128void MemberSignature::WarnAboutAccess(AccessMethod access_method,
129 HiddenApiAccessFlags::ApiList list) {
Mathew Inwood73ddda42018-04-03 15:32:32 +0100130 LOG(WARNING) << "Accessing hidden " << (type_ == kField ? "field " : "method ")
131 << Dumpable<MemberSignature>(*this) << " (" << list << ", " << access_method << ")";
132}
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100133// Convert an AccessMethod enum to a value for logging from the proto enum.
134// This method may look odd (the enum values are current the same), but it
135// prevents coupling the internal enum to the proto enum (which should never
136// be changed) so that we are free to change the internal one if necessary in
137// future.
138inline static int32_t GetEnumValueForLog(AccessMethod access_method) {
139 switch (access_method) {
140 case kNone:
141 return android::metricslogger::ACCESS_METHOD_NONE;
142 case kReflection:
143 return android::metricslogger::ACCESS_METHOD_REFLECTION;
144 case kJNI:
145 return android::metricslogger::ACCESS_METHOD_JNI;
146 case kLinking:
147 return android::metricslogger::ACCESS_METHOD_LINKING;
148 default:
149 DCHECK(false);
150 }
151}
Mathew Inwood73ddda42018-04-03 15:32:32 +0100152
153void MemberSignature::LogAccessToEventLog(AccessMethod access_method, Action action_taken) {
154 if (access_method == kLinking) {
155 // Linking warnings come from static analysis/compilation of the bytecode
156 // and can contain false positives (i.e. code that is never run). We choose
157 // not to log these in the event log.
158 return;
159 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100160 ComplexEventLogger log_maker(ACTION_HIDDEN_API_ACCESSED);
161 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_METHOD, GetEnumValueForLog(access_method));
Mathew Inwood73ddda42018-04-03 15:32:32 +0100162 if (action_taken == kDeny) {
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100163 log_maker.AddTaggedData(FIELD_HIDDEN_API_ACCESS_DENIED, 1);
Mathew Inwood73ddda42018-04-03 15:32:32 +0100164 }
Mathew Inwood2d4d62f2018-04-12 13:56:37 +0100165 std::ostringstream signature_str;
166 Dump(signature_str);
167 log_maker.AddTaggedData(FIELD_HIDDEN_API_SIGNATURE, signature_str.str());
168 log_maker.Record();
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700169}
170
171template<typename T>
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100172Action GetMemberActionImpl(T* member, Action action, AccessMethod access_method) {
David Brazdil54a99cf2018-04-05 16:57:32 +0100173 DCHECK_NE(action, kAllow);
174
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700175 // Get the signature, we need it later.
176 MemberSignature member_signature(member);
177
178 Runtime* runtime = Runtime::Current();
179
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100180 // Check for an exemption first. Exempted APIs are treated as white list.
181 // We only do this if we're about to deny, or if the app is debuggable. This is because:
182 // - we only print a warning for light greylist violations for debuggable apps
183 // - for non-debuggable apps, there is no distinction between light grey & whitelisted APIs.
184 // - we want to avoid the overhead of checking for exemptions for light greylisted APIs whenever
185 // possible.
Mathew Inwood27199e62018-04-11 16:08:21 +0100186 if (kLogAllAccesses || action == kDeny || runtime->IsJavaDebuggable()) {
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700187 if (member_signature.IsExempted(runtime->GetHiddenApiExemptions())) {
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100188 action = kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700189 // Avoid re-examining the exemption list next time.
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100190 // Note this results in no warning for the member, which seems like what one would expect.
191 // Exemptions effectively adds new members to the whitelist.
Mathew Inwood64ee8ae2018-04-09 12:24:55 +0100192 if (runtime->ShouldDedupeHiddenApiWarnings()) {
193 member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
194 member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
195 }
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100196 return kAllow;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700197 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700198
Mathew Inwoodc8ce5f52018-04-05 13:58:55 +0100199 if (access_method != kNone) {
200 // Print a log message with information about this class member access.
201 // We do this if we're about to block access, or the app is debuggable.
202 member_signature.WarnAboutAccess(access_method,
203 HiddenApiAccessFlags::DecodeFromRuntime(member->GetAccessFlags()));
204 }
David Brazdil54a99cf2018-04-05 16:57:32 +0100205 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700206
Mathew Inwood73ddda42018-04-03 15:32:32 +0100207 if (kIsTargetBuild) {
208 uint32_t eventLogSampleRate = runtime->GetHiddenApiEventLogSampleRate();
209 // Assert that RAND_MAX is big enough, to ensure sampling below works as expected.
210 static_assert(RAND_MAX >= 0xffff, "RAND_MAX too small");
211 if (eventLogSampleRate != 0 &&
212 (static_cast<uint32_t>(std::rand()) & 0xffff) < eventLogSampleRate) {
213 member_signature.LogAccessToEventLog(access_method, action);
214 }
215 }
216
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700217 if (action == kDeny) {
218 // Block access
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100219 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700220 }
221
222 // Allow access to this member but print a warning.
223 DCHECK(action == kAllowButWarn || action == kAllowButWarnAndToast);
224
David Brazdil54a99cf2018-04-05 16:57:32 +0100225 if (access_method != kNone) {
226 // Depending on a runtime flag, we might move the member into whitelist and
227 // skip the warning the next time the member is accessed.
228 if (runtime->ShouldDedupeHiddenApiWarnings()) {
229 member->SetAccessFlags(HiddenApiAccessFlags::EncodeForRuntime(
230 member->GetAccessFlags(), HiddenApiAccessFlags::kWhitelist));
231 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700232
David Brazdil54a99cf2018-04-05 16:57:32 +0100233 // If this action requires a UI warning, set the appropriate flag.
234 if (action == kAllowButWarnAndToast || runtime->ShouldAlwaysSetHiddenApiWarningFlag()) {
235 runtime->SetPendingHiddenApiWarning(true);
236 }
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700237 }
238
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100239 return action;
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700240}
241
242// Need to instantiate this.
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100243template Action GetMemberActionImpl<ArtField>(ArtField* member,
244 Action action,
245 AccessMethod access_method);
246template Action GetMemberActionImpl<ArtMethod>(ArtMethod* member,
247 Action action,
248 AccessMethod access_method);
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700249} // namespace detail
Narayan Kamathe453a8d2018-04-03 15:23:46 +0100250
251template<typename T>
252void NotifyHiddenApiListener(T* member) {
253 Runtime* runtime = Runtime::Current();
254 if (!runtime->IsAotCompiler()) {
255 ScopedObjectAccessUnchecked soa(Thread::Current());
256
257 ScopedLocalRef<jobject> consumer_object(soa.Env(),
258 soa.Env()->GetStaticObjectField(
259 WellKnownClasses::dalvik_system_VMRuntime,
260 WellKnownClasses::dalvik_system_VMRuntime_nonSdkApiUsageConsumer));
261 // If the consumer is non-null, we call back to it to let it know that we
262 // have encountered an API that's in one of our lists.
263 if (consumer_object != nullptr) {
264 detail::MemberSignature member_signature(member);
265 std::ostringstream member_signature_str;
266 member_signature.Dump(member_signature_str);
267
268 ScopedLocalRef<jobject> signature_str(
269 soa.Env(),
270 soa.Env()->NewStringUTF(member_signature_str.str().c_str()));
271
272 // Call through to Consumer.accept(String memberSignature);
273 soa.Env()->CallVoidMethod(consumer_object.get(),
274 WellKnownClasses::java_util_function_Consumer_accept,
275 signature_str.get());
276 }
277 }
278}
279
280template void NotifyHiddenApiListener<ArtMethod>(ArtMethod* member);
281template void NotifyHiddenApiListener<ArtField>(ArtField* member);
282
Andreas Gampe80f5fe52018-03-28 16:23:24 -0700283} // namespace hiddenapi
284} // namespace art