Debian Codegraph @

tests/DynamicCodeLoggerIntegrationTests/src/com/android/server/pm/dex/DynamicCodeLoggerIntegrationTests.java

raw symbols SCIP
1 /*
2 * Copyright 2017 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 package com.android.server.pm.dex;
18
19 import static com.google.common.truth.Truth.assertThat;
20 import static com.google.common.truth.Truth.assertWithMessage;
21
22 import android.app.UiAutomation;
23 import android.content.Context;
24 import android.os.Build;
25 import android.os.ParcelFileDescriptor;
26 import android.os.SystemClock;
27 import android.util.EventLog;
28 import android.util.EventLog.Event;
29
30 import androidx.test.filters.LargeTest;
31 import androidx.test.platform.app.InstrumentationRegistry;
32
33 import dalvik.system.DexClassLoader;
34
35 import org.junit.Before;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38 import org.junit.runner.RunWith;
39 import org.junit.runners.JUnit4;
40
41 import java.io.ByteArrayOutputStream;
42 import java.io.File;
43 import java.io.FileOutputStream;
44 import java.io.InputStream;
45 import java.io.OutputStream;
46 import java.security.MessageDigest;
47 import java.util.ArrayList;
48 import java.util.Formatter;
49 import java.util.List;
50 import java.util.concurrent.TimeUnit;
51
52 /**
53 * Integration tests for {@link DynamicCodeLogger}.
54 *
55 * The setup for the test dynamically loads code in a jar extracted
56 * from our assets (a secondary dex file).
57 *
58 * We then use shell commands to trigger dynamic code logging (and wait
59 * for it to complete). This causes DynamicCodeLogger to log the hash of the
60 * file's name and content. We verify that this message appears in
61 * the event log.
62 *
63 * Run with "atest DynamicCodeLoggerIntegrationTests".
64 */
65 @LargeTest
66 @RunWith(JUnit4.class)
67 public final class DynamicCodeLoggerIntegrationTests {
68
69 private static final String SHA_256 = "SHA-256";
70
71 // Event log tag used for SNET related events
72 private static final int SNET_TAG = 0x534e4554;
73
74 // Subtags used to distinguish dynamic code loading events
75 private static final String DCL_DEX_SUBTAG = "dcl";
76 private static final String DCL_NATIVE_SUBTAG = "dcln";
77
78 // These are job IDs from DynamicCodeLoggingService
79 private static final int IDLE_LOGGING_JOB_ID = 2030028;
80 private static final int AUDIT_WATCHING_JOB_ID = 203142925;
81
82 // For tests that rely on parsing audit logs, how often to retry. (There are many reasons why
83 // we might not see the audit logs, including throttling and delays in log generation, so to
84 // avoid flakiness we run these tests multiple times, allowing progressively longer between
85 // code loading and checking the logs on each try.)
86 private static final int AUDIT_LOG_RETRIES = 10;
87 private static final int RETRY_DELAY_MS = 500;
88
89 private static Context sContext;
90 private static int sMyUid;
91
92 @BeforeClass
93 public static void setUpAll() {
94 sContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
95 sMyUid = android.os.Process.myUid();
96 }
97
98 @Before
99 public void primeEventLog() {
100 // Force a round trip to logd to make sure everything is up to date.
101 // Without this the first test passes and others don't - we don't see new events in the
102 // log. The exact reason is unclear.
103 EventLog.writeEvent(SNET_TAG, "Dummy event");
104
105 // Audit log messages are throttled by the kernel (at the request of logd) to 5 per
106 // second, so running the tests too quickly in sequence means we lose some and get
107 // spurious failures. Sigh.
108 SystemClock.sleep(1000);
109 }
110
111 @Test
112 public void testGeneratesEvents_standardClassLoader() throws Exception {
113 File privateCopyFile = privateFile("copied.jar");
114 // Obtained via "echo -n copied.jar | sha256sum"
115 String expectedNameHash =
116 "1B6C71DB26F36582867432CCA12FB6A517470C9F9AABE9198DD4C5C030D6DC0C";
117 String expectedContentHash = copyAndHashResource(
118 "/DynamicCodeLoggerTestLibrary.jar", privateCopyFile);
119
120 // Feed the jar to a class loader and make sure it contains what we expect.
121 ClassLoader parentClassLoader = sContext.getClass().getClassLoader();
122 ClassLoader loader =
123 new DexClassLoader(privateCopyFile.toString(), null, null, parentClassLoader);
124 loader.loadClass("com.android.dcl.Simple");
125
126 // And make sure we log events about it
127 long previousEventNanos = mostRecentEventTimeNanos();
128 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
129
130 assertDclLoggedSince(previousEventNanos, DCL_DEX_SUBTAG,
131 expectedNameHash, expectedContentHash);
132 }
133
134 @Test
135 public void testGeneratesEvents_unknownClassLoader() throws Exception {
136 File privateCopyFile = privateFile("copied2.jar");
137 String expectedNameHash =
138 "202158B6A3169D78F1722487205A6B036B3F2F5653FDCFB4E74710611AC7EB93";
139 String expectedContentHash = copyAndHashResource(
140 "/DynamicCodeLoggerTestLibrary.jar", privateCopyFile);
141
142 // This time make sure an unknown class loader is an ancestor of the class loader we use.
143 ClassLoader knownClassLoader = sContext.getClass().getClassLoader();
144 ClassLoader unknownClassLoader = new UnknownClassLoader(knownClassLoader);
145 ClassLoader loader =
146 new DexClassLoader(privateCopyFile.toString(), null, null, unknownClassLoader);
147 loader.loadClass("com.android.dcl.Simple");
148
149 // And make sure we log events about it
150 long previousEventNanos = mostRecentEventTimeNanos();
151 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
152
153 assertDclLoggedSince(previousEventNanos, DCL_DEX_SUBTAG,
154 expectedNameHash, expectedContentHash);
155 }
156
157 @Test
158 public void testGeneratesEvents_nativeLibrary() throws Exception {
159 new TestNativeCodeWithRetries() {
160 @Override
161 protected void loadNativeCode(int tryNumber) throws Exception {
162 // We need to use a different file name for each retry, because once a file is
163 // loaded, re-loading it has no effect.
164 String privateCopyName = "copied" + tryNumber + ".so";
165 File privateCopyFile = privateFile(privateCopyName);
166 mExpectedNameHash = hashOf(privateCopyName);
167 mExpectedContentHash = copyAndHashResource(
168 libraryPath("DynamicCodeLoggerNativeTestLibrary.so"), privateCopyFile);
169
170 System.load(privateCopyFile.toString());
171 }
172 }.runTest();
173 }
174
175 @Test
176 public void testGeneratesEvents_nativeLibrary_escapedName() throws Exception {
177 new TestNativeCodeWithRetries() {
178 @Override
179 protected void loadNativeCode(int tryNumber) throws Exception {
180 // A file name with a space will be escaped in the audit log; verify we un-escape it
181 // correctly.
182 String privateCopyName = "second copy " + tryNumber + ".so";
183 File privateCopyFile = privateFile(privateCopyName);
184 mExpectedNameHash = hashOf(privateCopyName);
185 mExpectedContentHash = copyAndHashResource(
186 libraryPath("DynamicCodeLoggerNativeTestLibrary.so"), privateCopyFile);
187
188 System.load(privateCopyFile.toString());
189 }
190 }.runTest();
191 }
192
193 @Test
194 public void testGeneratesEvents_nativeExecutable() throws Exception {
195 new TestNativeCodeWithRetries() {
196 @Override
197 protected void loadNativeCode(int tryNumber) throws Exception {
198 String privateCopyName = "test_executable" + tryNumber;
199 File privateCopyFile = privateFile(privateCopyName);
200 mExpectedNameHash = hashOf(privateCopyName);
201 mExpectedContentHash = copyAndHashResource(
202 "/DynamicCodeLoggerNativeExecutable", privateCopyFile);
203 assertThat(privateCopyFile.setExecutable(true)).isTrue();
204
205 Process process = Runtime.getRuntime().exec(privateCopyFile.toString());
206 int exitCode = process.waitFor();
207 assertThat(exitCode).isEqualTo(0);
208 }
209 }.runTest();
210 }
211
212 @Test
213 public void testGeneratesEvents_spoofed_validFile() throws Exception {
214 File privateCopyFile = privateFile("spoofed");
215
216 String expectedContentHash = copyAndHashResource(
217 "/DynamicCodeLoggerNativeExecutable", privateCopyFile);
218
219 EventLog.writeEvent(EventLog.getTagCode("auditd"),
220 "type=1400 avc: granted { execute_no_trans } "
221 + "path=\"" + privateCopyFile + "\" "
222 + "scontext=u:r:untrusted_app_27: "
223 + "tcontext=u:object_r:app_data_file: "
224 + "tclass=file ");
225
226 String expectedNameHash =
227 "1CF36F503A02877BB775DC23C1C5A47A95F2684B6A1A83B11795B856D88861E3";
228
229 // Run the job to scan generated audit log entries
230 runDynamicCodeLoggingJob(AUDIT_WATCHING_JOB_ID);
231
232 // And then make sure we log events about it
233 long previousEventNanos = mostRecentEventTimeNanos();
234 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
235
236 assertDclLoggedSince(previousEventNanos, DCL_NATIVE_SUBTAG,
237 expectedNameHash, expectedContentHash);
238 }
239
240 @Test
241 public void testGeneratesEvents_spoofed_validFile_untrustedApp() throws Exception {
242 File privateCopyFile = privateFile("spoofed2");
243
244 String expectedContentHash = copyAndHashResource(
245 "/DynamicCodeLoggerNativeExecutable", privateCopyFile);
246
247 EventLog.writeEvent(EventLog.getTagCode("auditd"),
248 "type=1400 avc: granted { execute_no_trans } "
249 + "path=\"" + privateCopyFile + "\" "
250 + "scontext=u:r:untrusted_app: "
251 + "tcontext=u:object_r:app_data_file: "
252 + "tclass=file ");
253
254 String expectedNameHash =
255 "3E57AA59249154C391316FDCF07C1D499C26A564E4D305833CCD9A98ED895AC9";
256
257 // Run the job to scan generated audit log entries
258 runDynamicCodeLoggingJob(AUDIT_WATCHING_JOB_ID);
259
260 // And then make sure we log events about it
261 long previousEventNanos = mostRecentEventTimeNanos();
262 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
263
264 assertDclLoggedSince(previousEventNanos, DCL_NATIVE_SUBTAG,
265 expectedNameHash, expectedContentHash);
266 }
267
268 @Test
269 public void testGeneratesEvents_spoofed_pathTraversal() throws Exception {
270 File privateDir = privateFile("x").getParentFile();
271
272 // Transform /a/b/c -> /a/b/c/../../.. so we get back to the root
273 File pathTraversalToRoot = privateDir;
274 File root = new File("/");
275 while (!privateDir.equals(root)) {
276 pathTraversalToRoot = new File(pathTraversalToRoot, "..");
277 privateDir = privateDir.getParentFile();
278 }
279
280 File spoofedFile = new File(pathTraversalToRoot, "dev/urandom");
281
282 assertWithMessage("Expected " + spoofedFile + " to be readable")
283 .that(spoofedFile.canRead()).isTrue();
284
285 EventLog.writeEvent(EventLog.getTagCode("auditd"),
286 "type=1400 avc: granted { execute_no_trans } "
287 + "path=\"" + spoofedFile + "\" "
288 + "scontext=u:r:untrusted_app_27: "
289 + "tcontext=u:object_r:app_data_file: "
290 + "tclass=file ");
291
292 String expectedNameHash =
293 "65528FE876BD676B0DFCC9A8ACA8988E026766F99EEC1E1FB48F46B2F635E225";
294
295 // Run the job to scan generated audit log entries
296 runDynamicCodeLoggingJob(AUDIT_WATCHING_JOB_ID);
297
298 // And then trigger generating DCL events
299 long previousEventNanos = mostRecentEventTimeNanos();
300 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
301
302 assertNoDclLoggedSince(previousEventNanos, DCL_NATIVE_SUBTAG, expectedNameHash);
303 }
304
305 @Test
306 public void testGeneratesEvents_spoofed_otherAppFile() throws Exception {
307 File ourPath = sContext.getDatabasePath("android_pay");
308 File targetPath = new File(ourPath.toString()
309 .replace("com.android.frameworks.dynamiccodeloggertest", "com.google.android.gms"));
310
311 assertWithMessage("Expected " + targetPath + " to not be readable")
312 .that(targetPath.canRead()).isFalse();
313
314 EventLog.writeEvent(EventLog.getTagCode("auditd"),
315 "type=1400 avc: granted { execute_no_trans } "
316 + "path=\"" + targetPath + "\" "
317 + "scontext=u:r:untrusted_app_27: "
318 + "tcontext=u:object_r:app_data_file: "
319 + "tclass=file ");
320
321 String expectedNameHash =
322 "CBE04E8AB9E7199FC19CBAAF9C774B88E56B3B19E823F2251693380AD6F515E6";
323
324 // Run the job to scan generated audit log entries
325 runDynamicCodeLoggingJob(AUDIT_WATCHING_JOB_ID);
326
327 // And then trigger generating DCL events
328 long previousEventNanos = mostRecentEventTimeNanos();
329 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
330
331 assertNoDclLoggedSince(previousEventNanos, DCL_NATIVE_SUBTAG, expectedNameHash);
332 }
333
334 // Abstract out the logic for running a native code loading test multiple times if needed and
335 // leaving time for audit messages to reach the log.
336 private abstract static class TestNativeCodeWithRetries {
337 String mExpectedContentHash;
338 String mExpectedNameHash;
339
340 abstract void loadNativeCode(int tryNumber) throws Exception;
341
342 final void runTest() throws Exception {
343 List<String> messages = null;
344
345 for (int i = 0; i < AUDIT_LOG_RETRIES; i++) {
346 loadNativeCode(i);
347
348 SystemClock.sleep(i * RETRY_DELAY_MS);
349
350 // Run the job to scan generated audit log entries
351 runDynamicCodeLoggingJob(AUDIT_WATCHING_JOB_ID);
352
353 // And then make sure we log events about it
354 long previousEventNanos = mostRecentEventTimeNanos();
355 runDynamicCodeLoggingJob(IDLE_LOGGING_JOB_ID);
356
357 messages = findMatchingEvents(
358 previousEventNanos, DCL_NATIVE_SUBTAG, mExpectedNameHash);
359 if (!messages.isEmpty()) {
360 break;
361 }
362 }
363
364 assertHasDclLog(messages, mExpectedContentHash);
365 }
366 }
367
368 private static File privateFile(String name) {
369 return new File(sContext.getDir("dcl", Context.MODE_PRIVATE), name);
370 }
371
372 private String libraryPath(final String libraryName) {
373 // This may be deprecated. but it tells us the ABI of this process which is exactly what we
374 // want.
375 return "/lib/" + Build.CPU_ABI + "/" + libraryName;
376 }
377
378 private static String copyAndHashResource(String resourcePath, File copyTo) throws Exception {
379 MessageDigest hasher = MessageDigest.getInstance(SHA_256);
380
381 // Copy the jar from our Java resources to a private data directory
382 Class<?> thisClass = DynamicCodeLoggerIntegrationTests.class;
383 try (InputStream input = thisClass.getResourceAsStream(resourcePath);
384 OutputStream output = new FileOutputStream(copyTo)) {
385 byte[] buffer = new byte[1024];
386 while (true) {
387 int numRead = input.read(buffer);
388 if (numRead < 0) {
389 break;
390 }
391 output.write(buffer, 0, numRead);
392 hasher.update(buffer, 0, numRead);
393 }
394 }
395
396 // Compute the SHA-256 of the file content so we can check that it is the same as the value
397 // we see logged.
398 return toHexString(hasher);
399 }
400
401 private String hashOf(String input) throws Exception {
402 MessageDigest hasher = MessageDigest.getInstance(SHA_256);
403 hasher.update(input.getBytes());
404 return toHexString(hasher);
405 }
406
407 private static String toHexString(MessageDigest hasher) {
408 Formatter formatter = new Formatter();
409 for (byte b : hasher.digest()) {
410 formatter.format("%02X", b);
411 }
412
413 return formatter.toString();
414 }
415
416 private static void runDynamicCodeLoggingJob(int jobId) throws Exception {
417 // This forces the DynamicCodeLoggingService job to start now.
418 runCommand("cmd jobscheduler run -f android " + jobId);
419 // Wait for the job to have run.
420 long startTime = SystemClock.elapsedRealtime();
421 while (true) {
422 String response = runCommand(
423 "cmd jobscheduler get-job-state android " + jobId);
424 if (!response.contains("pending") && !response.contains("active")) {
425 break;
426 }
427 // Don't wait forever - if it's taken > 10s then something is very wrong.
428 if (SystemClock.elapsedRealtime() - startTime > TimeUnit.SECONDS.toMillis(10)) {
429 throw new AssertionError("Job has not completed: " + response);
430 }
431 SystemClock.sleep(100);
432 }
433 }
434
435 private static String runCommand(String command) throws Exception {
436 ByteArrayOutputStream response = new ByteArrayOutputStream();
437 byte[] buffer = new byte[1000];
438 UiAutomation ui = InstrumentationRegistry.getInstrumentation().getUiAutomation();
439 ParcelFileDescriptor fd = ui.executeShellCommand(command);
440 try (InputStream input = new ParcelFileDescriptor.AutoCloseInputStream(fd)) {
441 while (true) {
442 int count = input.read(buffer);
443 if (count == -1) {
444 break;
445 }
446 response.write(buffer, 0, count);
447 }
448 }
449 return response.toString("UTF-8");
450 }
451
452 private static long mostRecentEventTimeNanos() throws Exception {
453 List<Event> events = readSnetEvents();
454 return events.isEmpty() ? 0 : events.get(events.size() - 1).getTimeNanos();
455 }
456
457 private static void assertDclLoggedSince(long previousEventNanos, String expectedSubTag,
458 String expectedNameHash, String expectedContentHash) throws Exception {
459 List<String> messages =
460 findMatchingEvents(previousEventNanos, expectedSubTag, expectedNameHash);
461
462 assertHasDclLog(messages, expectedContentHash);
463 }
464
465 private static void assertHasDclLog(List<String> messages, String expectedContentHash) {
466 assertWithMessage("Expected exactly one matching log entry").that(messages).hasSize(1);
467 assertThat(messages.get(0)).endsWith(expectedContentHash);
468 }
469
470 private static void assertNoDclLoggedSince(long previousEventNanos, String expectedSubTag,
471 String expectedNameHash) throws Exception {
472 List<String> messages =
473 findMatchingEvents(previousEventNanos, expectedSubTag, expectedNameHash);
474
475 assertWithMessage("Expected no matching log entries").that(messages).isEmpty();
476 }
477
478 private static List<String> findMatchingEvents(long previousEventNanos, String expectedSubTag,
479 String expectedNameHash) throws Exception {
480 List<String> messages = new ArrayList<>();
481
482 for (Event event : readSnetEvents()) {
483 if (event.getTimeNanos() <= previousEventNanos) {
484 continue;
485 }
486
487 Object data = event.getData();
488 if (!(data instanceof Object[])) {
489 continue;
490 }
491 Object[] fields = (Object[]) data;
492
493 // We only care about DCL events that we generated.
494 String subTag = (String) fields[0];
495 if (!expectedSubTag.equals(subTag)) {
496 continue;
497 }
498 int uid = (int) fields[1];
499 if (uid != sMyUid) {
500 continue;
501 }
502
503 String message = (String) fields[2];
504 if (!message.startsWith(expectedNameHash)) {
505 continue;
506 }
507
508 messages.add(message);
509 //assertThat(message).endsWith(expectedContentHash);
510 }
511 return messages;
512 }
513
514 private static List<Event> readSnetEvents() throws Exception {
515 List<Event> events = new ArrayList<>();
516 EventLog.readEvents(new int[] { SNET_TAG }, events);
517 return events;
518 }
519
520 /**
521 * A class loader that does nothing useful, but importantly doesn't extend BaseDexClassLoader.
522 */
523 private static class UnknownClassLoader extends ClassLoader {
524 UnknownClassLoader(ClassLoader parent) {
525 super(parent);
526 }
527 }
528 }