1 /*
2  * Copyright (C) 2016 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 android.app.admin;
18 
19 import android.annotation.IntDef;
20 import android.annotation.Nullable;
21 import android.annotation.TestApi;
22 import android.compat.annotation.UnsupportedAppUsage;
23 import android.content.ComponentName;
24 import android.os.Build;
25 import android.os.Parcel;
26 import android.os.Parcelable;
27 import android.os.SystemProperties;
28 import android.os.UserHandle;
29 import android.util.EventLog.Event;
30 
31 import java.io.IOException;
32 import java.lang.annotation.Retention;
33 import java.lang.annotation.RetentionPolicy;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Objects;
37 
38 /**
39  * Definitions for working with security logs.
40  *
41  * <p>Device owner apps can control the logging with
42  * {@link DevicePolicyManager#setSecurityLoggingEnabled}. When security logs are enabled, device
43  * owner apps receive periodic callbacks from {@link DeviceAdminReceiver#onSecurityLogsAvailable},
44  * at which time new batch of logs can be collected via
45  * {@link DevicePolicyManager#retrieveSecurityLogs}. {@link SecurityEvent} describes the type and
46  * format of security logs being collected.
47  */
48 public class SecurityLog {
49 
50     private static final String PROPERTY_LOGGING_ENABLED = "persist.logd.security";
51 
52     /** @hide */
53     @Retention(RetentionPolicy.SOURCE)
54     @IntDef(prefix = { "TAG_" }, value = {
55             TAG_ADB_SHELL_INTERACTIVE,
56             TAG_ADB_SHELL_CMD,
57             TAG_SYNC_RECV_FILE,
58             TAG_SYNC_SEND_FILE,
59             TAG_APP_PROCESS_START,
60             TAG_KEYGUARD_DISMISSED,
61             TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
62             TAG_KEYGUARD_SECURED,
63             TAG_OS_STARTUP,
64             TAG_OS_SHUTDOWN,
65             TAG_LOGGING_STARTED,
66             TAG_LOGGING_STOPPED,
67             TAG_MEDIA_MOUNT,
68             TAG_MEDIA_UNMOUNT,
69             TAG_LOG_BUFFER_SIZE_CRITICAL,
70             TAG_PASSWORD_EXPIRATION_SET,
71             TAG_PASSWORD_COMPLEXITY_SET,
72             TAG_PASSWORD_HISTORY_LENGTH_SET,
73             TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
74             TAG_MAX_PASSWORD_ATTEMPTS_SET,
75             TAG_KEYGUARD_DISABLED_FEATURES_SET,
76             TAG_REMOTE_LOCK,
77             TAG_USER_RESTRICTION_ADDED,
78             TAG_USER_RESTRICTION_REMOVED,
79             TAG_WIPE_FAILURE,
80             TAG_KEY_GENERATED,
81             TAG_KEY_IMPORT,
82             TAG_KEY_DESTRUCTION,
83             TAG_CERT_AUTHORITY_INSTALLED,
84             TAG_CERT_AUTHORITY_REMOVED,
85             TAG_CRYPTO_SELF_TEST_COMPLETED,
86             TAG_KEY_INTEGRITY_VIOLATION,
87             TAG_CERT_VALIDATION_FAILURE,
88             TAG_CAMERA_POLICY_SET,
89             TAG_PASSWORD_COMPLEXITY_REQUIRED
90     })
91     public @interface SecurityLogTag {}
92 
93     /** @hide */
94     @Retention(RetentionPolicy.SOURCE)
95     @IntDef(prefix = { "LEVEL_" }, value = {
96             LEVEL_INFO,
97             LEVEL_WARNING,
98             LEVEL_ERROR
99     })
100     public @interface SecurityLogLevel {}
101 
102     /**
103      * Indicates that an ADB interactive shell was opened via "adb shell".
104      * There is no extra payload in the log event.
105      */
106     public static final int TAG_ADB_SHELL_INTERACTIVE =
107             SecurityLogTags.SECURITY_ADB_SHELL_INTERACTIVE;
108 
109     /**
110      * Indicates that a shell command was issued over ADB via {@code adb shell <command>}
111      * The log entry contains a {@code String} payload containing the shell command, accessible
112      * via {@link SecurityEvent#getData()}. If security logging is enabled on organization-owned
113      * managed profile devices, the shell command will be redacted to an empty string.
114      */
115     public static final int TAG_ADB_SHELL_CMD = SecurityLogTags.SECURITY_ADB_SHELL_COMMAND;
116 
117     /**
118      * Indicates that a file was pulled from the device via the adb daemon, for example via
119      * {@code adb pull}. The log entry contains a {@code String} payload containing the path of the
120      * pulled file on the device, accessible via {@link SecurityEvent#getData()}.
121      */
122     public static final int TAG_SYNC_RECV_FILE = SecurityLogTags.SECURITY_ADB_SYNC_RECV;
123 
124     /**
125      * Indicates that a file was pushed to the device via the adb daemon, for example via
126      * {@code adb push}. The log entry contains a {@code String} payload containing the destination
127      * path of the pushed file, accessible via {@link SecurityEvent#getData()}.
128      */
129     public static final int TAG_SYNC_SEND_FILE = SecurityLogTags.SECURITY_ADB_SYNC_SEND;
130 
131     /**
132      * Indicates that an app process was started. The log entry contains the following
133      * information about the process encapsulated in an {@link Object} array, accessible via
134      * {@link SecurityEvent#getData()}:
135      * <li> [0] process name ({@code String})
136      * <li> [1] exact start time in milliseconds according to {@code System.currentTimeMillis()}
137      *      ({@code Long})
138      * <li> [2] app uid ({@code Integer})
139      * <li> [3] app pid ({@code Integer})
140      * <li> [4] seinfo tag ({@code String})
141      * <li> [5] SHA-256 hash of the base APK in hexadecimal ({@code String})
142      * If security logging is enabled on organization-owned managed profile devices, only events
143      * happening inside the managed profile will be visible.
144      */
145     public static final int TAG_APP_PROCESS_START = SecurityLogTags.SECURITY_APP_PROCESS_START;
146 
147     /**
148      * Indicates that keyguard has been dismissed. This event is only logged if the device
149      * has a secure keyguard. It is logged regardless of how keyguard is dismissed, including
150      * via PIN/pattern/password, biometrics or via a trust agent.
151      * There is no extra payload in the log event.
152      * @see #TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT
153      */
154     public static final int TAG_KEYGUARD_DISMISSED = SecurityLogTags.SECURITY_KEYGUARD_DISMISSED;
155 
156     /**
157      * Indicates that there has been an authentication attempt to dismiss the keyguard. The log
158      * entry contains the following information about the attempt encapsulated in an {@link Object}
159      * array, accessible via {@link SecurityEvent#getData()}:
160      * <li> [0] attempt result ({@code Integer}, 1 for successful, 0 for unsuccessful)
161      * <li> [1] strength of authentication method ({@code Integer}, 1 if strong authentication
162      *      method was used, 0 otherwise)
163      */
164     public static final int TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT =
165             SecurityLogTags.SECURITY_KEYGUARD_DISMISS_AUTH_ATTEMPT;
166 
167     /**
168      * Indicates that the device has been locked, either by the user or by a timeout. There is no
169      * extra payload in the log event.
170      */
171     public static final int TAG_KEYGUARD_SECURED = SecurityLogTags.SECURITY_KEYGUARD_SECURED;
172 
173     /**
174      * Indicates that the Android OS has started. The log entry contains the following information
175      * about the startup time software integrity check encapsulated in an {@link Object} array,
176      * accessible via {@link SecurityEvent#getData()}:
177      * <li> [0] Verified Boot state ({@code String})
178      * <li> [1] dm-verity mode ({@code String}).
179      * <p>Verified Boot state can be one of the following:
180      * <li> {@code green} indicates that there is a full chain of trust extending from the
181      * bootloader to verified partitions including the bootloader, boot partition, and all verified
182      * partitions.
183      * <li> {@code yellow} indicates that the boot partition has been verified using the embedded
184      * certificate and the signature is valid.
185      * <li> {@code orange} indicates that the device may be freely modified. Device integrity is
186      * left to the user to verify out-of-band.
187      * <p>dm-verity mode can be one of the following:
188      * <li> {@code enforcing} indicates that the device will be restarted when corruption is
189      * detected.
190      * <li> {@code eio} indicates that an I/O error will be returned for an attempt to read
191      * corrupted data blocks.
192      * <li> {@code disabled} indicates that integrity check is disabled.
193      * For details see Verified Boot documentation.
194      */
195     public static final int TAG_OS_STARTUP = SecurityLogTags.SECURITY_OS_STARTUP;
196 
197     /**
198      * Indicates that the Android OS has shutdown. There is no extra payload in the log event.
199      */
200     public static final int TAG_OS_SHUTDOWN = SecurityLogTags.SECURITY_OS_SHUTDOWN;
201 
202     /**
203      * Indicates start-up of audit logging. There is no extra payload in the log event.
204      */
205     public static final int TAG_LOGGING_STARTED = SecurityLogTags.SECURITY_LOGGING_STARTED;
206 
207     /**
208      * Indicates shutdown of audit logging. There is no extra payload in the log event.
209      */
210     public static final int TAG_LOGGING_STOPPED = SecurityLogTags.SECURITY_LOGGING_STOPPED;
211 
212     /**
213      * Indicates that removable media has been mounted on the device. The log entry contains the
214      * following information about the event, encapsulated in an {@link Object} array and
215      * accessible via {@link SecurityEvent#getData()}:
216      * <li> [0] mount point ({@code String})
217      * <li> [1] volume label ({@code String}). Redacted to empty string on organization-owned
218      *     managed profile devices.
219      */
220     public static final int TAG_MEDIA_MOUNT = SecurityLogTags.SECURITY_MEDIA_MOUNTED;
221 
222     /**
223      * Indicates that removable media was unmounted from the device. The log entry contains the
224      * following information about the event, encapsulated in an {@link Object} array and
225      * accessible via {@link SecurityEvent#getData()}:
226      * <li> [0] mount point ({@code String})
227      * <li> [1] volume label ({@code String}). Redacted to empty string on organization-owned
228      *     managed profile devices.
229      */
230     public static final int TAG_MEDIA_UNMOUNT = SecurityLogTags.SECURITY_MEDIA_UNMOUNTED;
231 
232     /**
233      * Indicates that the audit log buffer has reached 90% of its capacity. There is no extra
234      * payload in the log event.
235      */
236     public static final int TAG_LOG_BUFFER_SIZE_CRITICAL =
237             SecurityLogTags.SECURITY_LOG_BUFFER_SIZE_CRITICAL;
238 
239     /**
240      * Indicates that an admin has set a password expiration timeout. The log entry contains the
241      * following information about the event, encapsulated in an {@link Object} array and accessible
242      * via {@link SecurityEvent#getData()}:
243      * <li> [0] admin package name ({@code String})
244      * <li> [1] admin user ID ({@code Integer})
245      * <li> [2] target user ID ({@code Integer})
246      * <li> [3] new password expiration timeout in milliseconds ({@code Long}).
247      * @see DevicePolicyManager#setPasswordExpirationTimeout(ComponentName, long)
248      */
249     public static final int TAG_PASSWORD_EXPIRATION_SET =
250             SecurityLogTags.SECURITY_PASSWORD_EXPIRATION_SET;
251 
252     /**
253      * Indicates that an admin has set a requirement for password complexity. The log entry contains
254      * the following information about the event, encapsulated in an {@link Object} array and
255      * accessible via {@link SecurityEvent#getData()}:
256      * <li> [0] admin package name ({@code String})
257      * <li> [1] admin user ID ({@code Integer})
258      * <li> [2] target user ID ({@code Integer})
259      * <li> [3] minimum password length ({@code Integer})
260      * <li> [4] password quality constraint ({@code Integer})
261      * <li> [5] minimum number of letters ({@code Integer})
262      * <li> [6] minimum number of non-letters ({@code Integer})
263      * <li> [7] minimum number of digits ({@code Integer})
264      * <li> [8] minimum number of uppercase letters ({@code Integer})
265      * <li> [9] minimum number of lowercase letters ({@code Integer})
266      * <li> [10] minimum number of symbols ({@code Integer})
267      *
268      * @see DevicePolicyManager#setPasswordMinimumLength(ComponentName, int)
269      * @see DevicePolicyManager#setPasswordQuality(ComponentName, int)
270      * @see DevicePolicyManager#setPasswordMinimumLetters(ComponentName, int)
271      * @see DevicePolicyManager#setPasswordMinimumNonLetter(ComponentName, int)
272      * @see DevicePolicyManager#setPasswordMinimumLowerCase(ComponentName, int)
273      * @see DevicePolicyManager#setPasswordMinimumUpperCase(ComponentName, int)
274      * @see DevicePolicyManager#setPasswordMinimumNumeric(ComponentName, int)
275      * @see DevicePolicyManager#setPasswordMinimumSymbols(ComponentName, int)
276      */
277     public static final int TAG_PASSWORD_COMPLEXITY_SET =
278             SecurityLogTags.SECURITY_PASSWORD_COMPLEXITY_SET;
279 
280     /**
281      * Indicates that an admin has set a password history length. The log entry contains the
282      * following information about the event encapsulated in an {@link Object} array, accessible
283      * via {@link SecurityEvent#getData()}:
284      * <li> [0] admin package name ({@code String})
285      * <li> [1] admin user ID ({@code Integer})
286      * <li> [2] target user ID ({@code Integer})
287      * <li> [3] new password history length value ({@code Integer})
288      * @see DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)
289      */
290     public static final int TAG_PASSWORD_HISTORY_LENGTH_SET =
291             SecurityLogTags.SECURITY_PASSWORD_HISTORY_LENGTH_SET;
292 
293     /**
294      * Indicates that an admin has set a maximum screen lock timeout. The log entry contains the
295      * following information about the event encapsulated in an {@link Object} array, accessible
296      * via {@link SecurityEvent#getData()}:
297      * <li> [0] admin package name ({@code String})
298      * <li> [1] admin user ID ({@code Integer})
299      * <li> [2] target user ID ({@code Integer})
300      * <li> [3] new screen lock timeout in milliseconds ({@code Long})
301      * @see DevicePolicyManager#setMaximumTimeToLock(ComponentName, long)
302      */
303     public static final int TAG_MAX_SCREEN_LOCK_TIMEOUT_SET =
304             SecurityLogTags.SECURITY_MAX_SCREEN_LOCK_TIMEOUT_SET;
305 
306     /**
307      * Indicates that an admin has set a maximum number of failed password attempts before wiping
308      * data. The log entry contains the following information about the event encapsulated in an
309      * {@link Object} array, accessible via {@link SecurityEvent#getData()}:
310      * <li> [0] admin package name ({@code String})
311      * <li> [1] admin user ID ({@code Integer})
312      * <li> [2] target user ID ({@code Integer})
313      * <li> [3] new maximum number of failed password attempts ({@code Integer})
314      * @see DevicePolicyManager#setMaximumFailedPasswordsForWipe(ComponentName, int)
315      */
316     public static final int TAG_MAX_PASSWORD_ATTEMPTS_SET =
317             SecurityLogTags.SECURITY_MAX_PASSWORD_ATTEMPTS_SET;
318 
319     /**
320      * Indicates that an admin has set disabled keyguard features. The log entry contains the
321      * following information about the event encapsulated in an {@link Object} array, accessible via
322      * {@link SecurityEvent#getData()}:
323      * <li> [0] admin package name ({@code String})
324      * <li> [1] admin user ID ({@code Integer})
325      * <li> [2] target user ID ({@code Integer})
326      * <li> [3] disabled keyguard feature mask ({@code Integer}).
327      * @see DevicePolicyManager#setKeyguardDisabledFeatures(ComponentName, int)
328      */
329     public static final int TAG_KEYGUARD_DISABLED_FEATURES_SET =
330             SecurityLogTags.SECURITY_KEYGUARD_DISABLED_FEATURES_SET;
331 
332     /**
333      * Indicates that an admin remotely locked the device or profile. The log entry contains the
334      * following information about the event encapsulated in an {@link Object} array, accessible via
335      * {@link SecurityEvent#getData()}:
336      * <li> [0] admin package name ({@code String}),
337      * <li> [1] admin user ID ({@code Integer}).
338      * <li> [2] target user ID ({@code Integer})
339      */
340     public static final int TAG_REMOTE_LOCK = SecurityLogTags.SECURITY_REMOTE_LOCK;
341 
342     /**
343      * Indicates a failure to wipe device or user data. There is no extra payload in the log event.
344      */
345     public static final int TAG_WIPE_FAILURE = SecurityLogTags.SECURITY_WIPE_FAILED;
346 
347     /**
348      * Indicates that a cryptographic key was generated. The log entry contains the following
349      * information about the event, encapsulated in an {@link Object} array and accessible via
350      * {@link SecurityEvent#getData()}:
351      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
352      * <li> [1] alias of the key ({@code String})
353      * <li> [2] requesting process uid ({@code Integer}).
354      *
355      * If security logging is enabled on organization-owned managed profile devices, only events
356      * happening inside the managed profile will be visible.
357      */
358     public static final int TAG_KEY_GENERATED =
359             SecurityLogTags.SECURITY_KEY_GENERATED;
360 
361     /**
362      * Indicates that a cryptographic key was imported. The log entry contains the following
363      * information about the event, encapsulated in an {@link Object} array and accessible via
364      * {@link SecurityEvent#getData()}:
365      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
366      * <li> [1] alias of the key ({@code String})
367      * <li> [2] requesting process uid ({@code Integer}).
368      *
369      * If security logging is enabled on organization-owned managed profile devices, only events
370      * happening inside the managed profile will be visible.
371      */
372     public static final int TAG_KEY_IMPORT = SecurityLogTags.SECURITY_KEY_IMPORTED;
373 
374     /**
375      * Indicates that a cryptographic key was destroyed. The log entry contains the following
376      * information about the event, encapsulated in an {@link Object} array and accessible via
377      * {@link SecurityEvent#getData()}:
378      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
379      * <li> [1] alias of the key ({@code String})
380      * <li> [2] requesting process uid ({@code Integer}).
381      *
382      * If security logging is enabled on organization-owned managed profile devices, only events
383      * happening inside the managed profile will be visible.
384      */
385     public static final int TAG_KEY_DESTRUCTION = SecurityLogTags.SECURITY_KEY_DESTROYED;
386 
387     /**
388      * Indicates that a new root certificate has been installed into system's trusted credential
389      * storage. The log entry contains the following information about the event, encapsulated in an
390      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
391      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
392      * <li> [1] subject of the certificate ({@code String}).
393      * <li> [2] which user the certificate is installed for ({@code Integer}), only available from
394      *   version {@link android.os.Build.VERSION_CODES#R}.
395      *
396      * If security logging is enabled on organization-owned managed profile devices, only events
397      * happening inside the managed profile will be visible.
398      */
399     public static final int TAG_CERT_AUTHORITY_INSTALLED =
400             SecurityLogTags.SECURITY_CERT_AUTHORITY_INSTALLED;
401 
402     /**
403      * Indicates that a new root certificate has been removed from system's trusted credential
404      * storage. The log entry contains the following information about the event, encapsulated in an
405      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
406      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
407      * <li> [1] subject of the certificate ({@code String}).
408      * <li> [2] which user the certificate is removed from ({@code Integer}), only available from
409      *   version {@link android.os.Build.VERSION_CODES#R}.
410      *
411      * If security logging is enabled on organization-owned managed profile devices, only events
412      * happening inside the managed profile will be visible.
413      */
414     public static final int TAG_CERT_AUTHORITY_REMOVED =
415             SecurityLogTags.SECURITY_CERT_AUTHORITY_REMOVED;
416 
417     /**
418      * Indicates that an admin has set a user restriction. The log entry contains the following
419      * information about the event, encapsulated in an {@link Object} array and accessible via
420      * {@link SecurityEvent#getData()}:
421      * <li> [0] admin package name ({@code String})
422      * <li> [1] admin user ID ({@code Integer})
423      * <li> [2] user restriction ({@code String})
424      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
425      */
426     public static final int TAG_USER_RESTRICTION_ADDED =
427             SecurityLogTags.SECURITY_USER_RESTRICTION_ADDED;
428 
429     /**
430      * Indicates that an admin has removed a user restriction. The log entry contains the following
431      * information about the event, encapsulated in an {@link Object} array and accessible via
432      * {@link SecurityEvent#getData()}:
433      * <li> [0] admin package name ({@code String})
434      * <li> [1] admin user ID ({@code Integer})
435      * <li> [2] user restriction ({@code String})
436      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
437      */
438     public static final int TAG_USER_RESTRICTION_REMOVED =
439             SecurityLogTags.SECURITY_USER_RESTRICTION_REMOVED;
440 
441     /**
442      * Indicates that cryptographic functionality self test has completed. The log entry contains an
443      * {@code Integer} payload, indicating the result of the test (0 if the test failed, 1 if
444      * succeeded) and accessible via {@link SecurityEvent#getData()}.
445      */
446     public static final int TAG_CRYPTO_SELF_TEST_COMPLETED =
447             SecurityLogTags.SECURITY_CRYPTO_SELF_TEST_COMPLETED;
448 
449     /**
450      * Indicates a failed cryptographic key integrity check. The log entry contains the following
451      * information about the event, encapsulated in an {@link Object} array and accessible via
452      * {@link SecurityEvent#getData()}:
453      * <li> [0] alias of the key ({@code String})
454      * <li> [1] owner application uid ({@code Integer}).
455      *
456      * If security logging is enabled on organization-owned managed profile devices, only events
457      * happening inside the managed profile will be visible.
458      */
459     public static final int TAG_KEY_INTEGRITY_VIOLATION =
460             SecurityLogTags.SECURITY_KEY_INTEGRITY_VIOLATION;
461 
462     /**
463      * Indicates a failure to validate X.509v3 certificate. The log entry contains a {@code String}
464      * payload indicating the failure reason, accessible via {@link SecurityEvent#getData()}.
465      */
466     public static final int TAG_CERT_VALIDATION_FAILURE =
467             SecurityLogTags.SECURITY_CERT_VALIDATION_FAILURE;
468 
469     /**
470      * Indicates that the admin has set policy to disable camera.
471      * The log entry contains the following information about the event, encapsulated in an
472      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
473      * <li> [0] admin package name ({@code String})
474      * <li> [1] admin user ID ({@code Integer})
475      * <li> [2] target user ID ({@code Integer})
476      * <li> [3] whether the camera is disabled or not ({@code Integer}, 1 if it's disabled,
477      *      0 if enabled)
478      */
479     public static final int TAG_CAMERA_POLICY_SET =
480             SecurityLogTags.SECURITY_CAMERA_POLICY_SET;
481 
482     /**
483      * Indicates that an admin has set a password complexity requirement, using the platform's
484      * pre-defined complexity levels. The log entry contains the following information about the
485      * event, encapsulated in an {@link Object} array and accessible via
486      * {@link SecurityEvent#getData()}:
487      * <li> [0] admin package name ({@code String})
488      * <li> [1] admin user ID ({@code Integer})
489      * <li> [2] target user ID ({@code Integer})
490      * <li> [3] Password complexity ({@code Integer})
491      *
492      * @see DevicePolicyManager#setRequiredPasswordComplexity(int)
493      */
494     public static final int TAG_PASSWORD_COMPLEXITY_REQUIRED =
495             SecurityLogTags.SECURITY_PASSWORD_COMPLEXITY_REQUIRED;
496 
497     /**
498      * Event severity level indicating that the event corresponds to normal workflow.
499      */
500     public static final int LEVEL_INFO = 1;
501 
502     /**
503      * Event severity level indicating that the event may require admin attention.
504      */
505     public static final int LEVEL_WARNING = 2;
506 
507     /**
508      * Event severity level indicating that the event requires urgent admin action.
509      */
510     public static final int LEVEL_ERROR = 3;
511 
512     /**
513      * Returns if security logging is enabled. Log producers should only write new logs if this is
514      * true. Under the hood this is the logical AND of whether device owner exists and whether
515      * it enables logging by setting the system property {@link #PROPERTY_LOGGING_ENABLED}.
516      * @hide
517      */
isLoggingEnabled()518     public static native boolean isLoggingEnabled();
519 
520     /**
521      * @hide
522      */
setLoggingEnabledProperty(boolean enabled)523     public static void setLoggingEnabledProperty(boolean enabled) {
524         SystemProperties.set(PROPERTY_LOGGING_ENABLED, enabled ? "true" : "false");
525     }
526 
527     /**
528      * @hide
529      */
getLoggingEnabledProperty()530     public static boolean getLoggingEnabledProperty() {
531         return SystemProperties.getBoolean(PROPERTY_LOGGING_ENABLED, false);
532     }
533 
534     /**
535      * A class representing a security event log entry.
536      */
537     public static final class SecurityEvent implements Parcelable {
538         private Event mEvent;
539         private long mId;
540 
541         /**
542          * Constructor used by native classes to generate SecurityEvent instances.
543          * @hide
544          */
545         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
SecurityEvent(byte[] data)546         /* package */ SecurityEvent(byte[] data) {
547             this(0, data);
548         }
549 
550         /**
551          * Constructor used by Parcelable.Creator to generate SecurityEvent instances.
552          * @hide
553          */
SecurityEvent(Parcel source)554         /* package */ SecurityEvent(Parcel source) {
555             this(source.readLong(), source.createByteArray());
556         }
557 
558         /** @hide */
559         @TestApi
SecurityEvent(long id, byte[] data)560         public SecurityEvent(long id, byte[] data) {
561             mId = id;
562             mEvent = Event.fromBytes(data);
563         }
564 
565         /**
566          * Returns the timestamp in nano seconds when this event was logged.
567          */
getTimeNanos()568         public long getTimeNanos() {
569             return mEvent.getTimeNanos();
570         }
571 
572         /**
573          * Returns the tag of this log entry, which specifies entry's semantics.
574          */
getTag()575         public @SecurityLogTag int getTag() {
576             return mEvent.getTag();
577         }
578 
579         /**
580          * Returns the payload contained in this log entry or {@code null} if there is no payload.
581          */
getData()582         public Object getData() {
583             return mEvent.getData();
584         }
585 
586         /** @hide */
getIntegerData(int index)587         public int getIntegerData(int index) {
588             return (Integer) ((Object[]) mEvent.getData())[index];
589         }
590 
591         /** @hide */
getStringData(int index)592         public String getStringData(int index) {
593             return (String) ((Object[]) mEvent.getData())[index];
594         }
595 
596         /**
597          * @hide
598          */
setId(long id)599         public void setId(long id) {
600             this.mId = id;
601         }
602 
603         /**
604          * Returns the id of the event, where the id monotonically increases for each event. The id
605          * is reset when the device reboots, and when security logging is enabled.
606          */
getId()607         public long getId() {
608             return mId;
609         }
610 
611         /**
612          * Returns severity level for the event.
613          */
getLogLevel()614         public @SecurityLogLevel int getLogLevel() {
615             switch (getTag()) {
616                 case TAG_ADB_SHELL_INTERACTIVE:
617                 case TAG_ADB_SHELL_CMD:
618                 case TAG_SYNC_RECV_FILE:
619                 case TAG_SYNC_SEND_FILE:
620                 case TAG_APP_PROCESS_START:
621                 case TAG_KEYGUARD_DISMISSED:
622                 case TAG_KEYGUARD_SECURED:
623                 case TAG_OS_STARTUP:
624                 case TAG_OS_SHUTDOWN:
625                 case TAG_LOGGING_STARTED:
626                 case TAG_LOGGING_STOPPED:
627                 case TAG_MEDIA_MOUNT:
628                 case TAG_MEDIA_UNMOUNT:
629                 case TAG_PASSWORD_EXPIRATION_SET:
630                 case TAG_PASSWORD_COMPLEXITY_SET:
631                 case TAG_PASSWORD_HISTORY_LENGTH_SET:
632                 case TAG_MAX_SCREEN_LOCK_TIMEOUT_SET:
633                 case TAG_MAX_PASSWORD_ATTEMPTS_SET:
634                 case TAG_USER_RESTRICTION_ADDED:
635                 case TAG_USER_RESTRICTION_REMOVED:
636                 case TAG_CAMERA_POLICY_SET:
637                 case TAG_PASSWORD_COMPLEXITY_REQUIRED:
638                     return LEVEL_INFO;
639                 case TAG_CERT_AUTHORITY_REMOVED:
640                 case TAG_CRYPTO_SELF_TEST_COMPLETED:
641                     return getSuccess() ? LEVEL_INFO : LEVEL_ERROR;
642                 case TAG_CERT_AUTHORITY_INSTALLED:
643                 case TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT:
644                 case TAG_KEY_IMPORT:
645                 case TAG_KEY_DESTRUCTION:
646                 case TAG_KEY_GENERATED:
647                     return getSuccess() ? LEVEL_INFO : LEVEL_WARNING;
648                 case TAG_LOG_BUFFER_SIZE_CRITICAL:
649                 case TAG_WIPE_FAILURE:
650                 case TAG_KEY_INTEGRITY_VIOLATION:
651                     return LEVEL_ERROR;
652                 case TAG_CERT_VALIDATION_FAILURE:
653                     return LEVEL_WARNING;
654                 default:
655                     return LEVEL_INFO;
656             }
657         }
658 
659         // Success/failure if present is encoded as an integer in the first (0th) element of data.
getSuccess()660         private boolean getSuccess() {
661             final Object data = getData();
662             if (data == null || !(data instanceof Object[])) {
663                 return false;
664             }
665 
666             final Object[] array = (Object[]) data;
667             return array.length >= 1 && array[0] instanceof Integer && (Integer) array[0] != 0;
668         }
669 
670         /**
671          * Returns a copy of the security event suitable to be consumed by the provided user.
672          * This method will either return the original event itself if the event does not contain
673          * any sensitive data; or a copy of itself but with sensitive information redacted; or
674          * {@code null} if the entire event should not be accessed by the given user.
675          *
676          * @param accessingUser which user this security event is to be accessed, must be a
677          *     concrete user id.
678          * @hide
679          */
redact(int accessingUser)680         public SecurityEvent redact(int accessingUser) {
681             // Which user the event is associated with, for the purpose of log redaction.
682             final int userId;
683             switch (getTag()) {
684                 case SecurityLog.TAG_ADB_SHELL_CMD:
685                     return new SecurityEvent(getId(), mEvent.withNewData("").getBytes());
686                 case SecurityLog.TAG_MEDIA_MOUNT:
687                 case SecurityLog.TAG_MEDIA_UNMOUNT:
688                     // Partial redaction
689                     String mountPoint;
690                     try {
691                         mountPoint = getStringData(0);
692                     } catch (Exception e) {
693                         return null;
694                     }
695                     return new SecurityEvent(getId(),
696                             mEvent.withNewData(new Object[] {mountPoint, ""}).getBytes());
697                 case SecurityLog.TAG_APP_PROCESS_START:
698                     try {
699                         userId = UserHandle.getUserId(getIntegerData(2));
700                     } catch (Exception e) {
701                         return null;
702                     }
703                     break;
704                 case SecurityLog.TAG_CERT_AUTHORITY_INSTALLED:
705                 case SecurityLog.TAG_CERT_AUTHORITY_REMOVED:
706                     try {
707                         userId = getIntegerData(2);
708                     } catch (Exception e) {
709                         return null;
710                     }
711                     break;
712                 case SecurityLog.TAG_KEY_GENERATED:
713                 case SecurityLog.TAG_KEY_IMPORT:
714                 case SecurityLog.TAG_KEY_DESTRUCTION:
715                     try {
716                         userId = UserHandle.getUserId(getIntegerData(2));
717                     } catch (Exception e) {
718                         return null;
719                     }
720                     break;
721                 case SecurityLog.TAG_KEY_INTEGRITY_VIOLATION:
722                     try {
723                         userId = UserHandle.getUserId(getIntegerData(1));
724                     } catch (Exception e) {
725                         return null;
726                     }
727                     break;
728                 default:
729                     userId = UserHandle.USER_NULL;
730             }
731             // If the event is not user-specific, or matches the accessing user, return it
732             // unmodified, else redact by returning null
733             if (userId == UserHandle.USER_NULL || accessingUser == userId) {
734                 return this;
735             } else {
736                 return null;
737             }
738         }
739 
740         @Override
describeContents()741         public int describeContents() {
742             return 0;
743         }
744 
745         @Override
writeToParcel(Parcel dest, int flags)746         public void writeToParcel(Parcel dest, int flags) {
747             dest.writeLong(mId);
748             dest.writeByteArray(mEvent.getBytes());
749         }
750 
751         public static final @android.annotation.NonNull Parcelable.Creator<SecurityEvent> CREATOR =
752                 new Parcelable.Creator<SecurityEvent>() {
753             @Override
754             public SecurityEvent createFromParcel(Parcel source) {
755                 return new SecurityEvent(source);
756             }
757 
758             @Override
759             public SecurityEvent[] newArray(int size) {
760                 return new SecurityEvent[size];
761             }
762         };
763 
764         /**
765          * @hide
766          */
767         @Override
equals(@ullable Object o)768         public boolean equals(@Nullable Object o) {
769             if (this == o) return true;
770             if (o == null || getClass() != o.getClass()) return false;
771             SecurityEvent other = (SecurityEvent) o;
772             return mEvent.equals(other.mEvent) && mId == other.mId;
773         }
774 
775         /**
776          * @hide
777          */
778         @Override
hashCode()779         public int hashCode() {
780             return Objects.hash(mEvent, mId);
781         }
782 
783         /** @hide */
eventEquals(SecurityEvent other)784         public boolean eventEquals(SecurityEvent other) {
785             return other != null && mEvent.equals(other.mEvent);
786         }
787     }
788 
789     /**
790      * Redacts events in-place according to which user will consume the events.
791      *
792      * @param accessingUser which user will consume the redacted events, or UserHandle.USER_ALL if
793      *     redaction should be skipped.
794      * @hide
795      */
redactEvents(ArrayList<SecurityEvent> logList, int accessingUser)796     public static void redactEvents(ArrayList<SecurityEvent> logList, int accessingUser) {
797         if (accessingUser == UserHandle.USER_ALL) return;
798         int end = 0;
799         for (int i = 0; i < logList.size(); i++) {
800             SecurityEvent event = logList.get(i);
801             event = event.redact(accessingUser);
802             if (event != null) {
803                 logList.set(end, event);
804                 end++;
805             }
806         }
807         for (int i = logList.size() - 1; i >= end; i--) {
808             logList.remove(i);
809         }
810     }
811 
812     /**
813      * Retrieve all security logs and return immediately.
814      * @hide
815      */
readEvents(Collection<SecurityEvent> output)816     public static native void readEvents(Collection<SecurityEvent> output) throws IOException;
817 
818     /**
819      * Retrieve all security logs since the given timestamp in nanoseconds and return immediately.
820      * @hide
821      */
readEventsSince(long timestamp, Collection<SecurityEvent> output)822     public static native void readEventsSince(long timestamp, Collection<SecurityEvent> output)
823             throws IOException;
824 
825     /**
826      * Retrieve all security logs before the last reboot. May return corrupted data due to
827      * unreliable pstore.
828      * @hide
829      */
readPreviousEvents(Collection<SecurityEvent> output)830     public static native void readPreviousEvents(Collection<SecurityEvent> output)
831             throws IOException;
832 
833     /**
834      * Retrieve all security logs whose timestamp is equal to or greater than the given timestamp in
835      * nanoseconds. This method will block until either the last log earlier than the given
836      * timestamp is about to be pruned, or after a 2-hour timeout has passed.
837      * @hide
838      */
readEventsOnWrapping(long timestamp, Collection<SecurityEvent> output)839     public static native void readEventsOnWrapping(long timestamp, Collection<SecurityEvent> output)
840             throws IOException;
841 
842     /**
843      * Write a log entry to the underlying storage, with a string payload.
844      * @hide
845      */
writeEvent(int tag, String str)846     public static native int writeEvent(int tag, String str);
847 
848     /**
849      * Write a log entry to the underlying storage, with several payloads.
850      * Supported types of payload are: integer, long, float, string plus array of supported types.
851      * @hide
852      */
writeEvent(int tag, Object... payloads)853     public static native int writeEvent(int tag, Object... payloads);
854 }
855