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